Consistent Hashing Explained: Hash Rings, Virtual Nodes, Rendezvous, and Jump Hash
Why hash(key) mod N reshuffles almost every key when a node joins, and how hash rings, virtual nodes, rendezvous hashing, and jump consistent hash keep movement near the minimum. Includes a runnable Python comparison.
Any system that spreads data or traffic across several machines must answer one question for every key: which machine owns it? A cache cluster picks the node holding a session, a sharded database picks the shard for a customer row, and a load balancer picks the backend that already has a user's data warm. The obvious answer works until the number of machines changes. Consistent hashing is the family of techniques that keeps the answer stable while nodes come and go. This guide covers the classic hash ring, virtual nodes, rendezvous hashing, and jump consistent hash, and then compares all four with a short Python script you can run yourself.
Why hash(key) mod N breaks when N changes
The simplest placement rule hashes the key and takes the remainder: shard = hash(key) mod N. Load spreads evenly, lookups cost almost nothing, and no state needs to be shared. The trouble starts when N changes. Going from 10 shards to 11 changes the remainder for nearly every key, because a key keeps its shard only when its hash gives the same remainder under both divisors. In practice about ten keys out of every eleven change owners.
For a cache, that means a near-total cold start: almost every lookup misses at once, and the full load lands on the database behind it. For a sharded store it is worse, because nearly the whole dataset has to be copied across the network to rebalance. The Lamping and Veach paper on jump hash gives the floor for this case: going from 10 shards to 12, only one sixth of the data has to move to end up balanced. A consistent hash is any scheme that gets close to that floor, moving about K/N keys when one of N nodes joins or leaves, while still spreading keys evenly.
The hash ring
Karger and colleagues introduced the original scheme in 1997 for web caching. Picture the hash output space bent into a circle. Each node is hashed onto a point on the circle, and so is each key. To find a key's owner, start at the key's position and walk clockwise until you reach a node. That node owns the key.
The useful property follows from the geometry. When a new node lands on the circle, it takes over only the arc between itself and the node before it, so only keys in that arc move, and they all move to the newcomer. When a node leaves, its arc goes to the next node clockwise. Every other key keeps its owner. In code, a lookup is a binary search over a sorted array of node positions, so it costs O(log n) in the number of points.
Virtual nodes fix uneven arcs
With one point per node, the arcs come out very unequal, because random points on a circle do not space themselves evenly. The Dynamo paper from Amazon names exactly this problem: random placement leads to uneven data and load, and the basic algorithm also ignores the fact that some machines are bigger than others. The standard fix is to give each physical node many points, called virtual nodes or tokens. With enough tokens per node, the arcs average out. The paper by Karger and colleagues reached a 3.2 percent standard deviation in keys per bucket by using 1,000 points per bucket, which shows how many points it can take to get really tight balance.
Virtual nodes also help failover: a dead node's many small arcs scatter across many survivors instead of landing on one neighbor. Capacity becomes adjustable too, since a bigger machine can get more tokens. The price is that every client keeps the full sorted token list.
Replicas and the preference list
Rings also give a natural way to place replicas. Dynamo stores each key on the first node clockwise and copies it to the next N-1 distinct physical nodes, skipping any tokens that belong to a machine already in the list. That ordered list of owners is the key's preference list. The skip matters: without it, two adjacent virtual nodes on the same host could leave a key with fewer real copies than intended.
Rendezvous hashing: no ring at all
Rendezvous hashing, also called highest random weight hashing, came from David Thaler and Chinya Ravishankar in 1996, about a year before the ring paper. It skips the circle entirely. For a given key, score every node by hashing the pair (node, key) together, then pick the node with the highest score. Every client that knows the same node list reaches the same answer without coordinating.
When a node is removed, only the keys it was winning move, and each one goes to its own runner-up, so the removed node's load spreads evenly across everyone else without any virtual nodes. Taking the top k scores instead of the top one gives k replica locations for free. The cost is lookup time: scoring every node makes each lookup O(n). That is cheap for a few dozen backends and wasteful for thousands, where a tree-structured variant or a ring is the better fit. Weighted variants exist; one maps the hash to a number u between zero and one and scores each node as weight / -ln(u).
Jump consistent hash: no memory at all
In 2014, John Lamping and Eric Veach at Google published jump consistent hash, which fits in a handful of lines and needs no data structure at all. It takes a 64-bit key and a bucket count and returns a bucket number from 0 to num_buckets minus 1. Here is the C++ version from the paper:
int32_t JumpConsistentHash(uint64_t key, int32_t num_buckets) {
int64_t b = -1, j = 0;
while (j < num_buckets) {
b = j;
key = key * 2862933555777941757ULL + 1;
j = (b + 1) * (double(1LL << 31) / double((key >> 33) + 1));
}
return b;
}The intuition: imagine growing the cluster one bucket at a time. When bucket j+1 is added, each key should move to it with probability 1/(j+1), which is exactly what keeps the spread even. Instead of simulating every step, the loop uses a pseudo-random sequence seeded by the key to jump straight to the next bucket count at which this key would move. The paper shows the expected number of loop iterations is below ln(n) + 1, so even millions of buckets take only a few dozen steps.
The catch is the interface. Buckets are just integers in a range, so you can only grow or shrink from the end. You cannot remove bucket 4 out of 10 when its server dies. The authors say plainly that this makes it a good fit for data storage, where each bucket is a long-lived shard backed by replicas, and a poor fit for caches made of servers that can disappear at random. A common pattern is to jump-hash keys onto logical shard numbers and keep a separate, small table that maps each shard to whichever machines currently serve it.
A worked comparison you can run
The script below puts 100,000 keys on 10 nodes, adds an eleventh node, and reports two numbers for each scheme: the share of keys that changed owner, and how loaded the busiest node is compared with a perfect 1/11 share. The ideal result is about 9.1 percent moved, which is 1/11, and a busiest node at 1.00x. It uses only the standard library and a stable hash, because Python's built-in hash() for strings is salted differently in each process.
import bisect
import hashlib
from collections import Counter
def h64(s: str) -> int:
"""Stable 64-bit hash (Python's built-in hash() is salted per process)."""
return int.from_bytes(hashlib.blake2b(s.encode(), digest_size=8).digest(), "big")
def mod_n(key, nodes):
return nodes[h64(key) % len(nodes)]
class Ring:
def __init__(self, nodes, vnodes=100):
self.points = sorted((h64(f"{n}#{i}"), n) for n in nodes for i in range(vnodes))
self.hashes = [p for p, _ in self.points]
def lookup(self, key):
i = bisect.bisect(self.hashes, h64(key)) % len(self.points)
return self.points[i][1]
def rendezvous(key, nodes):
return max(nodes, key=lambda n: h64(f"{n}:{key}"))
def jump(key: int, num_buckets: int) -> int:
b, j = -1, 0
while j < num_buckets:
b = j
key = (key * 2862933555777941757 + 1) & 0xFFFFFFFFFFFFFFFF
j = int((b + 1) * (float(1 << 31) / float((key >> 33) + 1)))
return b
keys = [f"user:{i}" for i in range(100_000)]
before = [f"node{i}" for i in range(10)]
after = before + ["node10"]
schemes = {
"mod-N": (lambda k: mod_n(k, before), lambda k: mod_n(k, after)),
"ring, 1 vnode": (Ring(before, 1).lookup, Ring(after, 1).lookup),
"ring, 100 vnodes": (Ring(before, 100).lookup, Ring(after, 100).lookup),
"rendezvous": (lambda k: rendezvous(k, before), lambda k: rendezvous(k, after)),
"jump": (lambda k: jump(h64(k), 10), lambda k: jump(h64(k), 11)),
}
for name, (old, new) in schemes.items():
moved = sum(old(k) != new(k) for k in keys)
load = Counter(new(k) for k in keys)
print(f"{name:17} moved {moved / len(keys):6.1%} "
f"busiest node {max(load.values()) / (len(keys) / 11):.2f}x average")Running it with Python 3 printed the following:
mod-N moved 90.9% busiest node 1.01x average
ring, 1 vnode moved 13.7% busiest node 2.54x average
ring, 100 vnodes moved 9.5% busiest node 1.11x average
rendezvous moved 9.2% busiest node 1.03x average
jump moved 9.1% busiest node 1.01x averageModulo hashing balances perfectly but moves nine keys in ten. A ring with a single point per node moves few keys, but its busiest node carries about two and a half times its fair share. A hundred virtual nodes bring that down to roughly 1.1x. Rendezvous and jump both sit near the ideal on both measures, rendezvous by doing more work per lookup and jump by giving up arbitrary node names.
Bounded loads: capping the hottest node
Even a well-tuned ring lets one node run noticeably hotter than average, and hot keys make that worse. In 2017 Google researchers described consistent hashing with bounded loads. Each node gets a capacity of (1 + epsilon) times the average load, and a key whose natural owner is full keeps walking clockwise until it finds a node with room. A smaller epsilon gives a flatter load but more key movement, and a larger epsilon gives the opposite. Google first used it in Cloud Pub/Sub, and an engineer at Vimeo later added it to HAProxy, where Google's write-up reports it cut cache bandwidth by close to a factor of eight.
Which one should you use?
- Hash ring with virtual nodes: when nodes have names, can fail at any time, and you want O(log n) lookups with tunable capacity per node. The default for caches and Dynamo-style stores.
- Rendezvous hashing: when the node list is small (tens, maybe low hundreds), you want even failover with no token tuning, or you need the top k nodes for replicas.
- Jump consistent hash: when buckets are numbered shards that only grow or shrink at the end, and you want zero memory and the best balance. Pair it with a shard-to-server table.
- Bounded loads on top of a ring: when the hottest node matters more than average balance, such as caches behind a load balancer with skewed traffic.
- Plain modulo: when N truly never changes, or when a full reshuffle is cheap, such as rebuilding a small in-memory cache from scratch.
Common mistakes
- Using a language's built-in, per-process salted hash. Different clients then disagree about placement. Use a stable hash such as BLAKE2, xxHash, or MurmurHash with a fixed seed.
- Running the ring with one point per node. As the script shows, the busiest node can carry well over twice its share. Start with roughly 100 to 200 virtual nodes and measure.
- Letting clients see different node lists. Consistent hashing only agrees if everyone hashes over the same membership, so membership changes need a single source of truth or a gossip protocol that converges.
- Counting replicas by virtual node instead of by physical machine. Skip tokens that belong to a host already chosen, as Dynamo does.
- Removing a middle bucket with jump hash. It only supports shrinking from the end; for an arbitrary failure, remap the shard to a new server instead.
- Forgetting that balanced keys do not mean balanced load. A few very hot keys can overload one node no matter how even the key count is; caching, key splitting, or bounded loads handle that.
The short version
Modulo placement reshuffles almost everything when the cluster resizes; consistent hashing moves roughly only the keys the new node should own. Rings with virtual nodes are the flexible default, rendezvous is simple with even failover, and jump hash wins on balance and memory when buckets are numbered shards. Measure moved keys and peak load on your own key distribution before relying on any of them.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter