Plain hash(key) % N looks fine until you add one server — then N changes and almost every key remaps at once, and a sharded cache stampedes its database into the ground. Consistent hashing puts servers and keys on a ring and hands each key to the next server clockwise. Add or drop a server and only the keys in one arc move — about 1/N of them. Place the nodes, add one, and watch.
O(log N) lookup · ~K/N keys moved per node change · the sharding primitive
the ring
The hash output space bent into a circle — 0 and the max value meet at the top.
node
A server, placed on the ring at hash(server-id).
key → owner
A key is owned by the first node clockwise from where hash(key) lands.
virtual nodes
Each server placed at many ring points, so load evens out.
ring.js — servers, keys, and one arc that moves
Ready
Three servers sit on the ring; keys land where their hash falls and walk clockwise to the next server. Press Add node — watch how few keys change hands.
3
servers
12
keys
–
last moved
How it works
The whole idea is to break the dependency between a key's home and the number of servers. With hash(key) % N, every key's destination is a function of N, so changing N by one reshuffles nearly everything. On the ring, a key's home is the next server clockwise — which doesn't depend on N at all, only on who its immediate clockwise neighbor happens to be.
1
Place servers on the ring
Hash each server id to a point on the circle. They partition the ring into arcs, one per server.
2
Each key walks clockwise
Hash the key to a point, then walk clockwise to the first server. That server owns the whole arc behind it.
3
Adding a node splits one arc
A new server lands inside exactly one existing arc and takes over just the keys in the slice behind it. Every other arc is untouched — only ~1/N of keys move.
✓
Virtual nodes even the load
One point per server gives lumpy arcs. Placing each server at many points (vnodes) makes the arcs interleave, so load per server converges to fair.
Lookup
O(log N)
Keys moved / change
~K / N
vs hash % N
~all keys
Used in
caches, DBs, LBs
The code
# keys and nodes both hash onto the same ring [0, 2^32)class HashRing:
def __init__(self, nodes, vnodes=150):
self.ring = {} # point -> nodefor node in nodes:
for v in range(vnodes): # many points per node = even load
self.ring[hash_(f"{node}#{v}")] = node
self.points = sorted(self.ring) # sorted ring positionsdef owner(self, key):
h = hash_(key)
i = bisect_left(self.points, h) # first point clockwiseif i == len(self.points): i = 0 # wrap past the topreturn self.ring[self.points[i]]
# add a node: only keys in its new arcs move — not the whole keyspace
Quick check
1. Why does adding a server to hash(key) % N remap almost every key?
The destination is hash(key) % N. Change N and the remainder changes for almost every key, so almost everything moves — a cache-wide miss storm.
2. When you add a node to the ring, which keys move?
A new node lands inside one existing arc and takes over only the slice of keys behind it, up to its clockwise neighbor. Every other arc is untouched — about K/N keys move.
3. What problem do virtual nodes solve?
With one point per server, a few servers can randomly own large arcs. Placing each server at many points interleaves the arcs, so per-server load converges to fair.
FAQ
What is consistent hashing?
A way to map keys to servers so that adding or removing a server only moves about 1/N of keys instead of nearly all of them. Both keys and servers hash onto a ring, and each key is owned by the first server clockwise from it.
Why not just use hash(key) % N?
Because N is baked into the destination. Add or remove a server and N changes, so nearly every key gets a new bucket — a cache-wide miss storm or massive reshuffle. The ring removes that dependency on N.
What are virtual nodes?
Each physical server is placed at many ring points (often 100–200) instead of one. This interleaves the arcs so no server randomly owns a huge slice, making load converge to fair — and spreads a removed node’s keys across many others, not one neighbor.
Where is consistent hashing used?
Sharded caches (Memcached), distributed databases (Cassandra, DynamoDB, Riak), CDNs, and load balancers — anywhere you shard across a changing set of servers and want to avoid reshuffling everything on every membership change.
The picture: the ring laid flat, and what D takes
The page’s ring_hash, with 3 virtual nodes per server instead of 100 so the points are readable. Adding D inserts three points and nothing else moves: every other point keeps exactly the arc it had, less what D cut from it. The few-points ring is lumpy, which is why the real code uses many more.
Worked example, step by step
Servers A, B and C with 100 virtual nodes each, then D is added. Keys are user:0 to user:999, hashed with the page’s ring_hash. The comparison is the plain rule servers[hash % N]. The table shows the first ten keys and the totals over all 1,000. Bold means the key changed server.
Key
Hash
Ring, A B C
Ring, + D
hash % 3
hash % 4
user:0
187275
C
C
A
D
user:1
463634
B
B
C
C
user:2
172652
A
A
C
A
user:3
943199
C
C
C
D
user:4
753060
C
D
A
A
user:5
890077
A
A
B
B
user:6
24078
C
C
A
C
user:7
855497
C
C
C
B
user:8
255472
C
C
B
A
user:9
955825
C
D
B
B
All 1,000 keys
284 moved
723 moved
In these ten keys the ring moved 2 (user:4 and user:9, both to D) and the modulus moved 6. Over all 1,000 keys the ring moved 284 and the modulus 723. The ideal for the ring is 1,000 / 4 = 250: D should end up with a quarter of the keys, and does hold 284. The ring moved a little over that because 100 points per server do not divide the ring perfectly evenly, and every moved key went to D, never between A, B and C. The modulus moved about three quarters of everything (the chance a key keeps its bucket when N changes from 3 to 4 is 1 in 4), and a lot of that traffic goes between servers that did not change. Each moved key is a cache miss or a data transfer, so the 439-key gap between the two columns is the point of the algorithm.
Complexity and trade-offs
Case
Time
Space
Why
Ring lookup (sorted points + binary search)
O(log(N·v))
O(N·v)
N servers, v virtual nodes each. With 3 servers at 100 points that is 300 sorted positions.
Add or remove a server
O(v log(N·v)) to update points
O(v) extra
Only keys on the touched arcs move: 284 of 1,000 for D joining (28%), 344 for C leaving, which is exactly the 344 keys C owned.
hash % N
O(1) lookup
O(N)
Changing N from 3 to 4 moved 723 of 1,000 keys; going from 3 to 2 moved 669.
Fewer virtual nodes (v = 1)
O(log N)
O(N)
Cheap but lumpy: with 3 servers and one point each the 1,000 keys split 63 / 60 / 877 instead of near thirds.
More virtual nodes (v = 100)
O(log(N·v))
O(N·v)
Evener: the same keys split 383 / 273 / 344 (spread 273 to 383), at the cost of a ring 100× larger.
The trade is memory and rebuild time for stability. Lookup cost barely changes with v because binary search is logarithmic, but the ring needs v times as many entries and a membership change touches v of them. Even with 100 points the split is not exact (273 to 383 per server with 3 servers); more points tighten it. Hash-mod is cheaper per lookup and needs no structure, which is fine when the server set never changes and wrong when it does.
Common mistakes
No wrap-around past the last point
The ring has no end, but the sorted array does. A lookup that returns “first point ≥ hash” and does not wrap to index 0 fails for every key hashing above the last point. Here the last point is 993994, and 5 of the 1,000 keys hash above it, so those lookups index past the end of the array.
A hash that clusters the virtual nodes
Virtual nodes only help if their positions are spread out. With the weak hash h = 31·h + byte (mod 1000003) applied to both keys and points, all 1000 of the 1000 keys land on A, even though each server has 100 points. Names like A#0, A#1 differ only in their last characters, which a weak hash barely mixes. The page’s hash adds an avalanche step for exactly this reason.
One point per server and calling it balanced
With v = 1 the arc sizes are random. Three servers, one point each, split the 1,000 keys 63 / 60 / 877. Moving to 100 points each gives 383 / 273 / 344.
Keeping the dead server’s points
On removal, delete all of its virtual nodes, not just its entry in the server list. Rebuilding the ring without C moves exactly the 344 keys C owned (344 moved). If its points stay, those lookups still resolve to C, which no longer answers.
Rehashing keys with a different function after a deploy
Keys and points must use the same hash and the same range everywhere. A client that hashes with a different function, or a different modulus, sends keys to servers that do not hold them even though the ring itself is unchanged.
Where this shows up
Sharded caches
A cache fleet that grows or loses a node should lose a fraction of its entries, not nearly all of them. In the run above adding a fourth server moved 284 keys instead of 723.
Partitioned data stores
Spreading rows across nodes by key hash, with the ring deciding which node owns each key. Replicas are usually the next distinct servers clockwise from the owner, so the ring also answers “who holds the copies”.
Load balancing with affinity
Sending the same user or session to the same backend when possible, while still tolerating backends joining and leaving, without a shared lookup table.
Weighted capacity
Give a larger machine more virtual nodes and it takes proportionally more keys. The same lever that smooths load also expresses uneven hardware.
SOLVE IT YOURSELF
Solve it: add a server without reshuffling everything
With hash(key) % N, adding one server moves almost every key. On a hash ring, it moves roughly 1/N of them — and the tests here prove that difference rather than asserting it.
YOUR TASK
Implement build_ring(nodes, vnodes) — place each node at vnodes positions around the ring — and lookup(ring, key), which returns the first node clockwise from the key’s hash, wrapping past the end. Use the provided ring_hash.
HINTS — 5 IDEAS
A node named "A" gets positions hash("A#0"), hash("A#1") … Keep the ring sorted by position.
Lookup is a binary search for the first position >= hash(key).
If the key hashes past the last position, wrap to index 0 — the ring has no end. Forgetting this is the classic bug and it only shows up for a small fraction of keys.
Why removing a node is cheap: only the keys that landed on its arcs move, and they move to the next node clockwise. Everyone else is untouched.
Virtual nodes are what make the load even. With one position per node the arcs are wildly uneven; with 100+, the law of large numbers smooths them out.