Imagine a library with a billion books and a hundred shelves. Where does each book go?
- By first letter of the title. Easy to find a range of titles, but the “S” shelf overflows while “X” sits empty.
- By a number worked out from the book’s ID. Perfectly even, but you can’t browse a range.
- Write each book’s shelf in a catalogue. Total flexibility, but now you depend on the catalogue.
In the previous part we decided to shard. Now every row needs an answer to the same question: which shard do you live on? The rule you choose is your sharding strategy, and it decides which queries are cheap, where hotspots appear, and how painful it is to add a shard later.
A good strategy aims for four things:
- Even data: each shard holds about the same amount.
- Even load: each shard gets about the same traffic. (Not the same thing as even data.)
- Few cross-shard queries: most requests touch one shard.
- Easy growth: adding a shard moves as little data as possible.
No strategy wins on all four. Here are the four you’ll meet.
1. Hash-based sharding
Run the shard key through a hash function and take the remainder:
shard = hash(user_id) % number_of_shards
// Java · hash router
public DataSource shardFor(String key) {
int hash = murmur3(key); // a well-mixed hash
return shards.get(Math.floorMod(hash, shards.size()));
}
Two Java details matter here. Use a well-mixed hash (like Murmur3) rather than relying on String.hashCode(), which can cluster for similar keys. And use Math.floorMod, not Math.abs(hash) % n: Math.abs(Integer.MIN_VALUE) is still negative and gives you a negative shard number.
- Good: data spreads evenly, there’s no lookup to do, and it’s simple.
- Bad: keys that are “next to each other” end up on different shards, so a range query (“users 1,000 to 2,000”) must ask every shard. And changing the number of shards moves most of your data. More on that below.
2. Range-based sharding
Give each shard a continuous range of keys:
| Shard | Holds |
|---|---|
| 1 | user_id 1 – 250M |
| 2 | 250M – 500M |
| 3 | 500M – 750M |
| 4 | 750M – 1B |
// Java · range router: find the highest range start ≤ the key
private final TreeMap<Long, DataSource> starts = new TreeMap<>(Map.of(
1L, shard1, 250_000_001L, shard2, 500_000_001L, shard3, 750_000_001L, shard4));
public DataSource shardFor(long userId) {
return starts.floorEntry(userId).getValue();
}
- Good: range queries hit only the shards that overlap the range. Time-series data fits naturally: “logs from last week” touches one shard, and old shards can move to cheap storage. Growing is easy too: split a full range in two.
- Bad: hotspots. If the key keeps increasing (auto-increment IDs, timestamps), every new write lands on the last shard while the others sit idle. Uneven data in the ranges also means uneven shards.
3. Directory-based sharding
Keep a lookup table that records where each key lives:
CREATE TABLE shard_directory (
tenant_id BIGINT PRIMARY KEY,
shard_id INT NOT NULL
);
The router looks up the key (with a cache in front, because this lookup happens on every request) and goes to that shard.
- Good: total flexibility. New tenants go to the least-loaded shard. A tenant that grows huge can be moved to its own dedicated shard by updating one row (after copying its data). This suits multi-tenant SaaS, where tenants range from 2 users to 500,000.
- Bad: the directory is on the path of every request. If it’s slow, everything is slow; if it’s down, everything is down. It has to be cached, replicated and kept highly available, which is real extra infrastructure.
The modulo problem
Hash sharding has a nasty surprise waiting. You have 4 shards using hash % 4, traffic grows, and you add a fifth: hash % 5.
Count it: for keys 0 to 19, only 4 of 20 land on the same shard under both rules. 80% of your data has to move, across every shard, just to add one machine. Even doubling from 4 to 8 moves half of it.
Two techniques fix this: consistent hashing and logical shards.
4. Consistent hashing
Picture a ring, like a clock face, covering every possible hash value. Place each shard at a point on the ring by hashing its name. To find a key’s shard, hash the key onto the ring and walk clockwise to the next shard.
When you add a shard, it lands somewhere on the ring and takes over only the keys between it and the previous shard. Everything else stays put. Going from 4 to 5 shards moves about a fifth of the data, which is the minimum possible: the new shard’s fair share.
There’s one catch. With only a few shards, their random positions leave some arcs much bigger than others, so some shards get far more data. The fix is virtual nodes: put each physical shard on the ring at many points (say 100–200). Each shard now owns many small arcs, and the totals even out. Virtual nodes also let a bigger machine take more points, and therefore more data.
// Java · consistent hash ring with virtual nodes
private final TreeMap<Long, DataSource> ring = new TreeMap<>();
public void addShard(String name, DataSource shard, int vnodes) {
for (int i = 0; i < vnodes; i++) ring.put(hash(name + "#" + i), shard);
}
public DataSource shardFor(String key) {
Map.Entry<Long, DataSource> e = ring.ceilingEntry(hash(key)); // next point clockwise
return (e != null ? e : ring.firstEntry()).getValue(); // wrap around the ring
}
Cassandra, DynamoDB and many caches use this idea. Like plain hashing, it gives up range queries.
The practical trick: logical shards
There’s a simpler fix many large systems use. Split the data into many more shards than you have machines, say 1,024 logical shards, fixed forever. Then map logical shards to physical servers:
logical = hash(user_id) % 1024 // never changes
server = logicalToServer[logical] // a small table you update when you grow
The key-to-logical-shard rule never changes, so no key is ever rehashed. To add a server, you move some whole logical shards to it and update a 1,024-row map. It’s a small, controlled directory, and it’s much easier to operate than a ring.
The four strategies side by side
| Hash | Range | Directory | Consistent hash | |
|---|---|---|---|---|
| Spreads data evenly | Yes | Often not | You decide | Yes, with virtual nodes |
| Range queries | Every shard | Few shards | Every shard | Every shard |
| Hotspot risk | Low (except one very hot key) | High with increasing keys | You can move hot keys | Low (except one very hot key) |
| Adding a shard | Moves most data | Split a range | Update the table | Moves ~1/N of data |
| Extra parts | None | A range map | Lookup service + cache | A ring |
| Good for | User data, evenly accessed | Time-series, logs | Multi-tenant SaaS | Distributed caches, key-value stores |
Choosing the shard key
The strategy matters, but the shard key matters more, and it’s the hardest thing to change later. A good key:
- Has many distinct values.
user_idhas millions.countryhas 200, and one of them may hold half your users. A yes/no field gives you two shards, forever. - Spreads writes. Avoid keys that only ever increase (timestamps, auto-increment IDs) with range sharding: all new writes pile onto one shard.
- Matches your main queries. If nearly every request is about one user,
user_idmakes nearly every request a single-shard query. - Keeps related data together. Shard a user’s orders by
user_id, notorder_id, so a user and their orders live on the same shard and can still be joined and updated in one transaction.
For multi-tenant apps, tenant_id is usually the natural key: tenants rarely query each other’s data. A compound key like (tenant_id, user_id) helps when single tenants get too big for one shard.
What breaks, and how to fix it
| What breaks | Why | The fix |
|---|---|---|
| Uneven hash shards | Weak hash function, or too few distinct key values | A well-mixed hash (Murmur3), a key with more distinct values, virtual nodes |
| The newest range is on fire | An increasing key with range sharding | Hash the key, or put a hash prefix in front of the time (hash(device) + timestamp) |
| Directory outage takes down everything | Every request needs a lookup | Cache the mapping in the app, replicate the directory, keep a stale copy to fall back on |
| Adding a shard means moving most data | Plain hash % N |
Consistent hashing or fixed logical shards |
| Queries need two shards | Related data sharded by different keys | Co-locate: shard related tables by the same key |
Puzzle 1: four to eight
Half of them. A key moves only if its % 8 result is 4 or more, which is half of all keys. And when you double, half has to move anyway: the new shards must get their share from somewhere. So doubling with modulo is actually the best case.
Going from 4 to 5 is far worse: about 80% of keys move, because % 5 and % 4 rarely agree. With consistent hashing, adding the fifth shard moves only about 20%. Modulo only behaves if you always double. Consistent hashing or logical shards let you grow one machine at a time.
Puzzle 2: the impossible join
A user lives on one shard, but their orders are scattered across all order shards, because order_id decides where each order goes. Showing one user’s orders means asking every order shard, then fetching the user from yet another shard and joining in code.
The fix is to shard orders by user_id too. Now a user and all their orders sit on the same shard: one query, a normal join, and even a local transaction. You can still look up an order by order_id if the ID carries the user’s shard (many systems embed the shard number in the ID itself). If you also need cross-user reports, send them to an analytics store rather than the live shards.
Puzzle 3: tenants of every size
Shard by workspace_id, since workspaces almost never share data. But plain hashing would put a giant workspace on a random shard alongside hundreds of others, and you couldn’t move it.
A directory fits best. New workspaces go to the least-loaded shard. When a workspace crosses a size threshold, copy it to a dedicated shard and update its one directory row. Cache the directory in every app server so the lookup is nearly free, and replicate it so it can’t take the system down.
Key takeaways
- Hash spreads data evenly but scatters ranges. Range keeps ranges together but creates hotspots with increasing keys.
- Directory gives full control, at the cost of a lookup service that must never go down.
- Plain
hash % Nmoves most of your data when N changes. Consistent hashing moves only about 1/N. - Virtual nodes even out consistent hashing. Logical shards are a simpler way to get the same benefit.
- The shard key matters more than the strategy: many distinct values, spread-out writes, and related data kept together.
Next in the Partitioning, sharding & distribution thread: rebalancing and hotspots, how to move data between shards without downtime, and what to do when one key gets far more traffic than the rest.
Comments