Chapter 06 / 24 · System Design

Where the data actually lives

Orders, menus, rider locations and photos behave differently. We open the two common storage engines and give each data set the home that fits it.

So far the database has been a box behind the cache. This chapter opens it, because Dabba has several kinds of data that behave very differently, and putting them all in one store is how a reasonable system ends up with an unreasonable outage. Orders involve money and must never be lost. Menus are read thousands of times a second and edited a few times a day. Rider locations arrive ten thousand times a second and are worthless after a minute. Photos are large files that are never edited.

We will describe each kind of data by how it is used, look inside the two engine designs that most databases are built on, follow what happened when one kind of data was put in the wrong one, and end with a written decision for each data set that another engineer could challenge.

Describe each data set by how it is used

Database products are easier to choose once the data has been described in terms that do not mention any product: how big it is, how fast it is written, how it is read, and what a lost or wrong write costs.

DataSize and growthWrites at peakHow it is readCost of a lost write
Orders and order items~2 GB a day, ~730 GB a year~150 inserts and ~250 status changes a secondby order ID; a customer’s recent orders; a restaurant’s active ordersmoney and trust
Restaurants and menus~2 GB in total, slow growtha few edits a secondwhole menu by restaurant, almost always through a cachean edit the owner has to repeat
Rider latest location50,000 rows, constant10,000 overwrites a secondriders near a point; one rider’s positionalmost none; a new one arrives in 5 s
Rider location history~86 GB a day (10,000 a second × ~100 bytes)10,000 appends a secondone rider over a time range, for disputes and analysissmall; a gap in a trace
Dish photosmillions of files, terabytesuploads, rareby URL, through the CDNa restaurant re-uploads

The table already separates the data into groups. Orders need transactions that cover several rows (the order, its items, the stock it takes, the idempotency key) and they need flexible queries, because support staff will ask questions nobody planned for. Rider locations need a very high rate of tiny writes with almost no durability requirement. Photos need cheap storage for large immutable blobs. These are three different shapes, and they will get three different homes.

Inside a B-tree database

Postgres and MySQL, like most relational databases, store tables and indexes in fixed size pages (8 KB in Postgres) and organise each index as a B-tree: a shallow, wide tree of pages in which each internal page points to hundreds of children. An index on an 8-byte order ID fits roughly 400 entries in a page, so three levels address about 400³ = 64 million rows and four levels about 25 billion. Dabba’s 365 million orders a year sit four levels deep, and the top levels are read so often that they are always in memory. Finding an order by ID costs at most one or two page reads from disk.

Durability comes from the write-ahead log. Before a change is applied to the pages, it is appended to a log file and the log is flushed to disk; only then does the commit succeed. The pages themselves are written back later, in the background. If the machine crashes, the database replays the log on restart. Appending to a log is sequential and fast, which is why a single commit can take well under a millisecond on good disks, and why many commits can share one flush when they arrive together.

Postgres adds one more behaviour that matters for Dabba. An update does not overwrite the row; it writes a new version of the row and leaves the old version for concurrent readers, to be cleaned up later by a background process called vacuum. Every index on the table normally needs a new entry pointing at the new version too. Postgres avoids that cost with a heap-only tuple (HOT) update when two conditions hold: no indexed column changed, and the new version fits on the same page as the old one. Then only the table page changes, not the indexes.

Each Dabba order changes status about six times. If status is not part of any index and pages have some free space (set by the table’s fill factor, say 90% to leave a tenth of each page empty), most of those changes are HOT updates and cheap. If status is indexed, every change writes new entries into every index on the table. At about 250 status changes a second, Postgres handles either case. At forty times that rate it would not, which is what the next section is about.

B-tree · read-optimisedrootleaf pages · updated in placeread: one descent · write: in placeLSM · write-optimisedmemtable · append, in RAML0 · flushed runsL1 · merged, sortedL2 · older, largerwrite: append · read: newest level firstsame data, opposite bets — pick by the workload’s read/write mix
Fig 1 · Two engine designs. A B-tree updates pages in place behind a log; an LSM tree appends and merges later

Inside an LSM engine

The other common design, the log-structured merge tree, never modifies data in place. RocksDB, Cassandra, ScyllaDB and many time-series stores use it. A write goes to the log for durability and into a sorted structure in memory called the memtable. When the memtable fills, it is written to disk as an immutable sorted file. Over time there are many such files, so a background process called compaction merges them into fewer, larger ones, discarding overwritten and deleted values along the way.

Writes are fast because they are always sequential: append to the log, insert into memory, and later write whole sorted files. Reads pay for it. A key might be in the memtable or in any of several files, newest first, so each file carries a Bloom filter, a compact structure that can say “this key is definitely not in this file” and so skip most of them. Compaction pays too: each byte may be rewritten many times as files are merged into larger ones (with leveled compaction, ten or more times over its life is common), which costs disk bandwidth that the foreground workload does not see directly until compaction falls behind.

The two designs make opposite bets. A B-tree spends effort at write time to keep data in one sorted place, so reads are predictable. An LSM tree defers that effort to background merging, so writes are cheap and reads may look in several places. For a workload of many small appends, such as 10,000 location points a second keyed by rider and time, the LSM bet fits. For a workload of transactions that read and update a few related rows, such as placing an order, the B-tree bet fits, along with everything a relational database offers on top.

The week rider locations lived in the orders database

Here is how the wrong choice plays out. It is a common path, because the first version of a feature tends to go wherever the existing database is.

Dabba’s first rider app sends a location every 5 seconds, and the team stores it in a rider_locations table in the main Postgres database, one row per rider, updated in place, with a spatial index on the location so dispatch can find riders near a restaurant. At launch there are 2,000 riders online, 400 updates a second, and nothing is wrong.

By the dinner peak a year later there are 50,000 riders online and 10,000 updates a second. Every update changes the indexed location column, so none of them is a HOT update: each writes a new row version and a new entry in the spatial index. The table has 50,000 live rows, but it accumulates 10,000 dead row versions a second, about 36 million an hour. Vacuum, with settings tuned for the orders table, falls behind. The spatial index fills with entries for dead versions, so the “riders near this restaurant” query, which dispatch runs for every order, reads far more pages than it should and slows from a few milliseconds to hundreds.

The damage spreads beyond dispatch. All those updates go through the write-ahead log, which also feeds the read replicas. Replicas apply the log in a single process, and during the peak they begin to fall behind. The reads chapter sent menu rebuilds to replicas, so restaurant owners now see their edits appear minutes late. Order placement shares the primary’s disk and log with the location updates, and its p99 rises. A feature whose individual writes are nearly worthless is now degrading the writes that carry money.

The fix moves each part of the location data to a store shaped like it. The latest position of each rider goes into Redis, which keeps data in memory, overwrites a value in place without leaving old versions behind, and has commands for indexing points and searching by radius. 10,000 small writes a second is a light load for it. The history goes onto an append-only stream and from there into a store built for time-ordered appends; the streams and geo chapters later in the course build both properly.

The fix has costs worth writing down. If the Redis node restarts, Dabba has no rider positions for about 5 seconds until the next updates arrive, and dispatch must cope with that. Assigning a rider can no longer happen in the same transaction as reading the rider’s location, so dispatch must tolerate a position that is a few seconds old. And the team now operates one more system. Each of these is a better trade than having location updates degrade order placement.

Predict first

Orders grow by about 2 GB a day. Counting indexes, how long until the orders database outgrows one Postgres primary, and is storage really the first limit Dabba will hit?

Show the worked answer

With indexes, roughly double the raw size: about 1.5 TB a year. Servers with several terabytes of fast local or attached storage are ordinary, so storage alone allows several years. Writes are also within reach: about 150 inserts and 250 status changes a second at peak is a modest load for one primary.

A less visible limit arrives first: recovery time. If the database must be restored from backup, say after an operator error that the standby faithfully copied, then restoring 5 TB at about 500 MB a second takes (5 × 10¹²) / (5 × 10⁸) = 10,000 seconds, close to three hours, before replaying the log since the backup. If Dabba’s target is to recover within an hour, it is breached long before the disk is full. That is an argument for partitioning orders by month, so that old months can be moved to cheaper storage and the live database stays small, well before anyone talks about sharding.

Indexes for the queries Dabba actually runs

An index is a second sorted copy of some columns, pointing back at the rows. It makes the queries that match its order fast, and it makes every insert, and every update that touches its columns, do one more write. So indexes should be chosen from the queries, one at a time. Dabba’s order database has three main ones.

