Chapter 09 / 24 · System Design

Sharding and partitioning

Dabba’s orders outgrow one database. Choosing the shard key decides which queries stay on one machine and which must ask them all.

Sharding splits one table across several databases so that each holds a slice and the slices together hold everything. It lets a dataset keep growing after one machine has stopped being enough. The price is that a query which used to be one lookup may now have to ask every slice, and the shard key you choose decides which queries pay that price.

The writes chapter ended on an assumption: one Postgres primary sees every order. The storage chapter named the conditions for revisiting it, a write rate approaching what one primary sustains or a tenfold rise in volume. This chapter starts on the day those conditions come into view. Dabba takes about 1 million orders a day today, and the plan for its expansion to more cities calls for about ten times that. One Postgres primary for orders is no longer enough for that plan, and this chapter works out why, what to split on, and how to change our minds later without a week of downtime.

What actually outgrows the database

The common story is that the database runs out of write throughput. It is worth checking against Dabba’s numbers before believing it, first for today and then for the plan. By the brief from the first chapter, the dinner hour carries about 42 orders a second on average, with spikes of two to three times, and the order path is designed for 150 orders a second.

An order is not one write. Placing it inserts the order, its items, a stock reservation, an idempotency key and an outbox row in one transaction, and then it goes through about six status changes, each its own small transaction that also appends to order_events. Call it seven commits and about fifteen row writes per order. At the design target of 150 orders a second that is about 1,000 commits and 2,250 row writes a second, each commit waiting for the synchronous standby. A well-tuned Postgres primary handles that comfortably. Today, throughput does not force a split, which is what the storage chapter concluded too.

Now multiply by ten. The design target becomes 1,500 orders a second at the dinner spike: about 10,500 commits and 22,500 row writes a second, every commit waiting a network round trip for the standby in another zone, and three or more index updates per insert. That is no longer a comfortable load for one primary; it is the kind of number teams reach by heroic tuning and then spend every dinner hour watching. Size grows the same way. At about 4 GB a day including indexes today, ten times the orders is about 40 GB a day, close to 15 TB a year.

Three things go wrong at that scale, and only the first shows up in a throughput benchmark. The first is commit capacity, above. The second is recovery time. The storage chapter’s monthly partitioning keeps only recent months in the live database, but even 90 days at ten times today’s volume is about 3.6 TB, and restoring that at about 500 MB a second takes two hours before any write-ahead log is replayed. The third is blast radius. One primary means one bad migration, one runaway query or one failed disk stops every city at dinner time.

So the decision we are about to write down is not only “we need more write throughput”. It is closer to “no single database should carry more than a fraction of dinner commits, hold more hot data than we can restore in well under an hour, or stop every city when it fails”. That sentence also tells us how many shards to start with. Eight shards at the tenfold target means about 1,300 commits a second and about 450 GB of hot data each, restorable in roughly 15 minutes. We build for eight, knowing that today each of them will be lightly loaded.

List the questions before choosing the key

A shard key is the column whose value decides which database a row lives in. A query that includes the key goes to one shard. A query that does not must ask all of them and merge the answers, which is called scatter-gather. So before choosing the key we list how the orders table is actually read, and how often.

QuestionWho asksRough rate at dinner peakFreshness needed
Active orders for this restaurantRestaurant tablet~20,000 open restaurants refreshing every 10 s: ~2,000/s today, growing with every new restaurantA second or two; a missed order is lost money
This order, by idCustomer status page, rider app, supportAround a thousand/sImmediate
My past ordersCustomer appA few hundred/sSeconds of lag are fine
Orders per city in the last 15 minutesOperations dashboardA handful/sA minute is fine
Restaurant earnings for last monthRestaurant owner, financeLowHours are fine

Two rows dominate: the restaurant tablet and the lookup by order id. The tablet is both the highest rate and the one with the least tolerance for staleness. Whatever key we choose has to keep that query on one shard.

Predict first

Suppose we shard orders by city: all Bengaluru orders on one database, all Mumbai orders on another, and so on. It is 20:30 on the night of a cricket final, and Bengaluru carries 30% of all orders. What happens to the Bengaluru shard, and what can we do about it without changing the key?

Show the worked answer

The Bengaluru shard takes 30% of all writes and reads while the Ahmedabad shard is nearly idle. With eight shards the fair share would be 12.5%, so Bengaluru runs at well over twice the load we sized each database for.

Without changing the key, the options are thin. We can give Bengaluru a bigger machine, which buys time but is the vertical scaling we were trying to leave behind. We cannot split Bengaluru across two databases, because the key has only one value for the whole city: every Bengaluru order maps to the same place. Any split inside a city means a new key, such as city plus restaurant, and that is a migration.

Three candidate keys, one dinner peak

City is the tempting key because it matches how the business thinks. Most queries are local, an order’s customer, restaurant and rider are almost always in the same city, and operations dashboards become single-shard. The trouble is granularity. A key with fifty values can never spread load more evenly than the cities themselves are spread, and Dabba’s cities are very uneven.

