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.
hash % N (about 80%)hash(key) % N ties every key to the server count. Change N and almost every remainder changes, which sets off a storm of cache misses at the exact moment you lost capacity.Outcomes
hash % N falls apart when the pool changes, with real remap counts.hash % N is a promise about NSay 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.
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:
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.
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.
Hash every server onto the ring once, when it joins.
Hash the key with the same function onto the same ring.
The first server you reach owns the key.
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.
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.
Press a button to make a change.
hash % NHow many keys plain modulo hashing would have relocated.
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.
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.
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.
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.
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.
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.
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:
| Alternative | How it works | Why you might prefer it |
|---|---|---|
| Rendezvous (HRW) hashing | For 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 hash | A 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 hashing | The 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. |
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:
country gives you ~200 values and permanent imbalance. user_id gives you millions.user_id has high cardinality and celebrity users, so it is uniform in storage and badly skewed in traffic. Those are different questions and both matter.user_id makes it one lookup and sharding by message_id makes it a scatter-gather across every shard.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.
| System | What sits on the ring | Why consistent hashing |
|---|---|---|
| Amazon Dynamo | Storage nodes, by key range | In 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 Cassandra | Cluster nodes, by token range | A new node streams one range from its neighbours instead of reshuffling the whole dataset. |
| Discord | Chat servers, by session or community | Long-lived, stateful sessions. When a node changes, only the sessions in its arc have to reconnect. |
| Akamai CDN | Cache servers, by content URL | Keeps caches warm as servers come and go. This is the original use case, from Karger et al. at MIT. |
| Google Maglev | Backends behind a network load balancer | When 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.
| They ask | You 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. |
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.
hash % N loses one node at peak traffic. Your database is sized for the normal miss rate. Predict the next ninety seconds.user_id. The interviewer asks what you lose compared to the current single database. Name the three biggest things.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.”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.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.
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).