Sub topic 12
Rendezvous hashing and jump consistent hash
This chapter assumes you have read the earlier chapters on the hash ring and virtual nodes. You should know why hash(key) mod N remaps most keys when N changes, and be comfortable reading short Python programs.
A ring with virtual nodes is not the only way to move few keys when a cluster changes. Two other algorithms reach the same goal with different trade-offs. Rendezvous hashing needs no ring data structure. Jump consistent hash needs no stored state at all. Both are short enough to implement from memory.
Rendezvous hashing
Rendezvous hashing is also called highest random weight (HRW) hashing. Each key scores every node, and the node with the highest score owns the key.
The score is a hash of the node name combined with the key. Every client computes the same scores, so every client picks the same owner without talking to anyone. This is the same determinism you needed from the hash function in the ring chapters.
import hashlib
def score(node, key):
return int(hashlib.md5(f"{node}:{key}".encode()).hexdigest(), 16)
def rendezvous_node(nodes, key):
return max(nodes, key=lambda node: score(node, key))
keys = [f"key{i}" for i in range(10000)]
nodes = ["a", "b", "c", "d"]
before = {k: rendezvous_node(nodes, k) for k in keys}
after = {k: rendezvous_node(nodes + ["e"], k) for k in keys}
moved = [k for k in keys if before[k] != after[k]]
print(len(moved) / len(keys))
print(all(after[k] == "e" for k in moved))The first line prints a value close to 0.2. The second prints True.
Why so few keys move
Adding node e adds one new score per key. A key changes owner only if e's score beats the old maximum. With five nodes and uniform hashes, that happens for about one key in five, and every key that moves goes to e.
Removing a node works the same way in reverse. A key moves only if the removed node was its winner. Its new owner is then the runner-up, which is the node with the second-highest score.
That last point matters. The runner-up is already well defined before any failure happens. Rendezvous hashing therefore has a built-in failover order for every key.
Replicas come for free
To pick count replicas, sort the nodes by score and take the top ones. You do not have to skip virtual nodes that belong to an already chosen machine, as you do on a ring.
def rendezvous_replicas(nodes, key, count):
ranked = sorted(nodes, key=lambda node: score(node, key), reverse=True)
return ranked[:count]Balance without virtual nodes
Each node wins about 1/N of the keys, because the scores are independent and uniform. There are no arcs of unequal length, so you do not need virtual nodes to smooth the load. The imbalance you see is only ordinary sampling noise.
Weighted nodes
On a ring, weight means giving a node more virtual nodes. In rendezvous hashing you scale the score instead. Turn the hash into a number u strictly between 0 and 1, then use -weight / ln(u) as the score.
import hashlib
import math
def weighted_score(node, weight, key):
h = int(hashlib.md5(f"{node}:{key}".encode()).hexdigest(), 16)
u = (h + 1) / (2**128 + 1)
return -weight / math.log(u)
def weighted_node(weights, key):
return max(weights, key=lambda n: weighted_score(n, weights[n], key))
weights = {"small": 1, "medium": 2, "large": 5}
counts = {n: 0 for n in weights}
for i in range(20000):
counts[weighted_node(weights, f"key{i}")] += 1
print(counts)The quantity -ln(u) / weight is an exponentially distributed random number with rate weight. The node with the smallest such value wins with probability proportional to its weight, so the counts come out near 1 : 2 : 5. Keeping the sign and the division as shown gives the same winner. The score is larger exactly when that value is smaller.
The cost: O(N) per lookup
The weakness is speed. Every lookup computes N hashes, while a ring needs one hash and a binary search. For 10 or 50 nodes this is negligible, especially next to a network call. For thousands of nodes on a hot path it hurts.
Common mitigations are caching results per key and grouping nodes hierarchically. With a hierarchy you pick a rack by rendezvous hashing, then pick a node inside the rack. Each lookup then costs roughly the number of racks plus the number of nodes per rack.
Jump consistent hash
Jump consistent hash was published by Lamping and Veach at Google. It maps a 64-bit integer key to a bucket number from 0 to N−1. It stores nothing, uses no hash table, and needs only a few lines of arithmetic.
The idea
Imagine growing the bucket count one step at a time, from 1 to N. When bucket count goes from n to n+1, a key should jump to the new bucket n with probability 1/(n+1). Otherwise it stays where it is. That rule is exactly what the minimal-movement property requires.
A key's jumps are rare, and the algorithm skips ahead. It uses a pseudo-random sequence seeded by the key to compute the next bucket count at which the key jumps. It repeats this until the next jump would pass N. The last bucket reached is the answer. The expected number of jumps is about ln N.
import hashlib
MASK = 0xFFFFFFFFFFFFFFFF
def jump_hash(key, num_buckets):
if num_buckets <= 0:
raise ValueError("num_buckets must be positive")
b, j = -1, 0
while j < num_buckets:
b = j
key = (key * 2862933555777941757 + 1) & MASK
j = int((b + 1) * ((1 << 31) / ((key >> 33) + 1)))
return b
def key64(text):
return int.from_bytes(hashlib.md5(text.encode()).digest()[:8], "big")
keys = [key64(f"key{i}") for i in range(10000)]
before = [jump_hash(k, 4) for k in keys]
after = [jump_hash(k, 5) for k in keys]
moved = [i for i in range(len(keys)) if before[i] != after[i]]
print(len(moved) / len(keys))
print(all(after[i] == 4 for i in moved))The output is again close to 0.2, followed by True. The constant is the multiplier of a 64-bit linear congruential generator. The mask keeps the arithmetic at 64 bits, as it would be in C, because Python integers do not overflow on their own.
The function takes an integer, so you must hash string keys to 64 bits first. That is what key64 does.
The limits
Jump hash balances load almost perfectly, uses constant memory, and runs in O(log N) time. The price is a restricted model:
- Buckets are numbers, not named nodes. You keep a separate table from bucket number to machine.
- You can only add or remove at the end. Going from N to N−1 buckets always removes bucket N−1. If bucket 3 of 10 fails, jump hash cannot give its keys to others without remapping. You would have to renumber, which moves data.
- There are no weights. Every bucket gets an equal share.
- There is no replication. Choosing several distinct buckets needs extra work, such as rehashing the key with different seeds and skipping duplicates.
This makes jump hash a good fit for sharded storage, where shards are numbered and a failed shard is restored or replaced in place. It is a poor fit for caches whose servers come and go in arbitrary order.
Comparing the three approaches
| Property | Hash ring with virtual nodes | Rendezvous hashing | Jump consistent hash |
|---|---|---|---|
| Lookup time | O(log(N·V)) | O(N) | O(log N) |
| Memory | O(N·V) positions | O(N) node list | O(1) |
| Keys moved on add or remove | About 1/N | About 1/N | About 1/N |
| Arbitrary node removal | Yes | Yes | No, end only |
| Weights | More virtual nodes | Score scaling | No |
| Replica selection | Walk clockwise, skip duplicates | Take top K scores | Needs extra work |
| Balance | Depends on V | Even | Very even |
Here N is the node count and V is the number of virtual nodes per node.
Common mistakes
- Hashing the node name alone. In rendezvous hashing the score must depend on both node and key. If you hash only the node, every key picks the same winner.
- A weak or inconsistent hash. If clients use different hash functions or string formats, they disagree on owners. Fix one function and one
f"{node}:{key}"format everywhere. - Passing strings to jump hash. The algorithm needs an integer. Hash the key to 64 bits first.
- Expecting zero movement on failure. All three algorithms move about 1/N of the keys when a node leaves. They reduce movement. They do not remove it, so cached data on the new owner starts cold.
- Treating replicas as free of ordering. In rendezvous hashing, replica order follows score. If clients sort with different tie-breaking, they can disagree about which replica is primary. Break ties on the node name.
Summary of the trade-off
All three techniques give the same headline result, which is that a membership change moves only about 1/N of the keys. They differ in what they ask of you:
- The ring needs memory and tuning of the virtual node count.
- Rendezvous hashing needs a linear scan per lookup.
- Jump hash needs numbered buckets that change only at the end.
Pick the algorithm whose constraint is cheapest for your system.
Exercise
A service has 8 numbered shards (0 to 7) and uses jump consistent hash. Shard 3 fails permanently and the team wants to keep serving with 7 shards. Why is jump hash a poor fit for this change, and which of the other two algorithms handles it better?
Show answer
Jump hash can only shrink by dropping the last bucket, so changing from 8 to 7 buckets removes shard 7, not shard 3. Keys owned by shard 3 would stay mapped to a dead shard. Renumbering shards to fill the gap would remap many keys. Rendezvous hashing handles it directly: remove "shard3" from the node list and only the keys that scored highest on shard 3 move, each to its runner-up. A hash ring also handles it by removing that node's virtual nodes.
Exercise
In the weighted rendezvous example, node "large" has weight 5 and node "small" has weight 1. About what fraction of keys should "large" receive if "medium" has weight 2?
Show answer
Each node wins with probability proportional to its weight, so "large" receives 5 / (1 + 2 + 5) = 5/8, or about 62.5% of the keys.