Consistent Hashing

Distribute keys across a changing set of nodes so that adding or removing a node moves only a small fraction of keys.

Intermediate · about 3 hours · difficulty 3/5

Learn first: Sharding and Partitioning

With naive hashing, server = hash(key) mod N. Add one server and almost every key maps somewhere new, so caches go cold and data must move. Consistent hashing fixes this.

How it works

  • Place nodes on a hash ring (positions 0 to 2^32 minus 1) by hashing their IDs.
  • Hash each key onto the same ring and walk clockwise to the first node: that node owns the key.
  • When a node joins, it takes over only the keys between it and its predecessor. When a node leaves, only its keys move to the next node. On average just 1/N of keys move.

Virtual nodes

With few nodes, ring positions are uneven and one node may own far more keys. Give each physical node many virtual nodes (say 100 to 200 points on the ring). Load evens out, and when a node dies its load spreads across many nodes instead of one neighbour. Stronger machines can get more virtual nodes.

Replication on the ring

To store 3 copies, write to the owner and the next two distinct physical nodes clockwise. This is how Dynamo-style systems such as Cassandra and Riak place replicas.

Where you will see it

Distributed caches (client-side sharding in Memcached), Cassandra and DynamoDB partitioning, load balancers that route the same user or key to the same backend, and CDN request routing. Alternatives such as rendezvous (highest random weight) hashing and jump consistent hash solve the same problem with different trade-offs.

Pitfalls

  • Forgetting virtual nodes and ending up with badly skewed load.
  • Assuming consistent hashing fixes hot keys. One celebrity key still lands on one node.

You are ready to move on when you can draw a ring with three nodes, add a fourth, and show exactly which keys move.

Key concepts

  • Problem with mod N hashing
  • Hash ring
  • Virtual nodes
  • Replica placement on the ring
  • Rendezvous hashing
  • Jump consistent hash

Mini project

Implement a consistent hash ring with virtual nodes in your language of choice. Map 1 million keys to 5 nodes, add a sixth, and report the fraction of keys moved and the per-node load spread for 1, 10 and 200 virtual nodes.

Check yourself

Why do virtual nodes improve both load balance and recovery when a node fails?

Free resources