shard key = cityBLR30%MUM22%DEL14%HYD10%PUN8%CHE6%KOL5%AMD5%shard key = hash(restaurant_id)s013%s112%s212.5%s313%s412%s512.5%s612%s713%dashed line · what one database handles comfortably at the dinner peak
Share of dinner-peak writes per shard. Sharding by city leaves the Bengaluru shard carrying 30%; hashing the restaurant id spreads the same load almost evenly.

Customer id spreads load well, since there are millions of customers and none of them orders very much. “My past orders” becomes a single-shard query. But the restaurant tablet, our hottest query, now has to ask every shard, because one restaurant’s orders come from customers spread everywhere. At 2,000 tablet refreshes a second and eight shards, that is 16,000 shard queries a second to answer what used to be 2,000, and both numbers grow with the restaurant count.

The extra load is not even the worst part. A scatter-gather request is as slow as its slowest shard. If each shard answers within 20 ms 99% of the time, the chance that all eight answer within 20 ms is 0.99 to the power 8, about 92%. So 8% of tablet refreshes see at least one shard’s worst-case latency, compared with 1% before. Add shards and it gets worse: with 16 shards it is 15%.

Restaurant id, hashed, keeps the tablet query on one shard, because every order belongs to exactly one restaurant. There are about 50,000 restaurants, so hashing spreads them evenly, and even the busiest outlet takes a few hundred orders on a busy evening, which no shard notices. The lookup by order id can also stay single-shard if the order id itself carries the shard number; the chapter on IDs builds exactly that.

Shard keyStays on one shardBecomes scatter-gatherSkew at the dinner peak
CityTablet, city dashboard, most order lookupsCustomers who order in two citiesSevere; Bengaluru cannot be split
Customer id (hashed)My past ordersRestaurant tablet, the hottest readLow
Restaurant id (hashed)Tablet, restaurant earnings, order by id if the id encodes the shardMy past orders, city dashboardLow; one outlet is tiny next to a shard
Order id (hashed)Order by idEverything elseNone, and nothing else works well

So we write the decision down in a form someone could argue with: we shard orders by a hash of restaurant_id, because the restaurant tablet is the highest-rate read with the tightest freshness need, and every order belongs to exactly one restaurant. Customer history, which tolerates seconds of lag, will be served from a separate copy keyed by customer_id. That last clause is a promise the derived-data chapter has to keep.

Notice what the key also decided about the product. An order from two restaurants at once, a combined cart, would now span two shards and need a cross-shard transaction. That is not impossible, but it means the product team’s idea for “add a dessert from the place next door” now has an infrastructure cost attached. The shard key is a product decision; it is better that the product people hear about it now.

Logical shards, so we only choose the number once

The obvious way to map a key to a shard is hash(restaurant_id) mod N. It works until N changes. Going from 8 to 9 databases, a key stays where it was only if its hash gives the same remainder for 8 and for 9, which is true for about one key in nine. The other eight in nine of all orders would have to move at once.

ABCD · newa key hashes to a point on the ring andbelongs to the next node clockwiseD arriving claims only the marked arc —~1/N of keys move; the rest stay putvs hash(key) mod N: nearly every key movesvirtual nodes: each machine owns many smallarcs, smoothing load and rebalancing
Consistent hashing places keys and nodes on a ring. A new node takes over one arc, so roughly 1/N of keys move instead of nearly all of them.

Consistent hashing is one fix: keys and nodes sit on a ring, and adding a node moves only the arc it takes over. Key-value stores like Cassandra and DynamoDB work this way. Teams sharding a relational database more often use a simpler arrangement with the same effect, called logical shards.

We fix a large number of logical shards up front and never change it. Dabba uses 8,192. A restaurant’s logical shard is computed from its id, and because 8,192 never changes, the answer for a given restaurant never changes either. A small mapping table then says which physical database holds each logical shard. On day one, eight databases each hold 1,024 logical shards. Adding a ninth means moving some logical shards to it, one at a time, and updating the map.

How the logical shard is computed deserves one deliberate decision. The plain choice, hash(restaurant_id) mod 8192, scatters every city across every logical shard, so logical shard 3,071 holds a few restaurants from Bengaluru, Pune and Kolkata. That is harmless inside one region and becomes a wall later: when Dabba wants to serve each city from a home region, as the multi-region chapter does, no logical shard can move without dragging other cities with it. So Dabba gives each city its own block of logical shards, sized to its expected share (Bengaluru gets 2,048, a new city 64, with room left unallocated for cities not yet launched), and hashes restaurants within their city’s block: block_start(city) + hash(restaurant_id) mod block_size(city).

This does not bring back the hot-city problem from the prediction above. That problem came from a key with one value per city; here Bengaluru is spread over 2,048 logical shards, which the map spreads across every physical database. What it costs is a block size per city that must be guessed in advance; a city that outgrows its block needs a second block and a migration for the restaurants moved into it. It also has to be decided before the first sharded order id is issued, because the chapter on IDs bakes the logical shard number into every order id.

The map has 8,192 rows. Every application server keeps a copy in memory and refreshes it when it changes. Routing a query costs a hash and an array lookup. This is the shape Vitess uses for YouTube’s MySQL and the one Instagram described for its Postgres shards, and it turns resharding from a rewrite into a series of small, reversible moves.

