Consistent hashing for system design interviews: why hash % N empties your cache, and how rings and virtual nodes fix it

2026-11-29来源 dev.toEnglish
Consistent hashing for system design interviews: why hash % N empties your cache, and how rings and virtual nodes fix it

The interview question: "You have a cache cluster of 4 servers and need to add a fifth. How do you decide which server holds each key, so that adding one doesn't wipe out your cache?"

This question separates candidates who have memorised "use consistent hashing" from those who can explain why. The interesting part is the numbers: how many keys move, and how even the load stays. Here is the walkthrough, round by round, using the simulations in the Designbench consistent hashing lesson.

Round 1: The obvious answer, and why it breaks

Interviewer: Why not just use hash(key) % N?

You: It works perfectly until N changes. A key stays on the same server only if hash % 4 equals hash % 5. Over every run of 20 consecutive hash values, that is true for just 4 of them, so going from 4 servers to 5 moves 80% of the keys. For a cache, that means an 80% miss rate the moment you scale up, and all those misses land on the database at once.

In general, going from N to N + 1 servers with modulo moves about N / (N + 1) of the keys. The ideal is the opposite: only 1 / (N + 1) should move, because that is exactly the share the new server should own.

Round 2: The ring

Interviewer: So what does consistent hashing do differently?

You: It hashes servers and keys onto the same circle. A key belongs to the first server you meet walking clockwise from the key's position. Add a server and it only takes over the arc between itself and the previous server. Remove one and only its arc moves to the next server. Every other key stays exactly where it was.

Round 3: Uneven load, and virtual nodes

Interviewer: Any problem with one point per server?

You: Yes. With only a few points on the circle, the arcs are random lengths. One server can own a huge arc and another a tiny one. The fix is virtual nodes: put each physical server on the ring many times (say 100 points, from hashing "S1#0", "S1#1" and so on). Lots of small arcs average out, so each server's share gets close to 1 / N.

Here is the same change, 3,000 keys going from 4 servers to 5, under four strategies:

  • hash % N: 81% of keys move, max load 1.02× average.
  • Ring, 1 point per server: 36% move, max load 1.82× average (very uneven).
  • Ring, 100 virtual nodes: 19% move, max load 1.14× average.
  • Rendezvous hashing: 20% move, max load 1.03× average.

The four strategies compared on Designbench
Same change, four strategies, on Designbench. Virtual nodes bring both the keys moved and the load spread close to ideal.

Round 4: Show me the code

Interviewer: How would you implement it?

You: A sorted map is all you need. Store each virtual node's hash, and for a key take the first entry at or after its hash, wrapping to the start of the ring:

final class HashRing { private final TreeMap<Long, String> ring = new TreeMap<>(); private final int vnodes; HashRing(int vnodes) { this.vnodes = vnodes; } void addServer(String server) { for (int i = 0; i < vnodes; i++) ring.put(hash(server + "#" + i), server); } void removeServer(String server) { for (int i = 0; i < vnodes; i++) ring.remove(hash(server + "#" + i)); } String serverFor(String key) { Map.Entry<Long, String> e = ring.ceilingEntry(hash(key)); return (e != null ? e : ring.firstEntry()).getValue(); // wrap around } private static long hash(String s) { try { byte[] d = MessageDigest.getInstance("MD5") .digest(s.getBytes(StandardCharsets.UTF_8)); return ByteBuffer.wrap(d).getLong(); // first 8 bytes, well mixed } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } } 

Lookups are O(log V) where V is the number of virtual nodes on the ring, which is tiny. MD5 is fine here because this is about spreading keys evenly, not security; any well-mixed hash works.

Round 5: Replication on the ring

Interviewer: You want 3 copies of each key. Where do they go?

You: Walk clockwise from the key and take the next 3 distinct physical servers, skipping virtual nodes that belong to a server you already picked. Otherwise two of your "three copies" could sit on the same machine. In production you also skip servers in the same rack or zone, so one failure can't take all copies. This is how Dynamo-style stores such as Cassandra place replicas.

Round 6: Alternatives worth naming

Interviewer: Is the ring the only way?

You: Two others come up:

  • Rendezvous (highest random weight) hashing: for each key, score every server with hash(key, server) and pick the highest. Near-perfect balance and minimal movement, with no ring to maintain, but each lookup costs O(N). Great when N is small.
  • Jump consistent hash: tiny, fast and perfectly balanced, but servers must be numbered 0 to N − 1 and you can only add or remove at the end. Good for sharded storage you grow in order, not for caches where any node can die.

Say it in the interview

"hash % N reshuffles about 80% of keys when I go from 4 to 5 servers, which would empty a cache. I'd put servers and keys on a hash ring and give each server around 100 virtual nodes, so a change moves about 1 / N of the keys and the busiest server stays within roughly 15% of average. For replicas I walk clockwise to the next distinct servers in different zones."

Common mistakes

  • Saying "consistent hashing" without the numbers: about 80% of keys move with modulo, about 1 / N with a ring.
  • Forgetting virtual nodes, so one server owns a huge arc.
  • Placing replicas on the next virtual nodes instead of the next distinct physical servers.
  • Treating it as a load balancer for stateless requests. It matters when the server holds state for the key: a cache, a shard or a session.
  • Ignoring hot keys. Consistent hashing spreads keys, not traffic: one viral key still lands on one server.

Practise it

Add and remove servers, watch the keys move and run the four-strategy comparison in the consistent hashing lesson on Designbench. Related: Caching and CDNs, Sharding and Replication.

原文:https://www.a8q9.cn/en/article/consistent-hashing-for-system-design-interviews-why-hash-n-empties-your-cache-an-45de7c.html

相关文章