Consistent hashing
Map keys to nodes so that adding or removing a node moves only a small fraction of the data.
16 min readThe ring
Consistent hashing places both nodes and keys on the same circular hash space, say 0 to 2 to the power 64. A key belongs to the first node found walking clockwise from the key's position. When a node joins, it takes over only the keys between itself and its predecessor; when one leaves, only its keys move to the next node. With N nodes, a membership change moves about 1/N of the keys, instead of nearly all of them with hash mod N.
Virtual nodes fix uneven load
With only a handful of nodes on the ring, random positions leave some nodes owning arcs several times larger than others. The fix is virtual nodes: each physical node is placed on the ring 100 to 256 times at different hashes. Load then averages out to within roughly 10% of fair, and when a node dies its keys spread across many survivors rather than all landing on one neighbour. The cost is a larger routing table, which is still only a few thousand entries.
- Give bigger machines more virtual nodes to weight them
- Replicate by storing each key on the next R distinct physical nodes clockwise
- Cassandra, DynamoDB's ancestor Dynamo, and many cache clients use this scheme
Alternatives worth knowing
Rendezvous (highest random weight) hashing scores every node for a key and picks the highest; it needs no ring and balances well, at the cost of O(N) work per lookup, which is fine for tens of nodes. Jump consistent hash computes the bucket in a few lines with no memory, but only supports adding or removing the last bucket. Many databases instead use fixed partitions plus a mapping table, which gives the same minimal movement with simpler operations.
Where it shows up in designs
Use consistent hashing when clients route directly to stateful nodes: a distributed cache cluster, a sharded websocket gateway that must keep a user on the same server, or a load balancer that should send the same tenant to warm instances. On the canvas, a cache or load_balancer configured with consistent hashing keeps hit rates high when you scale instances in the Feedback panel, instead of dropping to near zero after every resize. With 10 cache nodes, adding an eleventh costs about 9% of hits briefly rather than about 91%.
Key takeaways
- Consistent hashing moves about 1/N of keys when membership changes
- Use 100 or more virtual nodes per server to even out load and spread failover
- Replicas go on the next distinct physical nodes around the ring
- Reach for it when clients route directly to stateful nodes such as cache servers
Sign in to track lessons and earn badges.