A resharding move, and where it loses writes

Here is a move as it is usually first implemented. We want logical shard 3,071, which holds a handful of Bengaluru restaurants (about six on average, 50,000 ÷ 8,192), to go from db-2 to the new db-9.

  1. Copy a consistent snapshot of shard 3,071’s rows from db-2 to db-9.
  2. Tail db-2’s replication log and apply every later change to those rows on db-9.
  3. When db-9 has caught up to within a fraction of a second, update the map: 3,071 now lives on db-9.
  4. Delete shard 3,071’s rows from db-2 later.

Now walk it at 20:15 with real traffic. Application servers refresh the map every 30 seconds. The map changes at 20:15:00. Server 14 last refreshed at 20:14:50, so until 20:15:20 it still believes shard 3,071 is on db-2. At 20:15:07 a customer orders from restaurant 88213, which is in shard 3,071. Server 14 inserts the order on db-2. The replication tail from step 2 has already been stopped, because the move is “done”.

The order now exists only on db-2. The restaurant tablet, served by a server with the new map, reads db-9 and never sees it. The customer has paid and watches a spinner for forty minutes. Nobody gets an error, which is why this kind of bug survives testing.

The fix has two parts. Before flipping the map, we fence the source: db-2 stops accepting writes for shard 3,071 (the application checks a per-shard read-only flag, or the database rejects them), we wait for db-9 to apply the last change, and only then flip. Second, the map carries a version number, every write carries the version the server used, and a database that no longer owns a shard rejects the write with “moved, map version 42”. A server that gets that answer refreshes its map and retries.

The cost is a short write freeze for that one logical shard, usually a few seconds, during which about six restaurants cannot accept new orders and the client retries. That is the trade we accept: a brief, bounded, visible pause for a tiny slice of restaurants, instead of silent loss. We would schedule moves for the afternoon lull, not the dinner peak.

The queries that leave the shard

Choosing restaurant id did not make the other queries disappear. Each one needs a deliberate answer, and the honest answer is often “not from this database”.

“My past orders” is the clearest case. Asking eight shards for one customer’s history is affordable at a few hundred requests a second, but it gets worse as shards are added, and it puts a customer-facing page at the mercy of the slowest shard. The better plan is a second table, customer_orders, sharded by customer id and holding just enough to list the history: order id, restaurant name, total, date. It is filled from the stream of order events that the next chapter builds, and it lags by a second or two, which this page tolerates.

The operations dashboard, “orders per city in the last 15 minutes”, should not touch the order shards at all. It is an aggregate over a stream of events, and it belongs in the analytics path. Restaurant earnings for a month is a warehouse query.

Unique constraints are the quieter casualty. A rule like “a first-order coupon may be used once per customer” used to be a unique index on (customer_id, code), checked in the same database as the order. Now two orders from the same customer at two restaurants land on two shards, and each shard’s index only sees its own rows, so both succeed. A unique index only enforces uniqueness among rows on its own shard. The writes chapter’s coupon_redemptions table had the same weakness once orders split: it was written inside the order transaction, on the order’s shard. The rule has to move to a table keyed by what must be unique, here coupon_redemptions sharded by customer id and checked before the order is written, with a compensating release if the order then fails.

Transactions that cross shards follow the same logic. Placing an order touches one restaurant, so it stays on one shard and keeps its ordinary transaction. Anything that must change two shards together, like moving a refund between a restaurant’s balance and a customer’s wallet held elsewhere, becomes a saga of local steps with compensations, the pattern from the chapter on getting writes right.

When sharding is the wrong answer

Everything above has a running cost: routing code, a map to keep consistent, resharding tools, and every new feature asking “which shard?”. Before paying it, Dabba should try the cheaper moves, because they often push the problem out by years.

At today’s volume, the cheaper moves are the right ones, and the storage chapter already made the main one. A delivered order is read heavily for a few hours and then rarely. With orders partitioned by month and anything older than 90 days moved to the analytics store and an archive, the live tables hold about 90 million orders, roughly 360 GB with indexes, and recent orders fit comfortably in memory. Dropping an old partition is instant where deleting millions of rows is not.

Separating unrelated workloads helps too, and Dabba has already done it. Rider locations, 10,000 writes a second, left the orders database for Redis in the storage chapter. Menus live in their own database behind a cache. Each of these moves takes load off the primary without adding routing to every query. If the tenfold plan slips, the sharding work above can wait; the key choice and the logical-shard layout are still worth deciding now, because they shape the order id and every table that references it.

We would revisit the decision in two situations. If the restore-time or blast-radius goal still fails after archiving, sharding is the next step. And if the product changes the shape of an order, for example combined carts across restaurants, the restaurant key stops keeping orders on one shard, and the key itself is back on the table.

Sharding put Dabba’s orders in eight places and promised a second copy of them keyed by customer. Meanwhile every new order already owes work to the restaurant tablet, rider assignment, notifications and analytics. The next chapter, on streams and the log, gives the order service one place to record what happened, so that every other system can catch up in its own time.