Skip to content

Sharding: splitting data across machines

Working knowledgeUnder the hood

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.

ReplicasEvery row everywhereMore read capacity and a spare, but no more room and no more write capacity.
ShardsEach row in one placeRoom and write capacity grow with each shard. Queries that need several shards get harder.

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 shards: new ids pile onto the last shard
Step 1 of 7
Shard map · order id ranges
1–1000→shard 11001–2000→shard 22001 and up→shard 3
Shard 1 · new rows
Empty
Shard 2 · new rows
Empty
Shard 3 · new rows
Empty
  • 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.

— inserting

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.

Hash shards: the same ids spread out
Step 1 of 7
Router
id % 3
Shard 0 · new rows
Empty
Shard 1 · new rows
Empty
Shard 2 · new rows
Empty
  • 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:

router.py
import zlib
SHARDS = ["db-0", "db-1", "db-2"]
def shard_for(user_id: str) -> str:
h = zlib.crc32(user_id.encode())
return SHARDS[h % len(SHARDS)]
for user in ["ana", "raj", "ben"]:
print(user, shard_for(user))
Text
$ python3 router.py
ana db-0
raj db-1
ben db-2

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.

A range query on hash shards asks everyone
Step 1 of 5
Shards asked
shard 0
shard 1
shard 2
Rows back at the router
Empty
  • 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.

id 2041–2046 query
The same table, split two ways
PropertyRange on the keyHash of the key
Rows with nearby keysSame shardScattered
Range query, e.g. `BETWEEN`One or a few shardsEvery shard
Ever-growing keys (ids, timestamps)All on the last shardSpread evenly
ExamplesHBase, Bigtable, CockroachDBCassandra, 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.

Orders hash-sharded by user_id
QueryShards touchedWhat you do about it
Orders for user 42OneNothing: this is what the key is for
Order by its own idAllPut the shard number inside the order id, or keep a lookup table
Newest 10 orders overallAllEach shard returns its top 10; the router merges and keeps 10
Join users and orders on user_idOne, if both use user_idShard related tables by the same key so they sit together
Unique email addressAllA separate lookup table sharded by email
Move money between two usersTwoA 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.

The same six orders, 3 shards then 4
Order idid % 3id % 4Row moves?
204111No
204222No
204303Yes
204410Yes
204521Yes
204602Yes

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/N of the data.

07 When sharding bites

One key is hotA celebrity account gets a million reads a minute, and all of them hash to the same shard. Hashing spreads keys, not traffic for one key. Cache it, or split that key across several shards with a suffix.
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.
The key is not in the queryIf most queries filter on something other than the shard key, most queries ask every shard, and the slowest shard sets your latency.
Transactions across shardsA single-shard transaction is an ordinary database transaction. Across shards you need two-phase commit or a saga, and both are slower and harder. Shard so the things that change together live together.

08 Check yourself

Question

Events are range-sharded by created_at. Which shard takes today’s inserts?

Question

Users are hash-sharded by user_id. How many shards does WHERE email = ? touch?

Question

You have 4 shards chosen by id % 4 and add a fifth, switching to id % 5. Roughly how many rows move?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?