Consistent Hashing
Deriving consistent hashing from first principles: why modulo sharding causes cache-miss avalanches, how a hash ring bounds key movement to 1/N, and why virtual nodes eliminate hotspot skew.
Suppose you run 4 cache servers (node-A through node-D) holding 10
million session keys. The textbook way to route a key is:
server = servers[hash(key) % N]This works cleanly as long as N never changes. The moment node-D crashes
(N: 4 → 3) or you scale up (N: 4 → 5), the modulus changes for almost
every key in the universe. Roughly 75% to 80% of all keys suddenly route
to the wrong server, triggering a massive thundering herd of cache
misses that slams your origin database.
Put servers and keys on the same ring
To keep keys stationary when N changes, decouple routing from N:
- Hash the output space
[0, 232− 1]into a closed ring where the end wraps back to0. - Hash each server (
hash("node-A")) onto a point on the ring. - Hash each key (
hash("user:042")) onto the same ring and walk clockwise until you hit the first server.
Now when you add node-D or kill node-C, only the single arc immediately
preceding that server changes ownership — roughly 1/N of the keys move,
while the other (N − 1)/N stay untouched.
Why raw rings still skew — and how virtual nodes fix it
With only 1 point per server on the ring, random hash placement leaves huge gaps: one unlucky server can own 45%+ of the ring while another owns 10%. Worse, if a server dies, 100% of its traffic dumps onto its single clockwise neighbor, risking a cascading failure.
The fix is virtual nodes (vnodes): hash each physical server V
times ("node-A#v0", "node-A#v1", …, "node-A#v49"). By the law of large
numbers, standard deviation drops as 1 / √V, flattening shard skew and
spreading a dead server’s keys across all surviving nodes.
Test both effects below. Start at 1 vnode to see severe shard skew, raise
vnodes to 50 to flatten the bars against the dashed ideal line, then click
add node or kill node to compare remapped keys against hash(k) % N.
interactive · raise virtual nodes to flatten skew, then add or kill a server
dashed line = ideal share (25% per node)
vnodes: 1 · max skew 2.28×3 → 4 nodes moved 12% vs 79% modulo
~1/N
keys moved on node add / remove
50–200
typical vnodes per physical server
O(log V)
binary search lookup per request
Handling heterogeneous hardware and viral hot keys
Virtual nodes unlock two extra production superpowers — and leave one failure mode you still have to guard against:
- Weighted capacity: if
node-Ehas twice the RAM ofnode-A, simply givenode-E2× as many virtual nodes. Its ring share doubles automatically. - Replication without a coordinator: to store
R = 3replicas of a key, walk clockwise fromhash(key)and pick the first 3 distinct physical servers (skipping duplicate vnodes of the same host or same rack). - Viral hot keys (what consistent hashing does NOT fix): consistent
hashing balances key count, not request volume. If one celebrity profile
receives 50% of all QPS, its single owning shard still melts. Production
systems pair consistent hashing with Bounded-Load Consistent Hashing
(Vimeo / Google: cap each server at
1.25×average load and spill overflow clockwise to the next node) or key salting / local L1 caching.
note
Don’t confuse consistent hashing with Rendezvous (HRW) hashing or
Jump Consistent Hash. Jump Hash uses zero memory and gives perfect
balance, but only works when nodes are numbered 0..N-1 and removed from the
end — so it cannot handle arbitrary middle-node failures like a hash ring can.
Routing comparison
| Strategy | Keys moved on 1 node change | Balance | Arbitrary node failure |
|---|---|---|---|
Modulo hash(k) % N |
(N−1)/N (~75%–95%) |
Even | Breaks entire fleet |
| Hash Ring (1 vnode) | ~1/N |
Poor (high skew) | Neighbor takes 100% |
| Hash Ring (100+ vnodes) | ~1/N |
Tight (<10% skew) | Spread across fleet |
| Bounded-Load Ring | ~1/N |
Load-capped (e.g. 1.25×) | Spread + overflow safe |
Where this shows up in system design
- Memcached / Twemproxy / Redis ClusterClients hash cache keys onto a virtual-node ring (or 16,384 fixed hash slots in Redis Cluster) so scaling cache nodes avoids DB meltdowns.
- DynamoDB / Apache CassandraPartition tokens form a consistent hash ring with vnodes; walking clockwise picks the primary and N−1 replica nodes across racks.
- CDN Edge Routing (Akamai / Vimeo)Bounded-load consistent hashing routes popular video chunks to specific edge caches for high hit rates without overloading one box.
- Discord Guild / Voice RoutingMaps active servers (guilds) onto stateful Elixir/voice nodes so reconnecting clients land on the same process while surviving node restarts.
Check yourself: system design scenarios
interactive · pick an architecture for each prompt to test your intuition
1. Scaling a 10-node Memcached fleet to 11 nodes
cache hit rate critical · live scale-out · avoid DB storm
Your read-heavy feed service caches 95% of reads in 10 Memcached nodes. Traffic grew 10% and you want to add an 11th node during peak hours without triggering a database outage.
Select an option to check the trade-off.
2. Mixed instance sizes in a sharded key-value store
heterogeneous RAM · 4× capacity ratio · simple routing
Your cluster runs six 32 GB nodes and two newer 128 GB nodes. You want the 128 GB nodes to hold 4× as many partitions without writing custom range-splitting rules.
Select an option to check the trade-off.
3. Viral live-stream thumbnail melts one CDN cache node
single hot key · key count already balanced · edge CPU saturation
Your CDN uses consistent hashing with 200 vnodes per edge server. Key counts are perfectly balanced (within 3%), yet one edge server is at 100% CPU because 40% of all users are requesting the exact same live-stream segment.
Select an option to check the trade-off.
thundering herdcaching
When a hot cache key expires and hundreds of concurrent requests simultaneously miss and hammer the origin database.
virtual nodespartitioning
Multiple positions on a consistent hash ring assigned to each physical server so keys spread evenly and failures disperse.
key saltingsharding
Appending a small random suffix (e.g. 0–9) to a hot partition key to spread writes across shards, at the cost of fan-out reads.