Consistent hashing
medium 28 minConsistent hashing puts keys and machines on one circle.
Video lesson · Chapter 1 of 6
Walk clockwise to the owner
The hash ring in 75 seconds
1:15Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Data that does not fit on one machine is spread over several, so every read has to answer one question first: which machine holds this key? Consistent hashing answers it with arithmetic instead of a list of every key.
A hash function turns any text into a number. Draw all those numbers on a circle, the hash ring. Hash each machine's name to a point on the ring, and each key too. A key belongs to the first machine you meet going clockwise.
Why it exists
The obvious answer, the hash of the key modulo the number of machines, works until that number changes. Then almost every key has a new home, and for a cache that means almost every request misses at once.
On a ring a new machine takes over only the stretch just before it. Nobody else's keys move. Growing from three machines to four moves about a quarter of the keys, the least that can be moved if the fourth machine is to get its fair share.
A short history
1996
David Thaler and Chinya Ravishankar at the University of Michigan invent rendezvous hashing, a different way to reach the same goal.
1997
David Karger and colleagues publish "Consistent Hashing and Random Trees" to spread web requests over a changing set of caches. The paper introduces the name.
2007
Amazon publishes the Dynamo paper: a key-value store that partitions data on a ring and gives each machine many points on it, called virtual nodes.
2014
John Lamping and Eric Veach publish jump consistent hash, which needs almost no memory but numbers its buckets from 0 to n - 1.
2016
Mirrokni, Thorup and Zadimoghaddam publish consistent hashing with bounded loads, which caps how much any one machine can receive.
Words to know
- Hash function
- Turns any input into a number that looks random but is always the same for the same input.
- Hash ring
- The whole range of hash values bent into a circle, so the largest is followed by zero.
- Token
- One point on the ring that belongs to a machine.
- Virtual node
- One of several tokens owned by the same machine. Vnode for short.
- Successor
- The next machine clockwise.
- Preference list
- The first few different machines clockwise from a key, where its copies live.
- Rebalancing
- Moving data so that every machine holds a fair share again.
How it works
Step through the idea, or press Play.
Put machines on a ring. Hash each machine's name to one or more points
Understand it
Start here
A round campfire
Picture a camp at night. The sleeping bags lie in a circle around the fire, and little lanterns stand along the circle too. The rule is simple: start at a lantern and walk clockwise. The first camper you reach looks after it. So each camper tends one stretch of the circle.
A lantern that is far more popular than the rest still has one camper. The circle shares out lanterns, not visitors.
Another picture of the same idea is a circular race track. The stations are the machines and every car stops at the first station ahead of it. A new station catches only the cars that now reach it first, and nobody else is disturbed.
The problem
Why not hash modulo N?
The first idea is hash(key) % N, where N is the number of machines. It is fast and even. The trouble starts when N changes, because the remainder of nearly every number changes with it.
Three keys, from 3 machines to 4
| Key | Hash | hash % 3 | hash % 4 | Result |
|---|---|---|---|---|
| key1 | 7 | 1 = B | 3 = D | moved |
| key2 | 5 | 2 = C | 1 = B | moved |
| key3 | 9 | 0 = A | 1 = B | moved |
How many keys move when one machine is added?
One machine is added
The ring
Three steps
- 1
Hash the nodes
position = hash(node id). In a small example on 0 to 359 degrees: N1 at 45, N2 at 135, N3 at 225. Real systems use a range such as 0 to 2^32 - 1 or larger.
- 2
Hash the keys
The same function: user:42 lands at 100 degrees and order:7 at 200 degrees.
- 3
Walk clockwise
From 100 the first node is N2 at 135. From 200 it is N3 at 225. A key at 300 passes the end of the ring and reaches N1 at 45.
Where the ring lives
Lookup
Finding the owner fast
import bisecttokens = [45, 135, 225]owner = {45: "N1", 135: "N2", 225: "N3"}def get_node(position): i = bisect.bisect_left(tokens, position) # first token >= position return owner[tokens[i % len(tokens)]] # wrap past the endfor key, pos in [("user:42", 100), ("order:7", 200), ("late", 300), ("edge", 135)]: print(key, pos, "->", get_node(pos))One read
Change
Adding and removing a node
A node joins
- Hash the new node to its positions
- Find the successor of each position: it holds the data now
- Copy the keys between the predecessor and the new node
- Update the routing list, then delete the old copies
A node leaves
- Identify its stretches
- Find the successor of each one
- Copy all its keys there, or promote replicas if it crashed
- Remove it from the routing list
Only one neighbour takes part
How much data moves
Balance
Virtual nodes
Three random points rarely cut a circle into equal parts. One node may own 50% of the ring, another 30% and the last 20%. Virtual nodes fix this: node A is hashed many times, as A#0, A#1 and so on up to A#149, and owns all those short stretches.
Measured: 20,000 keys on 5 nodes, then a sixth joins
| Tokens per node | Busiest node, times the average | Keys moved to the sixth |
|---|---|---|
| 1 | 1.75 | 19.5% |
| 10 | 1.29 | 16.2% |
| 100 | 1.13 | 16.6% |
| 150 | 1.06 | 18.7% |
| 200 | 1.09 | 17.4% |
How uneven is it?
Even shares
More points mean shorter stretches and a fairer total.
Mixed hardware
A machine with twice the memory gets twice the tokens.
Smooth failure
When a node dies, its short stretches fall on many other nodes instead of one.
Replicas need care
Neighbouring tokens may belong to the same machine, so skip repeats when choosing copies.
Copies
Replicas on the ring
To keep three copies, continue clockwise and take the first three different machines. The Dynamo paper calls this the preference list. Real systems also skip machines in the same rack or zone. How copies agree is the job of replication and consistency models.
Choosing three copies
Limits
What the ring does not fix
It gives you
- Few keys moved on a change
- A lookup without a central table
- Roughly equal numbers of keys
- Easy weights
It does not give you
- Protection from one hot key
- Range scans: neighbours on the ring are unrelated
- Agreement about who is a member
- Copies that are consistent
For a hot key, cache it closer to the reader, split it into several keys, or use bounded loads: a node that already has, say, 1.25 times the average passes the request to the next node. For range scans use range partitions; see partitioning strategies.
Alternatives
Other ways to the same goal
| Method | Idea | Good | Weak |
|---|---|---|---|
| Ring with vnodes | Sorted tokens, go clockwise | Any node can leave; weights are easy | Token list to store and share |
| Rendezvous | Score every node for the key, highest wins | Even, no list of tokens | Each lookup scores all N nodes |
| Jump hash | A short loop gives a bucket number | Almost no memory, very even | Only the last bucket can be removed |
| Fixed slots | Key to one of many slots, slots to nodes in a table | Operators decide what moves | The table has to be stored and agreed |
| Modulo | hash % N | Simplest | Nearly everything moves |
Which one?
In practice
Who uses it
| System | What its own documents say |
|---|---|
| Dynamo (2007 paper) | Ring, virtual nodes, preference list |
| Apache Cassandra | Tokens on a ring, 16 per node by default |
| Riak KV | Each node manages a set of vnodes |
| nginx | hash with consistent uses the ketama method |
| Envoy | Ring hash and Maglev load balancers |
| Amazon DynamoDB | An internal hash function chooses the partition; the ring is not documented |
Summary
The whole topic in one minute.
Consistent hashing places keys and machines on one ring and gives each key to the first machine clockwise. A lookup is a binary search over sorted tokens. When a machine joins or leaves, only the keys in its own stretches move, about one part in N.
One token per machine gives uneven shares, so real systems give each machine many tokens. They even out the load, let a bigger machine take more, and spread a failed machine's work over many others. The ring balances keys, not popularity: one very hot key still lands on one machine.
- Keys and nodes share one ring; a key belongs to the first node clockwise.
- A change moves about one part in N of the keys. Modulo moves nearly all of them.
- The stretch that moves to a new node lies between its predecessor and itself.
- Virtual nodes even out the shares, allow weights and spread failures.
- Copies go to the next different machines clockwise.
- It does not cure hot keys, range scans or disagreement about members.