Finding an order by ID uses the primary key. Showing a customer’s recent orders runs this query:

SELECT order_id, restaurant_name, total_paise, status, created_at
FROM orders
WHERE customer_id = $1
ORDER BY created_at DESC
LIMIT 20;

CREATE INDEX orders_by_customer ON orders (customer_id, created_at DESC);

Column order in that index matters. Sorted by customer first and then by time, the index holds each customer’s orders together and already in time order, so the database reads the first 20 entries for that customer and stops. An index on (created_at, customer_id) holds the same columns in an order that does not help: one customer’s orders are scattered across the whole time range. The query plan, shown by EXPLAIN, confirms which happened; an “Index Scan using orders_by_customer” with no separate sort step is what we want to see.

The restaurant tablet asks for that restaurant’s active orders every few seconds. Out of hundreds of millions of orders only about 88,000 are active at peak, so a partial index that covers only active orders stays small and stays in memory:

CREATE INDEX active_by_restaurant ON orders (restaurant_id, created_at)
  WHERE status IN ('PLACED', 'ACCEPTED', 'PREPARING', 'READY');

This index has a cost we met above: status now appears in an index definition, so status changes are no longer HOT updates. At 250 changes a second, Dabba accepts that. What it does not do is index status on its own: with a handful of possible values and most rows “delivered”, such an index would rarely be cheaper than reading the table, and the query planner would rightly ignore it while every write still paid for it.

Each index makes every insert into orders do one more B-tree insert. With a primary key and the two indexes above, an order insert touches three trees. A team that adds an index for every report someone asks for will find, a year later, that order inserts touch ten. Reports belong in the analytics store; the order database keeps the indexes that live features need.

The decisions, written down

DataStoreWhy it fitsWhat we give up
Orders, payments state, idempotency keysPostgres, a synchronous standby in another zone, asynchronous read replicastransactions across several rows; flexible queries for support; mature toolingone primary’s write capacity; growth by bigger machines until sharding
Restaurants and menusPostgres (a separate database), cached in Redis and at the CDNrelational structure; edits are small transactions; reads go to cachesa cache layer to operate and keep correct
Rider latest locationRedis with a geospatial indexin-place overwrites in memory; radius searcha few seconds of blindness after a restart; no transactions with orders
Rider location historyappend-only stream into an LSM-based or time-series storesequential appends; reads by rider and time rangeupdates and deletes are awkward; compaction to watch
Dish photosobject storage behind the CDN, metadata in Postgrescheap, durable storage for large immutable filesno queries over contents
Analytics: payouts, demand, reportscolumn store fed from the othersscans a few columns across millions of rows quicklynot suitable for live lookups

The first row deserves one sentence in full: we store orders in Postgres because placing an order must change several rows atomically and support needs queries we cannot predict; we accept a single primary’s write capacity; and we will revisit when the write rate approaches what one primary sustains at peak, or when orders must be written in more than one region.

The synchronous standby is part of that decision. With it, a commit waits until the standby in another zone has the log record as well, which adds roughly a millisecond inside a region. In exchange, if the primary’s machine or zone fails, no committed order is lost when the standby takes over. For orders that millisecond is cheap. For rider locations it would be pointless, which is one more reason they live elsewhere.

When to reach past Postgres

A common mistake runs in the other direction: choosing a distributed key-value store for orders on day one because it scales. At 150 orders a second it buys capacity Dabba does not need and costs things it does: multi-row transactions, ad hoc queries for support, and joins for the restaurant’s daily statement. A store like that becomes the right choice when write rates exceed what a single primary can sustain after reasonable vertical growth, when data must be written in several regions at once, or when the access patterns are few, stable and known. None of these holds for Dabba’s orders yet. The sharding chapter picks up the moment one of them does.

We should revisit these choices when a data set’s row in the first table changes: a tenfold rise in order volume, a new requirement to keep rider traces for years, or a feature that reads menus in a new way, such as searching dishes across all restaurants, which no B-tree index on the menu tables will serve well (the derived data chapter builds a search index for it).

We now know where orders and menus live. We have not yet decided their shape: which tables, which columns, and which facts an order copies rather than references. The next chapter, Data modelling across paradigms, designs that shape, and shows why an order from last month must not change when the restaurant changes its prices.