Day 6 B-Building blocks 2026-10-01 ← All lessons

Consistent hashing: why hash % N breaks and how to fix it

Add one cache server under hash % N and most of your keys suddenly live somewhere else. Put the servers on a ring instead and only one neighbour's slice moves. This lesson proves the difference with real counts, and lets you drive the ring yourself.

7,975 movedOf 10,000 keys, when the pool grows 4→5 under hash % N (about 80%)
1,985 movedSame change on a ring (about 20% — the new server's fair share)
1 arcNeighbourhood affected by a join or a leave. Everything else is untouched
100–200Virtual nodes per server to get load variance under 10% (§5)

Key points

Outcomes

01Explain out loud why hash % N falls apart when the pool changes, with real remap counts.
02Walk through a lookup, a join and a leave on the ring, naming exactly which keys move and where.
03Argue the virtual-node trade-off, and say which problem it does not solve.
01

The problem: hash % N is a promise about N


Say you run 4 cache servers. The obvious way to pick one is serverIndex = hash(key) % N: run the key through a hash function, then take the remainder when dividing by N, the number of servers. As long as N stays fixed and the hash spreads keys evenly, this works perfectly.

Now a server dies and N becomes 3. The hashes have not changed at all — but you are dividing by a different number, so nearly every remainder changes.

How to read: Eight keys, each with a fixed hash. The top row is where they live with 4 servers; the bottom row is where they live with 3. Red means the key moved.

key0key1 key2key3 key4key5 key6key7 N = 4 s0 s3 s0 s1 s1 s2 s1 s2 N = 3 s0 s1 s2 s0 s2 s0 s2 s2 6 of 8 keys now live somewhere else — and only one server was removed. Every one of those clients asks the wrong server, misses, and falls through to the database. Losing one box costs you far more than one box of cache, and the extra load lands precisely when you have less capacity.
This is the cache miss storm. Note that key0 and key7 staying put is luck, not design — nothing in the scheme protects them.

Here are real numbers at scale. The runnable script in §6 hashes 10,000 keys and grows the pool from 4 servers to 5:

hash % N7,975
Consistent hashing ring1,985

Keys remapped out of 10,000 going from 4 to 5 servers. The ring moves roughly one fifth — exactly the share the new server should own, and nothing more. Both rows are computed by the §6 script.

Try it: these numbers are computed in your browser by actually hashing the keys and running both placements — the same FNV-1a and the same ring as the §6 script. Change the pool and watch both schemes.

hash % N
consistent hashing ring
keys moved, modulo
7,975
keys moved, ring
1,985
modulo is worse by
4.0x

Set virtual nodes to 1 and the ring's moved share wanders well away from its fair share — that is the uneven-partition problem of §4, showing up as a number before you see it as a picture.
Gotcha Failures are not the only time you pay. Scaling up also changes N. The deploy you run to add capacity for a traffic spike flushes your cache at the exact moment you need it most.
02

The mental model: a clock face with servers on it


Take the full output range of a hash function and bend it into a circle. With SHA-1 that range runs from 0 to 2160−1, and the two ends meet. Hash each server's name or IP onto the circle — a name is just a string, and strings are exactly what a hash function eats. Hash each key onto the same circle with the same function. There is no modulo anywhere, so where something sits never depends on how many servers you have.

The rule: a key belongs to the first server you meet walking clockwise from it. Picture a clock with a few people standing at different hours. A letter dropped at 2 o'clock goes to the next person clockwise. If someone new steps in at 3 o'clock, only the letters between the previous person and 3 o'clock change hands. Every other letter stays exactly where it was.

  1. Place the servers

    Hash every server onto the ring once, when it joins.

  2. Place the key

    Hash the key with the same function onto the same ring.

  3. Walk clockwise

    The first server you reach owns the key.

  4. Wrap around

    If you pass the top of the ring without meeting a server, continue to the first one. The ring has no end.

That gives you the guarantee: when the pool changes, only about one server's fair share of keys moves — k/n on average for k keys and n servers. That is 2,000 of 10,000 going from 4 to 5, which matches the §1 experiment. hash % N moves nearly all k instead.

03

The mechanism live: joins and leaves


How to read: Press Add a server to bring cache-d onto the ring and watch the moved counter, then compare it with the hash % N meter beside it. Hover or tap any key dot to trace its clockwise walk. New keys lays out a fresh set of 24 on the same ring.

Keys that moved on that change
0 of 24

Press a button to make a change.

Same change with hash % N
—

How many keys plain modulo hashing would have relocated.

Hover or tap a key dot on the ring to trace its lookup.
Three cache servers own twenty-four keys. Adding or removing a server moves only the keys in one arc, and the two meters prove it against plain modulo hashing.

Join. Three servers (cache-a, cache-b, cache-c) split 24 keys as 12, 3 and 9. Those exact numbers come from hashed placement, so yours will differ — but the lopsidedness is the point, and §4 is about exactly that. Press Add a server: cache-d joins and the counter reads 4 of 24. All four come from cache-c, the neighbour whose arc cache-d landed inside. cache-a and cache-b are untouched, so their clients keep hitting warm caches. The second meter shows what hash % N would have done on the identical change: 19 of 24 relocated.

Leave. Remove a server and its whole arc goes to the next server clockwise, and only there. Take cache-a out of the original three and all 12 of its keys land on cache-b, which jumps from 3 keys to 15 in one step. Nothing else moves. That instant quintupling is the cascading-failure risk §4 is about: if cache-b was already near capacity, it falls over next.

When does anything actually move? The mapping changes the moment the server list changes — the same key hash now resolves against a ring with one more node. The data follows later. In a cache nothing is pushed: the next lookup lands on the new owner, misses, and refills from the database, so keys migrate lazily, one miss at a time. In a store like Dynamo or Cassandra the new owner streams the affected arc from its neighbour. Either way, only that one arc is ever in flight.

Nothing outside that range moves. Rebalancing is a handover of one range between two neighbours, not a reshuffle of the cluster.

Interview line “On a join, only the keys between the new node and the node before it move, and they all come from one existing node. On a leave, the dead node's range goes to the next node clockwise.”
04

The weakness: one point per server lies about balance


The basic ring has two real problems, and the exhibit above already shows both.

Uneven partitions. A partition is the stretch of ring between a server and the one before it. With one hashed point per server these stretches are whatever size the hash happens to give, and every join or leave changes them. With four servers s0–s3: remove s1 and s2's partition becomes twice the size of s0's and s3's. In the exhibit, cache-d only took keys from cache-c — a new server relieves one neighbour, not the cluster.

Non-uniform key distribution. The same lumpiness from the other side. If the server points bunch together, one server can own most of the ring while others hold almost none. The exhibit's opening split is 12, 3 and 9; remove cache-a and cache-b goes from 3 keys to 15 in one step while cache-c sits idle. If cache-b was near capacity it falls over, its keys pile onto the next server, and you have a cascade.

Gotcha — the thing consistent hashing does not fix Consistent hashing spreads keys, not traffic. A single very hot key — a celebrity's profile — still lands on exactly one server no matter what ring you use. Even placement only helps when several hot keys would otherwise collide on one shard. One hot key needs extra copies on several servers, or a small cache sitting in front of it.
05

The fix: virtual nodes, and what they cost


Do not hash each server once. Hash it many times under different labels: server s0 becomes s0#0, s0#1, s0#2 and so on, each label getting its own point on the ring. Lookup is unchanged — walk clockwise to the first virtual node, then map it back to its real server.

How to read: One server, three labels. s0's points (green squares) interleave with s1's (amber squares). Dots are keys, coloured by owner, and each arc takes the colour of the server that owns it. Each server now owns three small arcs instead of one big one.

s0#0s1#0s0#1s1#1s0#2s1#2Positions are illustrative, not hashed. Real systems use 100–200 labels per server, not 3.
s0 and its keyss1 and its keys
Each server owns three small arcs instead of one big one. Oversized and undersized arcs now cancel out across the many each server holds.

This works because each server owns many small arcs spread around the ring rather than one big arc of random size. In one experiment the spread in keys per server was about 10% of the average with 100 virtual nodes per server, and about 5% with 200. It also fixes the failure case: when a server dies, each of its small arcs goes to a different successor, so its load spreads across the cluster instead of landing on one neighbour. A new server takes a little from everyone.

Option A

More virtual nodes

  • Lower load variance: about 10% at 100, 5% at 200.
  • A dead server's load spreads over many survivors instead of one.
  • A new server takes a little from every server.
  • Bigger machines can be given more vnodes for a larger share.
Option B

Fewer virtual nodes

  • Less metadata: every router stores every point.
  • Faster ring lookups and smaller membership updates.
  • Fewer, larger ranges to move during a rebalance.
  • Simpler to reason about and to debug.

The cost is space. Every client or router holds the full list of virtual node positions, and every membership change rewrites more entries. Treat it as a dial: raise virtual nodes until unevenness sits under what your capacity plan allows, then stop. Measure, do not guess.

06

The code: a ring with virtual nodes


Runnable, standard library onlypython
import bisect, hashlib

def h(s):
    return int(hashlib.md5(s.encode()).hexdigest()[:8], 16)

class Ring:
    def __init__(self, vnodes=100):
        self.vnodes = vnodes
        self.points = []      # sorted ring positions
        self.owner  = {}      # position -> real server

    def add(self, server):
        for i in range(self.vnodes):
            p = h(f"{server}#{i}")        # the virtual node trick
            bisect.insort(self.points, p)
            self.owner[p] = server

    def remove(self, server):
        for i in range(self.vnodes):
            p = h(f"{server}#{i}")
            self.points.remove(p)
            del self.owner[p]

    def lookup(self, key):
        i = bisect.bisect_right(self.points, h(key))   # the clockwise walk, as a binary search
        if i == len(self.points):
            i = 0                                      # wrap around the top of the ring
        return self.owner[self.points[i]]

keys = [f"user:{n}" for n in range(10000)]

mod_before = {k: h(k) % 4 for k in keys}
mod_after  = {k: h(k) % 5 for k in keys}
print("hash % N, 4 -> 5 servers, moved:",
      sum(mod_before[k] != mod_after[k] for k in keys))

ring = Ring()
for s in ["s0", "s1", "s2", "s3"]:
    ring.add(s)
before = {k: ring.lookup(k) for k in keys}
ring.add("s4")
after  = {k: ring.lookup(k) for k in keys}
print("ring,     4 -> 5 servers, moved:",
      sum(before[k] != after[k] for k in keys))
print("all moved keys went to s4:",
      all(after[k] == "s4" for k in keys if before[k] != after[k]))

# Output:
# hash % N, 4 -> 5 servers, moved: 7975
# ring,     4 -> 5 servers, moved: 1985
# all moved keys went to s4: True

The lines that matter. h(f"{server}#{i}") is the virtual node trick: one server becomes 100 labels and therefore 100 points. bisect_right on the sorted list is the clockwise walk, done as a binary search, so lookups stay fast however many points you add. The i == len(self.points) check is the wrap past the top of the ring — leave it out and any key past the last point crashes the lookup. The final print checks the property you are paying for: every key that moved went to the new server, and none moved between old servers.

Production notes Real systems keep this table in a membership service, or gossip it between nodes, so every router sees the same ring. They also use a fast non-cryptographic hash — no attacker is trying to forge keys here, so collision resistance is wasted work. The MD5 prefix above keeps only the first 8 hex digits (32 bits, plenty for an example) to stay in the standard library.
07

Two things the ring does not decide


It is not the only algorithm

Consistent hashing is the one everybody names, and for a cache or a store that must migrate data it is usually right. But it is not the only way to get stable assignment, and naming an alternative is cheap depth:

AlternativeHow it worksWhy you might prefer it
Rendezvous (HRW) hashingFor a key, compute hash(key, server) for every server and pick the highest score. No ring, no virtual nodes.Perfectly even distribution with no tuning, and weights are trivial to apply. The cost is O(n) per lookup rather than O(log n) — irrelevant for tens of servers, and it is a common choice in load balancers for exactly that reason.
Jump consistent hashA few lines of arithmetic mapping a key to one of N buckets, with optimal remapping and no stored state.No memory at all, and no ownership table to gossip. The catch: buckets are numbered 0…N−1, so you can only add or remove at the end — useless when any arbitrary node can die.
Bounded-load consistent hashingThe ring, plus a hard cap: if a key's owner is already above a load threshold, it overflows to the next node clockwise.Directly attacks the hot-shard problem the plain ring cannot. Used where one key's traffic can genuinely overwhelm its owner.

It does not choose your shard key

The ring answers “given this key, which server?”. It has nothing to say about which field should be the key — and that is the decision you cannot undo. Three tests, in order:

When a key passes the first two but produces a hot partition anyway, the standard escape is salting or bucketing: append a time bucket or a small random suffix so one logical key becomes several physical ones. Discord hit exactly this storing trillions of messages — keying by channel alone made busy channels into hot partitions, and adding a time bucket to the partition key spread them. The price is that reads must now fan out across the buckets, which is the trade you are accepting.

Gotcha A shard key is close to permanent. Changing it means rewriting every row and every query that assumed the old one, on a live system. Spend the extra two minutes in the interview naming all three tests — it is the decision an interviewer most wants to see you take seriously.
08

Field guide: who uses it and why


SystemWhat sits on the ringWhy consistent hashing
Amazon DynamoStorage nodes, by key rangeIn a large fleet, nodes join and leave constantly. Each change only moves data between ring neighbours, and virtual nodes let bigger machines take a bigger share.
Apache CassandraCluster nodes, by token rangeA new node streams one range from its neighbours instead of reshuffling the whole dataset.
DiscordChat servers, by session or communityLong-lived, stateful sessions. When a node changes, only the sessions in its arc have to reconnect.
Akamai CDNCache servers, by content URLKeeps caches warm as servers come and go. This is the original use case, from Karger et al. at MIT.
Google MaglevBackends behind a network load balancerWhen the backend set changes, packets from an existing connection keep reaching the same backend, so connections do not break.

What they share: moving a key costs something real — a cold cache, a copied partition, a dropped connection — and servers come and go too often to stop everything and remap.

09

Interview ears: the follow-ups that come next


They askYou say
“Why not just hash % N?”Changing N remaps nearly every key. In a cache that means a storm of misses hitting the database during a failure or a scale-up.
“A node dies. What happens?”Its range moves to the next node clockwise. Without virtual nodes that one node takes the whole load. With them, the load spreads across many survivors.
“How many virtual nodes?”Enough to bring unevenness under what your capacity plan allows — 100 to 200 gives roughly 10% down to 5% spread. You pay in a bigger ownership list on every router and chattier membership updates.
“Does it fix hot keys?”No. It spreads keys evenly, but a single hot key still has exactly one owner. Replicate it, or cache it closer to the client.
“How do you find what to migrate on a join?”Walk anticlockwise from the new node to the node before it. Only that range moves, and it all comes from one existing node.
Q&A

Check yourself


Consistent hashing is rarely asked on its own. It arrives as “how do you shard this?” and the follow-ups are about what it fails to fix.

Q1A 10-node cache placing keys with hash % N loses one node at peak traffic. Your database is sized for the normal miss rate. Predict the next ninety seconds.
  • Roughly a tenth of keys miss and the database absorbs it
  • Most keys miss at once, the database saturates, request latency climbs, and retries make it worse — a cascade, not a dip
  • No impact, because hashes are deterministic
✓ A cascade. Dividing by 9 instead of 10 changes most remainders, so most keys now resolve to the wrong server — the §1 calculator puts it near 90% for 10→9. Your database, sized for a 5% miss rate, suddenly receives something close to full read traffic while you have 10% less cache capacity. It saturates, p99 climbs, clients time out and retry, and the retries add load to an already-saturated database. The compounding detail: because all those requests miss, they all write back into the cache too, so you also get a write storm into a cache that is simultaneously rebalancing. This is why the failure of one cache node under modulo placement is a full outage rather than a 10% degradation, and it is the entire motivation for the lesson.
Q2You move to a ring and a node dies. Monitoring shows one surviving node's CPU at 95% while the others sit at 40%. You are running 1 virtual node per server. What happened, and what is the fix — and what is the fix's cost?
  • The ring is broken; revert to modulo
  • The dead node's whole arc went to its single clockwise neighbour. Raise virtual nodes so its load spreads — at the cost of a larger ownership table on every router
  • Add more nodes
✓ One point per server means one neighbour inherits everything. With a single ring position per node, a death transfers one contiguous arc to exactly one successor, which can double or triple that node's load in an instant. If it was already near capacity it falls over next, its arc moves to the following node, and you have a cascade around the ring. Virtual nodes fix it structurally: each server holds 100–200 scattered positions, so a death splits into many small arcs landing on many different survivors — typically a few percent extra each. The cost is metadata: every client or router stores every point (1,000 nodes × 200 vnodes = 200,000 entries), and every membership change rewrites more of it, making gossip chattier. Treat it as a dial: raise it until load variance is under what your capacity plan allows, then stop. Drag the vnode slider in §1 to watch the moved share converge on the fair share.
Q3“Shard our user database.” You propose consistent hashing on user_id. The interviewer asks what you lose compared to the current single database. Name the three biggest things.
  • Nothing significant — sharding is a solved problem
  • Cross-shard joins, multi-shard transactions, and any query that is not keyed by the shard key — plus resharding becomes an operational project
  • Only write throughput
✓ Joins, transactions, and every query that does not start with the shard key. (1) Joins: users JOIN orders only works if orders are co-located with their user, so the shard key has to propagate through your schema; anything crossing it becomes application-side fan-out and merge. (2) Transactions: “transfer from user A to user B” now spans two databases, so you need two-phase commit (slow, and a new failure mode) or a saga with compensating actions (complex, and eventually consistent). (3) Access patterns: “all users in Germany” or “everyone who signed up yesterday” hits every shard, so you scatter-gather — and your p99 becomes the slowest shard's p99. Also worth naming: consistent hashing solves only the routing problem. Choosing the shard key is the decision you cannot undo, and secondary indexes, unique constraints across shards and analytics queries all become separate projects. The strongest answer ends with “which is why I'd exhaust replicas and caching first.”
Q4One celebrity's profile is melting the server that owns it. A teammate proposes raising virtual nodes from 100 to 200. Will it help, and what would?
  • Yes — variance halves from 10% to 5%
  • No. One key has exactly one owner at any vnode count. You need replication of that key, or a cache in front of it
  • Yes — the key gets split across two servers
✓ No — and this is the boundary of what consistent hashing does. Virtual nodes balance how many keys each server holds. They do nothing about how much traffic any one key attracts, and no ring geometry splits a single key across servers. What actually works: replicate the hot key to several nodes and read from a random one (fine when it is read-heavy and tolerant of slight staleness); or add a small in-process cache on every application server so most reads never reach the shard at all — extremely effective, since a few seconds of TTL on a celebrity profile absorbs almost all of it; or shard the key itself by appending a random suffix (celeb:123:0 through :9) and pick one at random, which spreads a single logical key over ten physical ones at the cost of ten copies to invalidate. Detecting the hot key in the first place usually needs per-key request counters or sampling, which is worth mentioning as the prerequisite.
Q5You add a node to a Cassandra-style ring holding real data, not cache. Describe what physically happens, and name the operational risk.
  • The mapping changes instantly and all affected data appears on the new node
  • The mapping changes immediately but the data streams across afterwards — and the risk is that streaming saturates the network and degrades the serving path
  • Nothing until you run a manual rebalance
✓ Mapping flips first, data follows — and the copy is the dangerous part. In a cache, this asymmetry is harmless: the next lookup misses and refills lazily, one key at a time. In a store there is nothing to refill from, so the new owner must stream its arc from the neighbours that held it, while all three continue serving live traffic. The risks: streaming can saturate network and disk and raise latency for the requests you are still serving; during the transfer, reads must be routed carefully (usually to the old owner until the new one reports complete, which is why a node joins in a bootstrapping state); and if the join fails halfway you can be left with a partially-populated range. This is why production rings throttle stream throughput and add nodes one at a time — and why “only one arc is ever in flight” is the property that makes it survivable at all. Under modulo placement the same operation would mean moving nearly the entire dataset, which is simply not something you can do on a live cluster.
In practiceWhat production adds, and the questions that come next optional

This lesson covers the layer that decides an interview. Below it is the operational layer — the things that only show up once a system is running, and the questions that come if someone keeps pulling the thread. None of it is answered above.

Partitioning and sharding

  • Secondary indexes under partitioning: document-partitioned (local) vs. term-partitioned (global)

Consistent hashing

  • Replica placement: walking the ring for N successors and avoiding same-rack/same-AZ replicas

Terms used

Hash ring
The hash function's output range bent into a circle, with both servers and keys placed on it.
Clockwise rule
A key belongs to the first server encountered walking clockwise from the key's position.
Partition / arc
The stretch of ring one server owns: from the previous server's position to its own.
Virtual node (vnode)
One of many ring positions belonging to a single physical server, created by hashing labelled variants of its name.
Remap
A key changing owner because the server set changed. The quantity this whole lesson minimises.
Cache miss storm
A mass of simultaneous misses falling through to the database after a remap.
Hot key
A single key receiving disproportionate traffic. Not solvable by placement.
Membership service
The component that tells every router which nodes exist and where they sit on the ring.

What breaks next. The ring tells you which server owns a key. It says nothing about what happens when that server dies with the only copy on it. Day 7 puts replicas on the same ring, and then has to answer the harder question: if three machines hold a value and they disagree, which one is right?

Source: System Design Interview, Ch. 5 — Design consistent hashing: rehashing problem, hash ring, server lookup, virtual nodes, affected keys, real-world uses (pp. 71–86).