Scaling & Load BalancingAdvanced14 min read1 questions

Consistent Hashing Explained

Why `hash(key) % N` breaks catastrophically when N changes, and the ring that fixes it. The algorithm behind Cassandra, DynamoDB, Memcached clients and every sharded cache.

Covers: The rehashing problem, hash rings, virtual nodes, replication on the ring, rendezvous hashing, bounded loads

You have ten cache servers and route keys with hash(key) % 10. You add one server. Now % 11 sends roughly 91% of keys to a different server - the entire cache is effectively cold, the database receives full traffic, and adding capacity has caused an outage. Consistent hashing exists to make that number ~9% instead.

Filter
0/1 mastered
Advancedconsistent hashingshardingdistributedAsked at Amazon, Discord

30-second answer

Modulo hashing remaps almost every key when the server count changes, which is catastrophic for caches and expensive for sharded data. Consistent hashing maps both keys and servers onto the same circular hash space; a key belongs to the first server encountered clockwise from its position. Adding or removing a server only affects keys between it and its neighbour, so on average only K/N keys move instead of nearly all of them. Virtual nodes - placing each physical server at many points on the ring - are what make the distribution even in practice.

Showing 1 of 1 questions for consistent-hashing-explained.

Check your understanding

3 questions · no sign-up, nothing stored

0/3 answered
Question 1

1.You use `hash(key) % 10` across 10 cache servers and add an 11th. Roughly what fraction of keys map elsewhere?

Question 2

2.Why are virtual nodes necessary in a consistent hash ring?

Question 3

3.One key receives 40% of all traffic. Does consistent hashing help?

Hands-on challenge

Build it - this is what you talk about in a deep-dive round.

Build and measure a consistent hash ring

Implement the ring from scratch and empirically verify the properties this lesson claims.

Requirements

  • Implement add, remove, get and get_replicas with configurable virtual nodes.
  • Distribute one million keys over 10 nodes and report per-node load and standard deviation at 1, 10, 100 and 500 virtual nodes.
  • Add an 11th node and measure the exact fraction of keys that move; compare against modulo hashing.
  • Verify get_replicas always returns distinct physical nodes.
  • Remove a node and confirm its keys spread across all survivors rather than one neighbour.

Stretch goals

  • Add rack awareness so replicas never share a failure domain.
  • Implement bounded-load spillover and show it capping a hot node.