Consistent Hashing
How consistent hashing places keys on a changing set of servers, how virtual nodes even out the load, and what interviewers ask about it.
On this page
Consistent hashing is a way of deciding which server stores or serves each key so that adding or removing a server moves only a small share of the keys. It is used wherever data or traffic is spread over a set of machines that changes over time, such as a cache cluster or a partitioned key-value store.
The simple alternative is hash(key) % N, where N is the number of servers. It works until N changes. With 4 servers going to 5, a key keeps its server only when its hash gives the same remainder for 4 and 5, which is true for about 20% of keys. The other 80% now point at a server that does not hold them. In a cache, those lookups all miss and fall through to the database, so adding a server to relieve load can overload the database instead.
Where consistent hashing sits in a system
The ring is a small data structure kept in the client or in a routing layer. Given a key, it returns the server that owns it, without asking any other machine. In a key-value store the servers are the storage nodes, and in a cache they are the cache nodes. Some load balancers use it to send requests for the same key to the same backend.
The hash ring
The hash function maps both server names and keys to numbers in the same fixed range, and the range is treated as a circle, so the largest number is followed by zero. A key belongs to the first server found by walking clockwise from the key's position. Real rings use a range such as 0 to 232 − 1, and the examples here use 0 to 99.
What moves when a server joins or leaves
When a server joins, it takes over only the range between its predecessor on the ring and its own position, and the keys in that range come from one neighbour. When a server leaves, its range passes to the next server clockwise. Every other key keeps its owner. On average, adding the (N+1)th server moves about 1/(N+1) of the keys, which is the share the new server should hold anyway, while mod N would move about N/(N+1) of them.
- keys moved
- 0
1A, B and C sit at 10, 40 and 75. A owns 76 to 99 and 0 to 10 (35 positions), B owns 11 to 40 (30), C owns 41 to 75 (35).
- keys moved
- 0
2Server D joins at position 60 and takes positions 41 to 60 from C. Only keys in that range can move.
- keys moved
- 1
3Key 52 moves from C to D. Key 68 is past 60, so it stays with C, and A and B are untouched. One of the five keys moved.
- keys moved
- 2
4B leaves. Its positions 11 to 40 go to D, the next server clockwise, so only key 25 moves.
- keys moved
- 2
5D now owns positions 11 to 60, which is half the ring, while C owns only 15 positions. With one point per server the shares are uneven, and a server that leaves passes all of its keys to a single neighbour.
The last step of the tracer shows a flaw in the basic ring. With only one position per server, the ranges can be very different in size, and a leaving server hands its whole range to one neighbour, which may then be overloaded. Virtual nodes fix this.
Virtual nodes
A virtual node is one of many positions on the ring that belong to the same physical server. Instead of hashing "A" once, you hash "A#0", "A#1" and so on up to "A#99", and each result is a point on the ring that maps back to server A. Each server then owns many small ranges scattered around the ring instead of one large range. This has three effects:
- The share of keys per server is much closer to equal. The random variation in a server's share shrinks roughly as 1/√v for v points, which is about 10% at 100 points.
- When a server leaves, its many small ranges go to many different neighbours, so no single server takes the whole load.
- A server with twice the memory can be given twice as many points, and it will hold about twice as many keys.
A lookup keeps all the points in a sorted array and uses binary search to find the first point at or after the key's hash, wrapping to the start of the array if there is none. The hash function must spread values evenly.
const crypto = require("crypto");
function hash(s) { // first 32 bits of MD5
return parseInt(crypto.createHash("md5").update(s).digest("hex").slice(0, 8), 16);
}
class Ring {
constructor(vnodes = 100) {
this.vnodes = vnodes;
this.points = []; // [position, node], sorted
}
add(node) {
for (let i = 0; i < this.vnodes; i++) this.points.push([hash(`${node}#${i}`), node]);
this.points.sort((a, b) => a[0] - b[0]);
}
remove(node) {
this.points = this.points.filter(([, n]) => n !== node);
}
lookup(key) {
const h = hash(key);
let lo = 0, hi = this.points.length; // first point at or after h
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (this.points[mid][0] < h) lo = mid + 1; else hi = mid;
}
return this.points[lo % this.points.length][1]; // past the end: wrap to 0
}
}import bisect
import hashlib
def ring_hash(s):
# first 32 bits of MD5
return int(hashlib.md5(s.encode()).hexdigest()[:8], 16)
class Ring:
def __init__(self, vnodes=100):
self.vnodes = vnodes
self.points = [] # (position, node), sorted
def add(self, node):
for i in range(self.vnodes):
bisect.insort(self.points, (ring_hash(f"{node}#{i}"), node))
def remove(self, node):
self.points = [p for p in self.points if p[1] != node]
def lookup(self, key):
# first point at or after the key's hash; past the end: wrap to 0
i = bisect.bisect_left(self.points, (ring_hash(key), ""))
return self.points[i % len(self.points)][1]Replication on the ring
A key can be stored on more than one server by copying it to the next servers clockwise from its owner. With a replication factor of 3, a key is stored on the first three distinct servers found when walking from its position. With virtual nodes the walk must skip points that belong to a server already chosen, otherwise two copies could land on the same machine. If a server fails, the copies on the next servers already hold its keys, so reads can continue without moving data first. Replication covers the consistency questions that come with it.
Alternatives to the ring
hash(key) % N
This is the simplest method: one line of code, an even spread, and no data structure. It is the right choice when the number of servers never changes. Its problem is the one described at the top: changing N moves almost every key.
Rendezvous hashing
Rendezvous hashing, also called highest random weight hashing, has no ring. To place a key, compute a score for every server from the pair (key, server), for example hash(key + server), and pick the server with the highest score. When a server leaves, only the keys that had it as the top scorer move, and each of them moves to its second-highest scorer, so movement is minimal and spread across all servers. When a server joins, it takes exactly the keys for which it now scores highest. The load is even without virtual nodes, and the code is short. The cost is that each lookup computes N scores, so it is O(N). That is fine for tens of servers and slow for thousands. Pick it for a small cluster where you want even load and simple code.
Fixed hash slots
With fixed slots, the key space is cut into a fixed number of slots, for example 16,384, using hash(key) % slots. A table assigns each slot to a server. Adding a server means moving a chosen set of slots to it, and removing a server means reassigning its slots. Because the number of slots never changes, a key always stays in the same slot, and only whole slots move. Some distributed caches and databases work this way. It gives full control over what moves and when. The cost is that the slot table must be stored, versioned and sent to every client, which needs a coordinator or a gossip protocol.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| hash mod N | It is one line of code and spreads keys evenly. | Changing N moves almost every key. | The number of servers never changes. |
| Ring with virtual nodes Usual default | A join or leave moves about 1/N of the keys, weights are easy, and each client computes placement alone. | It needs many points per server, and every client must hold the same membership. | Caches and leaderless stores whose servers come and go, which is the most common case. |
| Rendezvous hashing | It spreads load evenly with minimal movement and no ring to maintain. | Each lookup scores every server, so it costs O(N). | A cluster of tens of servers. |
| Fixed hash slots | Data moves only when you decide, one slot at a time. | The slot table must be stored and distributed to every client. | Databases that move data between servers deliberately. |
Hot keys, membership changes and failures
Consistent hashing does not guarantee balanced load
The ring balances the number of keys per server, and only approximately. It does not balance traffic. If a few keys are read far more often than the rest, the servers that own them are busy, whatever the ring looks like. Adding virtual nodes does not help because a single key still lives on one server (and on its replicas). The fixes are to keep a short-lived copy of the hot key in each app server's memory, or to store the hot key under several names, such as key#1 to key#5, so that its reads spread over several servers.
Clients that disagree about membership
Each client builds its own ring from a list of servers, and that list reaches different clients at different times. For a short period two clients can send the same key to different servers. For a cache this causes some extra misses and possibly a stale copy. For a store that holds the only copy of the data it is more serious, so such systems use a coordinator or a consensus service to publish membership changes, or they send a request to the key's true owner, which forwards it if the ring has changed.
A failed server and its return
When a cache node fails and is removed from the ring, its keys move to other nodes where they are missing, so those reads go to the database until the cache is filled again. This is about 1/N of the traffic, not all of it. If the node comes back with its old contents, some values may be out of date because writes during its absence went elsewhere. It should therefore be started empty.
Moving data for stores that keep it
A cache can simply let moved keys miss. A key-value store cannot, because the data exists only on its servers. When a server joins, the data in its new ranges must be streamed to it before it takes over those ranges, and the old owner deletes it afterwards.
In the interview
Bring up consistent hashing when keys are spread over servers that can be added, removed or replaced. Say that hash mod N would move most keys on every change, name the ring with virtual nodes, and add that hot keys still need a separate fix. For a small cluster, or when you control data movement, mention rendezvous hashing or fixed slots.
Questions to expect:
- "Why not use hash mod N?" When N changes, most keys get a new server. For a cache that means most lookups miss at once, and for a store it means most data would have to be copied. Consistent hashing moves only about 1/N of the keys.
- "Why do you need virtual nodes?" With one point per server the ranges are random and can differ a lot in size, and a failed server hands its whole range to one neighbour. With around 100 points per server, the shares are close to equal and a failure spreads over many servers.
- "What happens when a node is added?" It takes over ranges from several neighbours, about 1/(N+1) of the keys in total. In a cache those keys miss once and are reloaded. In a store the data for those ranges is streamed to the new node before it is used.
- "How do you replicate with a ring?" Store each key on the next few distinct servers clockwise from its position, skipping points that belong to servers already chosen. If a server fails, the next servers on the walk already hold its keys.
- "Does it fix hot keys?" No. It balances the number of keys, not the traffic. A hot key needs a local cache in the app servers or several copies under different names.
- "How do clients learn the ring?" They get the list of servers from a configuration service or through gossip between servers, and each client builds the same ring from it. Clients can disagree for a short time after a change, which a cache tolerates as a few extra misses.
The cache needs a fifth node. Is that a problem?
With hash mod N it would be, because going from 4 to 5 nodes remaps about 80% of the keys and the database would receive most reads at once. I would place keys with consistent hashing and about 100 virtual nodes per server, so the new node takes roughly a fifth of the keys, a little from each existing node.
Does that fix a single very hot key?
No, because one key still lives on one node. I would keep a copy of that key in each app server's memory for a few seconds, or store it under several names so that its reads spread across nodes.
Ring of 0 to 99 with servers at 20, 50 and 80. Which server owns key 95?
A 9-node ring with virtual nodes gets a tenth node. About what share of keys move?
A cluster of 20 servers needs even load and minimal key movement, and you want the least code. Which method fits?
What to practise next
Read sharding and partitioning to see how databases split data, and Design a Key-Value Store to use a ring with replication.