Sharding: splitting data across machines
Replicas copy everything, so they cannot help when the data or the writes outgrow one machine. Sharding splits the rows across machines by a key. The key you choose decides which queries stay cheap and which now have to ask every shard.
01 When one machine is not enough
Replication gives you more copies of the same data. Every replica stores all of it, and every write still goes through one leader. When the table no longer fits, or the leader cannot keep up with writes, you have to split the data itself.
A shard is one slice of the rows, on its own machine (usually with its own replicas). The shard key is the column that decides which slice a row belongs to. A router, either in your app, in a proxy, or inside the database, turns a key into a shard. MongoDB, Vitess, Citus, Cassandra and DynamoDB all work this way underneath.
02 Range sharding
The simplest split gives each shard a range of keys: orders 1 to 1000 on shard 1, and so on. Rows with nearby keys sit together, so “orders 1500 to 1600” touches one shard. But watch where new rows go when the key only ever grows.
- range matched
- just inserted
Orders are range-sharded by id. The router holds the shard map, and we watch where the next six new orders go.
Auto-increment ids and timestamps behave the same way. All writes hit one hot shard while the others idle, which is the problem sharding was meant to solve.
03 Hash sharding
Hash the key first and split on the hash. Neighbouring keys get unrelated hashes, so writes spread out even when the key only grows. Real systems use a proper hash function, such as MurmurHash or MD5, and then either take it modulo the number of shards or give each shard a range of hash values.
- routing
- just inserted
- not used yet
Now the same orders are sharded by hash. To keep the arithmetic visible, the “hash” here is simply id % 3.
In code the router is a few lines. Use a hash that is the same on every machine and every run:
Do not use Python’s built-in hash() for this. Since Python 3.3, string hashes are randomised per process, so two app servers would send the same user to different shards. Use a fixed function such as zlib.crc32 or one from hashlib.
04 Range or hash
Hashing fixed the hot shard, but it scattered neighbours. Now look at the range query that was cheap before.
- answering
- not answered yet
- rows just arrived
- result
The app asks for orders 2041 to 2046. On hash shards, nearby ids are not stored together, so the router cannot tell which shard has them.
| Property | Range on the key | Hash of the key |
|---|---|---|
| Rows with nearby keys | Same shard | Scattered |
| Range query, e.g. `BETWEEN` | One or a few shards | Every shard |
| Ever-growing keys (ids, timestamps) | All on the last shard | Spread evenly |
| Examples | HBase, Bigtable, CockroachDB | Cassandra, DynamoDB partition keys |
MongoDB offers both: ranged and hashed shard keys. A common middle ground is a compound key: hash on user_id to spread users out, then keep each user’s rows sorted by time within their shard.
05 The queries that now span shards
Say orders are hash-sharded by user_id. Any query that names one user goes to one shard. Everything else has to be rethought.
| Query | Shards touched | What you do about it |
|---|---|---|
| Orders for user 42 | One | Nothing: this is what the key is for |
| Order by its own id | All | Put the shard number inside the order id, or keep a lookup table |
| Newest 10 orders overall | All | Each shard returns its top 10; the router merges and keeps 10 |
| Join users and orders on user_id | One, if both use user_id | Shard related tables by the same key so they sit together |
| Unique email address | All | A separate lookup table sharded by email |
| Move money between two users | Two | A cross-shard transaction (two-phase commit) or a saga |
Pick the shard key from the queries you run most, usually the thing most requests are “about”: the user, the tenant, the account. If your hottest query does not include the key, every request becomes a scatter-gather.
06 Adding a shard: why modulo hurts
Shard 3 of 3 fills up and you add a fourth. With id % N, changing N changes the answer for most keys, and each changed answer is a row that must move to another machine.
| Order id | id % 3 | id % 4 | Row moves? |
|---|---|---|---|
| 2041 | 1 | 1 | No |
| 2042 | 2 | 2 | No |
| 2043 | 0 | 3 | Yes |
| 2044 | 1 | 0 | Yes |
| 2045 | 2 | 1 | Yes |
| 2046 | 0 | 2 | Yes |
In general, going from 3 to 4 shards keeps a key in place only when id % 3 equals id % 4, which is one key in four. Three quarters of the data moves. Two common fixes:
- Many small logical shards. Split into a fixed, large number (say 256) up front and map several to each machine. Adding a machine moves whole logical shards to it; the key-to-shard mapping never changes. Citus, for example, creates 32 shards per distributed table by default.
- Consistent hashing. Place shards and keys on a ring of hash values; a new shard takes over only the keys next to it, roughly
1/Nof the data.
07 When sharding bites
ORDER BY created_atRange on an ever-growing keyRange-sharding by time or by auto-increment id puts every insert on the last shard. Hash, or lead the key with something that spreads out.hash(user_id) % NA hash that changesA per-process or per-version hash routes the same key to different shards from different servers. Use a fixed function.