Sharding splits one big dataset across many machines, so each machine holds and serves only part of it. Every row has a shard key, such as a user id, and a rule turns that key into the machine that owns it.
The rule is the whole game. A bad one sends all new writes to one machine, or moves almost all your data when you add a machine. A good one spreads the work, moves little and keeps related rows together. This page shows each rule working on real keys, then the problems that no rule fixes.
In the labs after the walkthrough, every small square is one key, such as a user or an order, in a simulation running in your browser. Its colour is the node it was first stored on: A, B, C, D. So when a key moves, you see a square of the wrong colour in its new home. Keys that just moved get a thick outline for a moment. Click any key to follow it and see what happened to it.
00 The life of one key
Before the live labs, follow a single key, user 42, from the moment it is written to the day a new node joins. Step through at your own pace, or press Play all.
Step 1 of 10
Meet the pieces
Four pieces work together. The app sends reads and writes. The router decides where each one goes, using the hash ring as its rule. The nodes are database servers, and each one holds some of the rows.
01 Why shard
A single database server has three limits that do not move: how much it can store on disk, how much of its working set fits in memory, and how many writes a second it can make durable. Read replicas help with reads, but every copy still holds all the data and takes every write.
When one of those limits gets close, you can buy a bigger machine (scaling up) until there is no bigger machine to buy, or split the data so each machine holds a part (scaling out). Splitting is sharding, and each part is a shard.
- Keys stored
- 0
- Writes rejected
- 0
Click any key to follow it and see what happens to it.
Shard when one machine cannot hold or write your data, not before. Every section below is a cost you take on in exchange.
02 Choosing a shard key, and range sharding
The shard key decides everything else. A good one has three properties:
- Many distinct values, so it can be spread thinly. Country is a poor key; user id is a good one.
- Even traffic, so no single value is much busier than the rest.
- It is in most queries, so most requests can go straight to one shard (section 07).
The simplest rule is range sharding: each shard owns a range of key values, like a phone book split into A to F, G to M and so on. Range scans are cheap, because neighbouring keys live together. But if the key only ever grows, such as an order id or a timestamp, every new row lands past the last boundary: on the last shard.
- Keys stored
- 40
- New writes on one shard
- –
Click any key to follow it and see what happens to it.
Range sharding suits keys that arrive in random order and queries that scan ranges. For ids and timestamps that only grow, hash the key first.
03 Hash sharding, and why mod N hurts
Hashing turns any key into a number that looks random, so even neighbouring ids like 1041 and 1042 land far apart. The obvious rule is hash(key) % N, where N is the number of nodes. It spreads keys evenly and needs no lookup table.
The trouble starts when N changes. A key stays put only if its hash gives the same remainder for N and for N + 1. For almost every key it does not, so adding one node moves nearly everything, all at once, while the system is serving traffic.
- Moved by last change
- –
- Share that moved
- –
- User 5380 lives on
- Node B
Following user 5380, now on node B.
- 0.0s Stored on node B: hash % 4 = 1.
With mod N, growing by one node means moving about N/(N + 1) of your data. That is the problem consistent hashing solves.
04 Consistent hashing: the ring
Picture every possible hash value on a circle, from 0 at the top round to the largest value just before it. Each node is hashed onto the circle too, at a point called its token. To find a key’s node, hash the key and walk clockwise until you reach a token. That node owns it.
So each node owns the arc that ends at its token. Adding a node drops one new token on the ring: it takes over part of one arc, and only the keys in that part move, all to the new node. Removing a node hands its arc to the next token clockwise. Every other key stays exactly where it was.
- Moved by last change
- –
- Share that moved
- –
- User 67 lives on
- Node A
Following user 67, now on node A.
- 0.0s Stored on node A: first token clockwise from 20.3% round the ring.
With a ring, adding or removing a node moves only about 1/N of the keys, and only between the nodes next to the change.
05 Virtual nodes: smoothing the arcs
One token per node has two flaws. Random tokens make uneven arcs, so one node can own half the ring while another owns a sliver. And when a node joins or leaves, all the moving keys come from, or go to, a single neighbour, which takes the whole load of the move.
The fix is to give every node many tokens, called virtual nodes. Each node now owns many small arcs scattered round the ring. Their sizes average out, and a new node takes a little from everyone instead of a lot from one node. A bigger machine can simply get more tokens. Cassandra and the original Amazon Dynamo design both work this way.
- Biggest node holds
- 71%
- Fair share
- 25%
- Moved by last change
- –
Click any key to follow it and see what happens to it.
Use many tokens per node, or a fixed number of slots that are handed out to nodes. Both give even arcs and spread out the work of a move.
The fixed-slot version is common: Redis Cluster hashes every key into one of 16,384 slots, and Citus and Kafka fix the number of shards or partitions up front. The key-to-slot rule never changes, so moving data means moving whole slots between nodes.
06 Hot keys: what no hash can spread
Hashing spreads different keys. It cannot spread one key. If a celebrity account gets half of all reads, every one of those reads goes to the node that owns that key, however many nodes you add. That node melts while the others idle.
The usual fixes:
- Cache it in front of the shards, so most reads never reach them.
- Split the key into sub-keys such as
celebrity#0tocelebrity#7, each with its own hash. Writes go to one sub-key; reads either pick one at random (for copies) or gather all of them (for a counter split in parts). - Add read replicas for the hot shard only.
- Busiest node
- 0/s
- Timed out, last 5 s
- 0
- Served by cache
- 0
Click any key to follow it and see what happens to it.
Look for hot keys before you shard, and plan for them. Adding nodes fixes uneven key counts, not one popular key.
07 Cross-shard queries
A router (or a smart client) knows which node owns which key. A query that includes the shard key goes straight to one node. A query that does not, such as “all orders for this product” when orders are sharded by user, must ask every node and merge the answers. This is scatter-gather, and it is as slow as the slowest node, and it gets slower as you add nodes.
- Joins work inside one shard. Store rows that are joined together under the same shard key (all of a user’s orders with the user) so the join stays local.
- Global uniqueness, such as “no two users share an email”, cannot be checked on one shard unless email is the shard key. The usual fix is a second lookup table sharded by email.
- Counts and sorts across everything need every shard, so they usually move to an analytics copy.
- Nodes asked
- –
- Time to answer
- –
Click any key to follow it and see what happens to it.
Pick the shard key from your most common queries, and keep rows that are read together under the same key.
08 Transactions across shards
A transaction on one shard is an ordinary database transaction. A transfer between two users on different shards is not: each shard can commit on its own, and you need both to commit or neither.
The classic protocol is two-phase commit. A coordinator asks every shard involved to prepare: write the change, lock the rows and promise it can commit. When all have said yes, it tells them to commit. That costs an extra round trip, and rows stay locked across both. Worse, if the coordinator dies after the prepare, the shards cannot decide on their own. Their rows stay locked, in doubt, until it comes back.
- Nodes asked
- –
- Round trips
- –
- Time to answer
- –
- Rows locked
- 0
Click any key to follow it and see what happens to it.
Design so most transactions stay on one shard. When they cannot, use the database’s distributed transactions, or break the work into steps that can be retried or undone (a saga).
09 Rebalancing while the system runs
The moves in the earlier labs were instant. Real ones copy data while users keep writing to it. The usual shape: copy a key (or a whole slot) to its new node, keep it in sync, then cut over so the new node becomes the owner.
The dangerous moment is between the copy and the cut-over. A write that lands on the old node after its key was copied never reaches the new one, and is lost when the old copy is dropped. So during a move, writes must reach both copies, or be replayed from a change log, or be paused for a moment while the key cuts over.
- Keys still to move
- 0
- Writes sent to both
- 0
- Lost writes
- 0
Click any key to follow it and see what happens to it.
Rebalancing is slow on purpose and must handle writes in flight. Tools like Vitess, Citus and MongoDB’s balancer exist largely to do this part safely.
10 Each shard needs its own replicas
Sharding splits the data; it does not copy it. With 10 shards on 10 machines, any one failure takes a tenth of your users offline, and with more machines a failure somewhere becomes routine. So each shard is usually a small replica set: a primary that takes writes and one or more replicas that can take over.
How replicas stay in sync, and what you can lose when one is promoted, is the subject of the database lesson. Here, the point is the shape: shards multiply your capacity, replicas multiply your copies, and you need both.
- Copies stored
- 36
- Keys unavailable
- 0
- Failed reads
- 0
Click any key to follow it and see what happens to it.
Plan copies per shard: three copies of each shard is a common default, across separate machines or zones.
11 How real systems shard
Each product below makes the choices above in its own way. A rough map:
| System | How keys map to shards | Moving data | Cross-shard work |
|---|---|---|---|
| Vitess (MySQL) | A vindex turns the key into a keyspace id (often a hash); each shard owns a range of keyspace ids | Online resharding by splitting ranges | Router plans scatter queries; atomic cross-shard transactions are an option |
| Citus (Postgres) | Hash of a distribution column into a fixed number of shards, placed on worker nodes | Shard rebalancer moves whole shards | Joins are fast on co-located tables; distributed transactions supported |
| MongoDB | Shard key, ranged or hashed, split into chunks | A balancer migrates chunks between shards | Queries without the shard key go to every shard; multi-document transactions supported |
| Cassandra, DynamoDB | Partition key hashed; Cassandra uses a token ring with virtual nodes, DynamoDB splits partitions for you | Cassandra streams token ranges; DynamoDB does it behind the scenes | Designed around single-partition queries; model tables per query |
| Redis Cluster | CRC16 of the key into one of 16,384 slots, slots assigned to primaries | Slots migrate key by key; clients follow redirects | Multi-key commands only within one slot; hash tags like {user42} force keys together |
Check the current docs before you choose: these systems change between versions, and managed offerings differ from self-hosted ones.
12 Check yourself
You shard orders by order id, using ranges. Order ids only ever grow. What happens to writes?
You use hash(key) % N with 10 nodes and add an eleventh. Roughly how many keys move?
On a consistent hash ring with 10 nodes, you add an eleventh. Which keys move?
One user with 50 million followers gets a third of all reads. You add more shards. What happens to that user’s shard?
Users are sharded by user id. Signup must check that an email is not already used. What is the problem?