What is consistent hashing and where is it used?
System designSenior
In shortA way to map keys to nodes so that adding or removing a node moves only about 1/N of the keys, instead of nearly all of them as with hash(key) mod N. Keys and nodes are placed on a hash ring; virtual nodes even out the load. Used by distributed caches, databases and load balancers.
Model answer
The problem: with node = hash(key) % N, changing N from 10 to 11 remaps almost every key: a cache cluster loses nearly all hits at once, or a database must move nearly all data.
Consistent hashing: hash both nodes and keys onto the same ring (for example the 2^64 space). A key belongs to the first node clockwise from its position. Adding a node only takes keys from its successor; removing one only gives its keys to the next node: about 1/N of keys move.
Virtual nodes: with few nodes, positions on the ring are uneven and some nodes get far more keys. Each physical node gets many points (vnodes) on the ring, which evens out load and lets bigger machines take more vnodes. When a node fails, its load spreads over many others instead of one neighbor.
Replication: store each key on the next R distinct physical nodes clockwise (as in Dynamo-style stores like Cassandra), which also gives a natural read/write quorum setup.
Where it’s used: client-side sharding for memcached and Redis clusters, partitioning in Cassandra and DynamoDB-style systems, CDN and load balancer affinity (sending a user or object to the same backend).
Limits: it balances key counts, not traffic; a hot key still lands on one node and needs caching, replication of that key, or key splitting. Alternatives: rendezvous (highest random weight) hashing and jump consistent hash, which need less memory and give very even distribution.
What they're looking for
The problem with modulo hashing, the ring and clockwise assignment, virtual nodes for balance and heterogeneous capacity, replication to the next nodes, and real uses (Cassandra, DynamoDB-style stores, memcached clients, sticky load balancing). Bonus for rendezvous hashing or jump hash.
Common mistakes
- Not explaining why modulo hashing fails when nodes change.
- Ignoring hot keys, which consistent hashing doesn't fix.