Sharding and Partitioning
How sharding splits a database across machines, how range, hash and directory mapping differ, and what interviewers ask about shard keys and rebalancing.
On this page
Sharding, also called partitioning, splits one large dataset into pieces and stores each piece on a different machine. Each piece is a shard. A shard key, which is a column such as user_id, decides which shard a given row belongs to. Sharding is how a database grows beyond the storage and write capacity of a single machine.
Read replicas and caches do not solve that problem, because every replica holds a full copy of the data and applies every write. Replicas add read capacity but not storage or write capacity.
Where sharding sits
The router can be a separate service, a library in the application, or part of the database. A query that contains the shard key reaches one shard, and a query without it has to be sent to all of them. Each shard is normally a leader with followers, so replication protects each piece against machine failure and sharding divides the load between pieces.
When to shard and what to try first
Sharding has a permanent cost: joins and transactions across shards become hard, every query has to include the shard key, and changing the key later means moving data. Try the cheaper options first.
- If the machine is short of CPU, memory or disk, a bigger machine is the simplest fix, and many systems never need more.
- If the load is mostly reads, add read replicas. They scale reads without changing the data model, at the price of replication lag.
- If the same rows are read repeatedly, add a cache.
Shard when the data volume or the write rate exceeds what the largest practical machine can handle.
Mapping keys to shards
The mapping from a key to a shard is the central design choice. There are three common ones, and each behaves very differently under load and growth.
Range partitioning
Each shard owns a continuous range of key values, for example usernames A to F on shard 1 and G to M on shard 2. The ranges are stored in a small table that the router consults. Because neighbouring keys live together, a range query such as "all orders between two dates" touches one or two shards.
Use it when range queries over the key are a main access pattern. The danger is uneven load: if the key grows over time, such as a timestamp, every new write falls in the newest range and one shard takes all the writes. Range-based stores usually split a range into two when it grows too large, which handles size but not a hot newest range.
Hash partitioning
The router applies a hash function to the key and uses the result to pick the shard. A good hash spreads keys evenly even when the keys are sequential. It is the default for lookups by key, such as user ids or order ids.
The cost is that key order is lost, so a range scan over a hashed key has to ask every shard. The other danger is the way the hash is turned into a shard number, covered under rebalancing below.
Directory partitioning
A lookup service stores an explicit entry for each key or group of keys saying which shard holds it. Routers read the directory on every request, normally from a local cache. A key can be placed anywhere and moved by updating one entry.
Use it when placement must be controlled, for example in a multi-tenant product where a few large customers get a dedicated shard and small ones share the rest. If the directory is unavailable no request can be routed, so it must be replicated and cached in the routers.
Choosing the shard key
The shard key matters more than the mapping, because it decides which queries are cheap. A good key meets three conditions.
- The most frequent queries include it. If the main query is "the latest 50 messages in a chat", sharding by
chat_idputs the whole query on one shard. - Rows that are used together share it. A transaction or join that stays inside one shard is as simple as on a single database.
- It has many distinct values with an even spread. Sharding by
countrygives a few hundred values and a few very large ones, so a few shards end up much bigger than the rest.
The key favours one access pattern and makes the others more expensive, so say which query it serves and which it hurts.
Hot keys, cross-shard queries and secondary indexes
Hot keys and skew
Even a good key has outliers. One celebrity account or one very active group chat can receive far more traffic than a single shard can serve, and adding shards does not help because the key still lives on one of them. If the hot key is mostly read, cache it or read it from replicas. If it is written heavily, append a random suffix such as chat:8813#0 to chat:8813#9 on writes so they spread over ten shards, and have reads fetch all ten and merge them. That makes every read of the key ten times more expensive, so apply it only to keys known to be hot.
Queries that cross shards
A query without the shard key is sent to every shard and the router merges the answers. This is called scatter-gather. The query is only as fast as its slowest shard, so it gets slower as shards are added. If a frequent query does not match the shard key, serve it from a second copy of the data sharded by the field it uses, or from a search index.
Transactions across shards
A transaction whose rows are on one shard works as it does on a single database. When rows are on different shards, the shards must agree on commit or abort with a protocol such as two-phase commit, which is slow and can leave participants waiting if the coordinator fails. The better answer is to choose the shard key so that the rows of one transaction live together. When that is impossible, use a sequence of local transactions with compensating steps, as described in transactions and isolation.
Secondary indexes
A secondary index lets you query by a column that is not the shard key, such as finding a user by email when users are sharded by id. There are two ways to build one.
A local index is kept separately by each shard and covers only that shard's rows. A write updates one shard, which keeps writes cheap and atomic. A read by the indexed column has to ask every shard, because any of them might hold a match.
A global index covers all rows and is itself sharded by the indexed column, so a lookup by email goes to one index shard. The cost moves to writes: one row write updates the data shard and an index shard on different machines, so many systems update the index asynchronously and it can briefly lag. Use a local index when such reads are rare, and a global index when they are frequent and a short lag is acceptable.
Unique ids across shards
Auto-increment counters are per database, so two shards will generate the same ids. Use ids that are unique without coordination, as described in unique ids. A unique column such as a username must be the shard key of its own table, so that a duplicate is detected on one shard.
Adding shards and rebalancing
Shards are added as data grows, and the mapping should let that happen with little data movement and no downtime.
Why hash mod N fails
The obvious way to turn a hash into a shard number is hash(key) mod N, where N is the number of shards. It works until N changes. Going from 8 shards to 9, a key stays where it is only when its hash gives the same remainder for 8 and for 9, which is true for 8 of every 72 hash values, so about 89% of the rows have to move.
Consistent hashing
Consistent hashing places both the shards and the keys on a circle of hash values. A key belongs to the first shard found going clockwise from its position. When a shard is added, it takes over only the arc between itself and its neighbour, so on average only 1/N of the keys move, and the other shards are unaffected. To even out the arcs, each machine is given many positions on the circle, called virtual nodes.
Many fixed partitions mapped to fewer machines
Many databases fix the number of partitions up front, much larger than the number of machines, for example 1,024. A key's partition never changes, and a small table maps each partition to a machine. Adding a machine means moving whole partitions to it and updating the table. With 8 machines holding 128 partitions each, a ninth machine takes about 114 partitions, roughly 1/9 of the data. The partition count is hard to change later, so pick a number comfortably larger than the machines you will ever need.
Moving a partition without downtime
The tracer follows one partition from an old shard to a new one while the system keeps serving requests.
- p37 owner
- shard 1
1Chat 8813 hashes to partition 37, and the router's cached map says shard 1 owns it.
- p37 owner
- shard 1
2The empty shard 9 joins, and shard 1 copies a snapshot of partition 37 to it while still serving it.
- p37 owner
- shard 1
3If shard 9 failed now, nothing would be lost, because shard 1 still owns the partition and the copy is retried.
- p37 owner
- shard 1
4Writes made during the copy are replayed from shard 1's change log until shard 9 is milliseconds behind.
- p37 owner
- shard 9
5Shard 1 briefly pauses writes to the partition, sends the last changes, and the map is switched to shard 9.
- p37 owner
- shard 9
6A router with the old map still sends chat 8813 to shard 1, which says the partition has moved, so the router refreshes its map.
- p37 owner
- shard 9
- data moved
- ≈ 11%
7Chat 8813 now goes to shard 9, and shard 1 deletes its copy later. Repeating this gives shard 9 about a ninth of the data.
In the interview
Bring up sharding only after your estimate shows that one machine cannot hold the data or take the writes. Then say which key you shard by, which query that key makes cheap, which query it makes expensive, and how you handle hot keys and growth. For the mapping, hash into many fixed partitions, unless range queries over the key are a core requirement (use ranges) or tenants need individual placement (use a directory).
Questions to expect:
- "Why shard instead of adding replicas?" Replicas copy all the data and all the writes, so they add read capacity only. Sharding is the one that adds storage and write capacity.
- "How do you pick the shard key?" Look at the most frequent query and use the field it filters on, so that query reaches one shard. Check that it has many evenly spread values and that rows used in one transaction share it.
- "Range or hash?" Hash gives an even spread and suits lookups by key. Range keeps neighbouring keys together for scans but sends sequential writes, such as timestamps, to one shard. I would hash unless scans over the key are central.
- "What happens when you add a shard?" With
hash mod Nnearly all data moves, so I would use many fixed partitions or consistent hashing. A new shard then copies whole partitions while the old shard still serves them, replays recent writes, and switches the map at the end. - "What if one key is extremely hot?" More shards do not help, because the key stays on one shard. I would cache it if it is read-heavy, or split it into sub-keys for writes and merge on read.
- "How do you query by a column that is not the shard key?" A local index asks every shard, while a global index answers from one shard but makes writes touch two places and usually lags slightly. I choose by how frequent the query is.
The chat service stores 8 TB of messages and takes 30,000 writes a second. How do you store them?
That is more than one primary can handle, and replicas do not add write capacity, so I would shard. The hottest query loads the latest messages of one chat, so I would shard by chat_id, hashed into 1,024 partitions spread over 8 shards, which keeps that query on a single shard.
What does that make hard?
Listing all chats of one user would ask every shard, so I would keep a second table sharded by user_id with each user's chat list.
One chat goes viral and its shard is overloaded.
More shards would not help, because the chat stays on one of them. For chats known to be huge, I would split writes over ten sub-keys and merge on read, and leave ordinary chats alone.
A service stores events with an increasing timestamp as the key, and most queries read the latest events. Which mapping avoids a hot shard?
A store of 100 million users is sharded by user_id. You need to look up a user by email address often. What is the best way to support it?
What to practise next
Read Consistent Hashing for the ring in detail, and Unique IDs for generating keys across shards. Design a Chat App applies sharding by conversation.