TL;DR
Consistent hashing spreads keys across a set of servers so that adding or removing one server moves only a small share of the keys. Both the servers and the keys are hashed (turned into numbers by a Hash Function) onto the same circle of numbers. A key belongs to the first server found going clockwise from the key's position.
Where you'll see it: distributed key-value stores (databases that look up a value by its key), cache clusters that choose a server per key, and content delivery networks that route each request to a cache node.
Intuition
Suppose you have four shops and a stock of cards, each labelled with a customer ID. (This is the situation of a Distributed System that spreads data over several machines.) The simplest rule is to send each ID to shop number ID mod 4, a rule of the kind used in a Hash Table, where means the remainder after dividing by 4. That works until you open a fifth shop. Now the rule is ID mod 5, and almost every card goes to a different shop. Every shop has to restock, and the stock is in the wrong place until it moves.
Consistent hashing avoids that. Place the shops around a circle, each at a spot chosen by hashing its name. Place each card on the same circle by hashing its ID. A card goes to the next shop clockwise from its spot. Open a new shop: it takes over only the cards between it and the shop before it on the circle. Close a shop: its cards pass to the next shop clockwise, and nothing else moves.
The problem it solves is churn. A cache (a fast store of recently used answers; see Cache Eviction Policy) or database spread over many machines must change when machines fail or are added. A plain hash rule would send most keys to new machines at once, and that wipes the caches and floods the database. Consistent hashing makes each change local.
The math
Fix a hash function that maps any key to an integer in a large range, in many systems. Read the range as a ring, where the value after wraps back to . Arithmetic on the ring is Modular Arithmetic with .
Given servers , place each server at on the ring. For a key with position , define its owner as the first server clockwise from :
and if no such server exists, the owner wraps around to the server with the smallest position.
When a server is added, the keys that move are exactly those in the arc between the new server and the server before it. When a server is removed, its keys move to the next server clockwise. Nothing else changes.
If the hash spreads keys uniformly, each server owns about of the ring. Adding an th server takes about of the keys, and every one of them comes from the server that was next to it. The total moved is about of all keys. Compare this with the naive rule . A key stays on its server only when the old and new remainders match, so about of the keys move.
Each server holds one point on the ring, so the arcs can be uneven. Give each server points, called virtual nodes, and the owned shares average out. With more virtual nodes, each server's share gets closer to .
Worked examples
- Place three servers on a ring of 12 positions: A at 2, B at 6, C at 10.
- Key k1 hashes to 4. The first server clockwise is B at 6, so k1 goes to B.
- Key k2 hashes to 11. Going clockwise from 11 there is nothing until the wrap, then A at 2. So k2 goes to A.
- Key k3 hashes to 8. The first server clockwise is C at 10. So k3 goes to C.
- Remove B. Now k1 at 4 goes to the next clockwise server, C at 10. k2 still goes to A, and k3 still goes to C.
- Only k1 moved, and it moved from B to C, the server after B. Keys that were on A or C did not change.
- Add D at 5. The key k1 at 4 now finds D at 5 first, so k1 moves to D. Every other key is still where it was.
- Use a ring of 100 positions. Servers A, B, C, D sit at 10, 40, 65 and 90.
- Key at 25 goes to B (first server clockwise). Key at 70 goes to D. Key at 95 goes to A after wrapping. Key at 5 goes to A.
- Add E at 55. It takes the arc from 41 to 55 that previously belonged to C. That arc is part of C's range, so keys in now go to E.
- The arc length is 15 of 100, so about 15 percent of keys move, and they all come from C. Keys in still go to C, and the key at 70 still goes to D.
- The same change with the naive rule moves keys between N = 4 and N = 5 in a different way. Take the 20 residues to . A residue stays put only if its remainder mod 4 equals its remainder mod 5. That holds for only, so 4 of 20 stay and 16 of 20 move, which is 80 percent.
- Interpretation: consistent hashing moved about 15 percent of keys, and the naive rule moved about 80 percent. For a large cache, the difference is the difference between a small miss burst and a cold cache.
- Ten servers, each with 100 virtual nodes, so the ring has 1000 points. Each server owns about 10 percent of the keys.
- Remove one server. Its 10 percent of keys is spread across the arcs of its virtual nodes, which fall next to many different surviving servers.
- Those keys are shared among the 9 survivors, about percent extra each. A survivor goes from about 10 percent to about 11.1 percent of the keys.
- Moved keys: about 10 percent of the total. The remaining 90 percent do not move at all.
- Interpretation: the removal cost matches the ideal fraction, and the extra load is spread evenly. With one point per server, the load would be lumpier and one neighbour could take a much larger share.
Tradeoffs and failure modes
| Situation | Problem | Better choice |
|---|---|---|
| Few servers, few points each | Arcs are uneven, so one server may own a large share | Add virtual nodes, for example 100 or more per server |
| Hash function is weak | Keys cluster, so arcs carry unequal load | Use a well-mixed hash, not a simple modulo of the key |
| Servers differ in capacity | Equal virtual nodes give equal load regardless of size | Give bigger servers more virtual nodes in proportion to capacity |
| Keys have a hot spot | One key or key range gets most of the traffic | Consistent hashing does not fix hot keys; replicate them or split the key |
| Need exact placement control | The ring decides placement, not the operator | Use an explicit lookup table, at the cost of storing the table |
| Replicas are needed | Owner alone is one point of failure | Store each key on the next several servers clockwise |
One failure mode deserves a warning. Moving keys is cheap, but moving the data behind them is not. Right after a server joins, the cache misses for the keys it took, and a backing store may take a spike. Rebalancing should be gradual where the system allows it.
History
The idea was introduced in 1997 by David Karger and colleagues at MIT, in work on distributed caching for the web. It was motivated by caches spread over many machines, where a change of machines should not invalidate the whole cache. The technique later became a standard part of large distributed systems. Amazon's Dynamo key-value store, described in 2007, used a ring with virtual nodes to place data and replicas. Many client libraries for caches and databases implement a similar ring. The key idea has not changed since the 1997 paper: hash both servers and keys into one space and let each key follow its nearest server.
Recap
Taking keys mod the server count reshuffles almost everything when the count changes. Consistent hashing puts servers and keys on one ring, assigns each key to the next server clockwise, and so moves only about of the keys when a server joins, and only the leaving server's keys when one leaves. Virtual nodes even out the shares and can be weighted by capacity. It leads next to replication on successive ring neighbours and to the storage systems built on it, such as Dynamo.
Check yourself
QuestionIn one sentence, why does a plain rule of hash mod N cause a problem that a ring does not?Show answer
With hash mod N, changing N changes the remainder for most keys, so most keys move to new servers. On a ring, changing a server affects only the arc it sits on, so only the keys in that arc move.
QuestionA ring has positions 0 to 99 and servers at 20, 50 and 80. A new server is placed at 65. Which arc of keys moves, and how many of the 100 positions does it cover?Show answer
The new server at 65 takes the arc from just after 50 up to 65, that is positions 51 to 65. That is 15 positions, so 15 percent of the ring moves. The keys in that range that previously went to the server at 80 now go to the server at 65. Keys in 66 to 80 stay with the server at 80.
QuestionWhy do virtual nodes help even when the hash function is good?Show answer
A good hash places points uniformly in expectation, but with only one point per server the arcs are random and can differ a lot in length. Many virtual nodes per server make each server's total share an average of many small arcs, so the shares concentrate near one over N. The good hash makes the positions random; the virtual nodes make the totals even.
QuestionApplied: a cache cluster of 8 servers loses one server. Roughly what fraction of cached keys is lost, and what happens to the hit rate?Show answer
About one eighth of the keys were on the failed server, roughly 12.5 percent. Those keys now miss in the cache until they are fetched again and stored on their new owners. The other keys keep their servers and still hit. The hit rate drops by about the share of traffic those keys carried, and recovers as they refill. Replicating each key on a second server would cut the loss to near zero.