Consistent Hashing
Distribute keys across nodes so adding or removing a node moves as little data as possible.
Consistent hashing in 30 seconds
- The problem:
hash(key) % Nremaps almost every key when N changes — a rebalancing stampede. - The idea: place nodes and keys on a ring; a key belongs to the first node clockwise from it.
- The win: adding or removing a node moves only about 1/N of the keys, not nearly all of them.
- Virtual nodes: many ring positions per physical node, to even out load and smooth failover.
- Also lets you weight bigger machines by giving them more ring positions.
- It fixes placement and movement, not hot keys — one scorching key still needs replication or caching.
A cloakroom with numbered pegs
Imagine a theatre cloakroom with a long row of numbered pegs, bent around into a circle so the last peg sits right next to the first. When you hand over your coat, a simple rule decides where it hangs: start at the peg matching your ticket number and walk clockwise until you hit the first staffed peg — that attendant takes your coat. Now a new attendant clocks in and stands at one peg: only the coats that would have walked past that peg change hands; everybody else's coat stays exactly where it was. An attendant goes home: only their coats shuffle to the next person clockwise. That tiny, local reshuffle — instead of re-hanging every coat in the building — is the whole idea behind consistent hashing.
Keep that picture in mind. The 'ring of pegs' is the hash ring, the 'attendants' are your servers, and the 'coats' are your keys. Everything below is just that cloakroom, made precise.
The problem it solves
When you spread keys across N nodes with simple modulo hashing (hash(key) % N), changing N remaps almost every key — add one node and nearly all your data has to move. For a distributed cache or database, that's a stampede of rebalancing that can take the system down. Consistent hashing solves this: adding or removing a node only moves a small fraction of keys, so the cluster can grow and shrink smoothly.
keys = range(12)
# with 4 nodes, each key lands on hash(key) % 4
before = {k: k % 4 for k in keys}
# add one node -> N goes from 4 to 5, so the divisor changes
after = {k: k % 5 for k in keys}
moved = [k for k in keys if before[k] != after[k]]
print(len(moved), "of", len(keys), "keys moved") # ~10 of 12 -- almost all!
# changing N shifts the remainder for nearly every key, so the whole
# dataset reshuffles. Consistent hashing moves only ~1/N instead.Look at why that happens. The remainder of a number depends on what you divide by. Change the divisor from 4 to 5 and almost every remainder changes too — 13 % 4 is 1 but 13 % 5 is 3. Since the divisor is the node count, every scaling event re-shuffles the deck. The naive fix 'just add a node' turns out to be the most expensive operation you can run.
The gap a plain hash table can't fill
You might think: a hash map already spreads keys evenly across buckets — why not just use that? Because a plain hash table assumes a fixed number of buckets. The entire premise of a distributed cache or database is that nodes come and go — you add capacity under load, machines crash, you scale down overnight. A structure that reshuffles everything whenever the bucket count changes is exactly the wrong tool. Consistent hashing is a hash scheme designed around the node count changing, which is the one thing ordinary modulo hashing handles worst.
The core idea, plainly
Imagine a circle (a 'ring') numbered from 0 all the way around. You hash each node to a point on the ring, and you hash each key to a point too. A key belongs to the first node you meet going clockwise from the key's position. That's it. The magic is what happens when the set of nodes changes.
# Place each node at a point on a big numeric ring (say 0 .. 2**32).
ring = sorted((hash_fn(node), node) for node in ["A", "B", "C"])
def node_for(key):
h = hash_fn(key)
for position, node in ring: # walk clockwise from the key
if position >= h:
return node # first node at or past the key wins
return ring[0][1] # past the last point -> wrap to the first
# 'Clockwise' is just 'the next-larger number, wrapping around to 0.'
# Nothing here mentions N -- that's why changing N barely disturbs it.Why it moves so little data
When you add a node, it drops onto the ring between two existing nodes and takes over only the keys in that arc — everything else stays put. When you remove a node, only its keys shift to the next node clockwise. So a change touches roughly 1/N of the keys instead of nearly all of them. That's the entire reason consistent hashing exists, and why it underpins distributed caches (like Memcached clusters) and databases (like Cassandra and DynamoDB).
The gap a single point per node can't fill
The simple one-point-per-node ring has two real problems, and seeing them is what motivates the next step. First, with only a handful of random points, the arcs between them come out wildly uneven — one node might own a third of the ring while another owns a sliver, so load is lopsided. Second, when a node leaves, all of its keys land on the single node immediately clockwise, suddenly doubling that neighbor's load right when the cluster is already short a machine. We need a way to chop each node's share into many small pieces scattered around the ring.
Virtual nodes: fixing uneven distribution
A naive ring has two problems: with few nodes, keys cluster unevenly, and when a node leaves, all its load dumps onto a single neighbor. Virtual nodes fix both: each physical node is hashed to many points on the ring instead of one. Now load is spread smoothly, and when a node leaves its keys scatter across many neighbors rather than crushing one. Virtual nodes also let you weight bigger machines by giving them more ring positions.
def build_ring(nodes, vnodes=150):
ring = []
for node in nodes:
# hash each node to many points -> smooth, even spread.
# give a bigger machine more vnodes to weight it heavier.
for i in range(vnodes):
position = hash_fn(f"{node}#{i}")
ring.append((position, node))
ring.sort() # sorted so lookup can walk clockwise
return ring
# when a node leaves, its 150 points vanish and their keys scatter
# across many neighbors instead of crushing a single one.# ring: sorted list of (hash_position, node) including virtual nodes
def node_for(key, ring):
h = hash_fn(key)
for position, node in ring: # walk clockwise
if position >= h:
return node
return ring[0][1] # wrapped past the end -> first nodeIn production the lookup isn't a linear walk — you keep the ring in a sorted structure and binary-search for the first position at or past the key's hash, so a lookup is O(log V) where V is the number of virtual nodes. The loop above is written out only to make the 'next clockwise' rule obvious.
| Ring style | Load balance | Failover behavior | When to use |
|---|---|---|---|
| One point per node | Lopsided with few nodes | Departing node dumps all load on one neighbor | Only a teaching example, almost never in production |
| Virtual nodes (100-200 per node) | Smooth and even | Load scatters across many neighbors | The real-world default |
| Weighted virtual nodes | Proportional to machine size | Same scatter, sized by capacity | Mixed hardware — give big boxes more vnodes |
How it pairs with replication
Real stores don't put a key on just one node — they replicate it. Consistent hashing makes replica placement trivial: after finding the first node clockwise, keep walking and place copies on the next few distinct physical nodes. DynamoDB and Cassandra do exactly this — the key's 'preference list' is simply the next N physical nodes around the ring.
def replicas_for(key, ring, n=3):
h = hash_fn(key)
chosen, seen = [], set()
# walk clockwise from the key, skipping vnodes of a node we already picked
for position, node in walk_clockwise(ring, start=h):
if node not in seen:
seen.add(node)
chosen.append(node)
if len(chosen) == n: # got N distinct machines -> done
break
return chosen
# The first node is the primary; the rest hold replicas. Because vnodes
# scatter a machine around the ring, we must skip repeats to get N *distinct*
# physical nodes, not N positions that map back to the same box.This is why the ring shows up everywhere leaderless replication does: one simple 'walk clockwise' rule decides both who owns a key and where its backups live, and both answers stay stable as the cluster changes.
Choosing: when to reach for the ring
| Situation | Reach for | Why |
|---|---|---|
| Fixed, never-changing node set | Plain modulo hashing | Simpler; the reshuffle problem never arises |
| Elastic cluster that scales up/down | Consistent hashing + vnodes | Adding/removing a node moves only ~1/N of keys |
| Range scans or ordered queries | Range-based sharding, not hashing | Hashing scatters neighbors; ranges keep them together |
| A few scorching-hot keys | Replication / caching on top | The ring balances count, not request heat |
Consistent hashing is the quiet machinery that lets distributed caches and databases grow and shrink without a rebalancing crisis — it's what turns 'add a node' from a scary migration into a routine operation.
Why it matters
- It makes elastic scaling practical: you can add capacity under load without moving most of your data.
- It underpins the stores people rely on daily — Cassandra, DynamoDB, and clustered caches all use the ring.
- It separates two concerns cleanly: even placement (virtual nodes) and cheap rebalancing (the ring).
If ignored
- Modulo hashing remaps nearly every key on a scaling event, flooding the network and often taking the cluster down.
- Skipping virtual nodes leaves load lopsided and dumps a departing node's whole share onto one neighbor.
- Expecting it to solve a hot key leads to a single node melting while the ring looks perfectly balanced.
Where it fits
- Sits in the routing layer, deciding which node owns each key.
- Lives inside distributed caches and leaderless databases rather than in app logic.
- Pairs with replication and caching to cover the hot keys it deliberately doesn't handle.
Related topics
- Sharding: consistent hashing is the resharding-friendly way to assign keys to shards
- Caching: clustered caches use the ring so adding a node doesn't cold-start everything
- Database scaling: it's what makes the shard step of the playbook survivable
- Scalability: the elastic, horizontal growth this technique is built to enable
Interview lens
Questions it unlocks
- How do you add a node to a distributed cache without remapping everything?
- Why not just use hash(key) % N for sharding?
- What are virtual nodes and why do you need them?
60-second answer
Modulo hashing remaps almost every key when the node count changes, which is a rebalancing disaster. Consistent hashing places nodes and keys on a ring and assigns each key to the next node clockwise, so adding or removing a node only moves about 1/N of the keys. I'd use virtual nodes — many ring positions per physical node — to even out load and avoid dumping a departing node's entire share onto one neighbor, and to weight larger machines. I'd note it fixes distribution and movement, not hot keys, which still need replication or caching.
Common traps
- Defaulting to modulo hashing and causing mass data movement on scaling.
- Skipping virtual nodes and getting lopsided load or bad failover.
- Expecting consistent hashing to solve a single hot key.