Partitioning and consistent hashing¶
What you'll be able to do¶
- Explain when you need partitioning (sharding) and when you don't.
- Compare range, hash and directory-based partitioning.
- Explain why consistent hashing exists and what a bad shard key costs you.
The problem¶
Replication copies the same data to more machines. That helps reads and availability, but every machine still holds everything. When the dataset or the write rate outgrows one machine, you must split the data so each machine owns only part of it. This is partitioning, usually called sharding at the database level.
Do it last
Sharding makes everything harder: cross-shard queries, cross-shard transactions, resharding, operations. Try indexes, query tuning, caching, a bigger machine and read replicas first. Shard when writes or data size truly need it.
Three ways to decide where a row lives¶
| Strategy | Rule | Good | Bad |
|---|---|---|---|
| Range | Keys A–F on shard 1, G–M on shard 2… | Range scans are efficient; easy to reason about | Hot spots (e.g. time-based keys send all new writes to one shard) |
| Hash | shard = hash(key) mod N |
Spreads load evenly | Range queries must hit every shard; changing N moves almost every key |
| Directory | A lookup table says where each key lives | Fully flexible, supports moving tenants | The directory is a new critical component |
Why hash mod N is a trap¶
With shard = hash(key) mod N, going from N=4 to N=5 changes the shard of roughly 80% of the keys, so you'd move most of your data to add one machine.
Consistent hashing¶
Place both nodes and keys on a ring (the output range of a hash function). A key belongs to the first node clockwise from it.
When you add or remove a node, only the keys between it and its neighbour move: about 1/N of the data, instead of almost all of it. To even out load, each physical node takes many positions on the ring (virtual nodes). Used by Dynamo-style stores, Cassandra and many caches and load balancers.
Choosing a shard key¶
The shard key matters more than the strategy. A good key has:
- High cardinality: many distinct values, so data can spread.
- Even access: no single value gets most of the traffic.
- Locality for your queries: the things you read together live together (e.g. all of one user's data on one shard).
Bad choices: country (a few huge values), boolean flags, or a monotonically increasing ID with range partitioning (every new write lands on the last shard).
What gets harder¶
- Cross-shard queries: joins and aggregations must fan out and merge. Design access patterns to stay on one shard.
- Cross-shard transactions: need two-phase commit or sagas, and are slow or complex. Avoid them in the design.
- Hot shards / noisy neighbours: one busy tenant or celebrity key slows everyone on that shard. Isolate big tenants, split hot keys, or add a cache.
- Resharding: moving data while serving traffic. Plan for it from day one (more logical partitions than machines helps).
- Blast radius: a shard outage hits only its share of users, which is a benefit if you design for it.
Interview angle
Always name the shard key, justify it against the main query, and say what happens when one shard gets hot. If the interviewer asks "what if you need to add nodes?", the answer is consistent hashing or many small logical partitions.
For AI engineers¶
For AI engineers
A distributed training script must decide which worker reads each example. Hashing a stable example ID spreads work independently of file order; assigning whole files can leave one worker with far more data. A vector index split across nodes has a different cost: each node returns its local top k, then the coordinator merges those candidates into a global top k. Asking each node for fewer than k can discard a result the global answer needs.
Partitioning a RAG index by tenant keeps most tenant queries local, but a large or popular tenant can become a hot partition. Date-based training-data layout helps date-filtered reads, while many tiny files add file-opening and metadata work. For cache or embedding-service routing, consistent hashing limits how many keys change owners when nodes join or leave.
Common mistakes¶
- Sharding on a skewed key and assuming a large key space means even traffic.
- Using
hash(key) % Nwithout planning for how many keys move whenNchanges. - Asking each vector-search shard for fewer than
kcandidates before merging a global topk. - Forgetting the time and extra capacity needed to rebalance data while serving requests.
- Treating every tenant as equally sized, leaving a large or busy tenant on one overloaded shard.
Check yourself¶
You shard orders by created_at ranges. Next week a launch sends 10x traffic. What goes wrong?
All new writes carry the newest timestamp, so they land on the most recent range's shard. That one shard becomes a hot spot while the others sit idle. Use a hash of a high-cardinality key (e.g. order or customer ID) or a composite key.
With hash(key) mod 4 you add a fifth node. Roughly what fraction of keys must move, and what does consistent hashing do instead?
About 80% move with mod N (a key stays only if its hash gives the same remainder). With consistent hashing, only about 1/N of the keys, those adjacent to the new node on the ring, move.
Why is a multi-tenant system often sharded by tenant ID, and what is the risk?
It keeps one tenant's data and queries on one shard (no cross-shard joins, easy isolation, easy to move a tenant). The risk is a very large or very busy tenant overloading its shard, so you need a way to split or relocate big tenants.
Lab¶
Build stable hash, range, and consistent-hash partitioners in code/partitioning/. Measure key movement when adding a node and detect hot keys in an access log. Merge local search results into a correct global top k. Run: cd code/partitioning && PYTHONPATH=starter python -m pytest tests -q
Real systems that use this¶
Atlas cases linked below include a block-storage system that maps the hash of each data block to a storage cell, an incident where one store's traffic took down every other store sharing its database shard (Shopify), DynamoDB's region-aware data placement, and active/active designs that route each record to a "home region".
Go deeper¶
- Interactive: Designed to Scale – consistent hashing
- Deeper: Designing Data-Intensive Applications, ch. 6
- Your handbook: Software Engineering Handbook, ch. 8 §"Khi nào mới cần Sharding?"
- Exercise (later): implement a consistent-hash ring with virtual nodes in
code/consistent-hashing/
See it in the wild¶
Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.




