Sharding and consistent hashing
Sharding is what remains when everything else is exhausted: the data, or the write volume, genuinely no longer fits on one machine, so you split the data itself across many. Each shard holds a slice; no machine holds everything. It solves the unsolvable — and it is the most expensive, least reversible move in this entire course, which is why it sits at the bottom of Tier 0's ladder. Since you'll do it at most once, do it right.
The decision that is the whole decision: the shard key
Which piece of data determines where a row lives? Everything downstream flows from this choice. A good key does two things at once: spreads load evenly (no shard drowning while others idle) and keeps data that's queried together on the same shard (so common queries touch one machine, not all of them).
- Hash of user ID — hashing scatters users evenly, and all of one user's data lands together, so "everything about user X" hits one shard. Usually the right answer for consumer products.
- Range by date — January here, February there. Lovely for time-series and archiving old shards wholesale... and catastrophically, the current shard receives 100% of new writes. You've built a hot spot into the design on purpose.
- Geography — Indian users on Indian shards. Great for latency, sometimes legally required (data residency — Tier 14). Terrible for balance: one region always dominates.
Why the obvious function fails
The instinctive routing rule — shard = hash(key) % N — works perfectly until the day N changes. Go from 4 shards to 5, and follow one key: hash % 4 = 2, but hash % 5 = 4. Nearly every key's answer changes — roughly 80% of all data must physically move between machines, while serving live traffic. Adding one machine shouldn't require relocating the whole dataset. Enter the fix:
Consistent hashing: the ring
Picture a clock face running 0 to 2³²−1. Hash each node onto the ring; hash each key onto the ring; each key belongs to the first node clockwise from it. Now add a node: it claims only the keys between itself and its counterclockwise neighbour — about 1/N of the data moves, instead of 80%. Remove a node: its keys slide to the next node clockwise; everyone else is untouched.
One refinement makes it production-grade: raw, each physical machine is one point on the ring, so distribution is lumpy and a departing node dumps its entire load onto one neighbour. So real systems give each machine 100–200 virtual nodes — 100–200 ring positions. Distribution smooths out statistically, and a departing machine's load sprinkles across all survivors. (This is also the "consistent hashing" option from the load-balancer lesson — same ring, routing requests instead of placing data.)
The bill — read before signing, because there are no refunds
- Cross-shard joins: gone. Joining users on shard 3 with orders on shard 7 is not a SQL query anymore — it's your application fetching from both and stitching results by hand.
- Cross-shard transactions: gone. Atomically updating rows on two shards has no cheap answer. The workaround is sagas — a Tier 6 topic that exists substantially because of this line.
- Auto-increment IDs: gone. Each shard counting independently produces colliding IDs. You need distributed generation: Snowflake-style IDs (timestamp + machine ID + sequence — unique everywhere, roughly time-sortable) or UUIDv7.
- Boring operations become distributed problems. Backups, schema migrations, "just run this quick script" — everything is now N-way.
Hot shards: when even a good key isn't enough
Hashing balances keys, not load per key. One celebrity with 80 million followers, one viral post, one enormous enterprise tenant — and their shard glows red while its siblings nap. Mitigations: split the hot key into sub-keys (append a random suffix on write, aggregate the pieces on read — spreading one key across shards), or give the whales dedicated shards and route them explicitly. Both are patches; monitoring per-shard load is what tells you when to apply them.
Choosing a shard key that doesn't match the dominant query. Shard orders by order_id — nicely uniform! — and then watch the top query, "show this customer's orders," fan out to every shard on every page load, because the customer's orders are sprinkled everywhere. The shard key must follow the access pattern, not the primary key. Here that means sharding orders by customer_id — and yes, that's Lesson 0.05 again: access patterns first, storage decisions second. It was true for picking a database, and it's true for splitting one.
The tradeoff sheet
- Problem solved
- A dataset or write rate that no single machine can hold, once replicas and caching have run out of room.
- Rejected, and why
- Vertical scaling, archiving cold rows, and moving the heaviest tables to their own database all buy years and are reversible. Sharding is the answer when those are exhausted, not before.
- The trade
- Cross-shard joins and transactions, permanently. The shard key becomes an assumption baked into every query, and changing it later is a full data migration.
- First to break at 10x
- Key distribution. At 10x the hot shard arrives — one tenant, one celebrity, one country — and the fleet is idle while a single node saturates.
- What it does to the bill
- More instances, each smaller, and a router tier. Rarely cheaper than one large machine at the same total capacity; you are buying headroom you cannot otherwise get.
- Day-2 operations
- Rebalancing is the operation that matters and the one nobody practises. Know how you add a shard, how long it takes, and what is unavailable while it runs, before you need to.
The nuance
“Shard last — it is the bottom of the ladder.”
Right for a system growing into scale, which is most of them. Some workloads are born partitioned, though: hard per-tenant isolation, data residency that puts Indian records on Indian infrastructure, or a regulator requiring physical separation. There the partition is a requirement expressed on day one, not a capacity decision deferred to year five.
Going deeper
- Dynamo: Amazon’s Highly Available Key-value Store DeCandia et al., SOSP 2007
Consistent hashing, virtual nodes, quorums and the explicit choice of availability over consistency, in the paper that pushed all four into mainstream practice. - Consistent Hashing and Random Trees Karger et al., 1997
The original construction, and shorter than its reputation suggests.