Sharding strategies explained: hash, range, directory and consistent hashing

Once you shard, every row needs an address. Learn the four ways to decide which shard data lives on, why plain hash-mod-N hurts the day you add a shard, how consistent hashing and logical shards fix it, and how to choose a shard key you won't regret.

A librarian with a cart of books stands in front of four shelving signs, each showing a different filing rule. Hash: a book's number run through a small machine that prints a shelf number. Range: shelves labelled A to F, G to M, N to S and T to Z. Directory: a card catalogue drawer listing each book's shelf. Consistent hashing: a round clock face with shelves placed around its edge. A sign above asks 'Which shelf does this go on?'
Fig. 1 — Four ways to give every row an address. Each makes some queries cheap and some changes painful.

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.

Four panels. Hash: user 42 goes through a hash function, then modulo 4, landing on shard 2. Keys spread evenly but neighbours scatter. Range: a number line from 1 to 1 billion cut into four ranges, one per shard; user 42 falls in the first range. Neighbours stay together, but the newest range can get all the traffic. Directory: a lookup table lists user 42 on shard 3, user 43 on shard 1, and so on, with a cache in front. Any key can move anywhere, but the table must always be available. Consistent hashing: a ring with four shards placed around it; a key's hash lands on the ring and walks clockwise to the next shard. Adding a shard only takes keys from its neighbour.
Hash spreads evenly. Range keeps neighbours together. Directory lets you place anything anywhere. Consistent hashing makes growth cheap.

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.

Twenty keys, 0 to 19, shown as a grid. For each key, its shard under modulo 4 and under modulo 5 is compared. Only keys 0, 1, 2 and 3 stay on the same shard; the other 16 change shard, so 80 percent of the data must move. Below, a bar comparison of the share of data that moves when going from 4 to 5 shards: modulo moves about 80 percent, consistent hashing about 20 percent, which is only the new shard's fair share.
With hash-mod-N, adding one shard to four moves 80% of keys. Consistent hashing moves only the 20% the new shard should own.

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.

Left: a hash ring with shards A, B, C and D placed around it. Keys k1 to k6 sit on the ring; each belongs to the next shard clockwise, so k1 and k2 belong to B. Right: shard E is added between A and B. Only the keys between A and E, here k1, move from B to E. Every other key stays where it was. Below, virtual nodes: each physical shard appears at many points around the ring, A1, A2, A3 and so on, so each one owns many small arcs and the load evens out.
Adding shard E only takes keys from its clockwise neighbour. Virtual nodes give each shard many small slices instead of one big one.

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:

Top: user IDs hash into 1,024 logical shards, numbered 0 to 1023, and this mapping never changes. Middle: at the start, four physical servers each hold 256 logical shards: server A holds 0 to 255, B holds 256 to 511, C holds 512 to 767, D holds 768 to 1023. Bottom: later, server E is added, and some logical shards are moved whole from A, B, C and D to E. Only the small mapping table from logical shard to server changes; no key is ever rehashed.
Hash keys into a fixed number of logical shards. To grow, move whole logical shards between servers and update a small map.
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_id has millions. country has 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_id makes nearly every request a single-shard query.
  • Keeps related data together. Shard a user’s orders by user_id, not order_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

  1. Hash spreads data evenly but scatters ranges. Range keeps ranges together but creates hotspots with increasing keys.
  2. Directory gives full control, at the cost of a lookup service that must never go down.
  3. Plain hash % N moves most of your data when N changes. Consistent hashing moves only about 1/N.
  4. Virtual nodes even out consistent hashing. Logical shards are a simpler way to get the same benefit.
  5. 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

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.