#6 most askedVery commonHardConsistent hashing
Consistent hashing
๐ข Asked in real interviews
No reports yet. Were you asked this? Be the first to say where.Why does hash(key) % N break when you add a cache server, and how does consistent hashing fix it?
๐งญ Adding a node to the hash ring
Key user:42
Hash ring
Node A
Node B
New node D
Press Next to follow a request through the system.
๐ค Answer it out loud, then check yourself
Say your answer as if the interviewer is listening (30โ90 seconds). Then reveal what a strong answer covers and tick what you said.
const hash = (s) => [...s].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7) % 1000;
const keys = Array.from({ length: 1000 }, (_, i) => "user:" + i);
const modMoved = keys.filter((k) => hash(k) % 4 !== hash(k) % 5).length;
const ring = (nodes) => (k) => nodes.find((n) => n >= hash(k)) ?? nodes[0];
const before = ring([100, 350, 600, 850]), after = ring([100, 350, 600, 725, 850]);
const ringMoved = keys.filter((k) => before(k) !== after(k)).length;
console.log(`4โ5 servers: modulo moved ${modMoved / 10}% of keys, consistent hashing moved ${ringMoved / 10}%`);
Answer out loud first, then compare.
Want to rehearse it?Answer this to the AI interviewer and get a verdict โ