Sub topic 4
Consistent hashing and the hash ring
This chapter assumes you have read the previous chapter on why data is partitioned. It also assumes you are comfortable with hash functions, sorted lists, binary search, and short Python snippets. Here you will build the mechanism that decides which node owns a key, and see why it moves little data when the cluster changes.
The problem with hash-mod-N
The simplest partitioning scheme is node = nodes[hash(key) % N]. It spreads keys evenly and needs no lookup table. The trouble starts when N changes.
If you go from 4 nodes to 5, hash(key) % 4 and hash(key) % 5 agree for only about one key in five. Roughly 80% of keys get a new owner. In a store holding terabytes, adding one node would trigger a near-total reshuffle, and every cache or replica holding the old placement becomes wrong at once.
A good scheme should satisfy two properties:
- Balance: each node owns roughly the same share of keys.
- Minimal disruption: when a node joins or leaves, only the keys that must move do move, which is about 1/N of them.
Consistent hashing gives you the second property directly. The first needs extra work, which the next chapter covers.
The hash ring
Consistent hashing treats the output range of the hash function as a circle. With a 64-bit hash, positions run from 0 to 2^64 - 1, and the position after the largest value wraps around to 0.
The rules are short:
- Hash each node's identifier (for example
"node-a") to get its position on the ring. - Hash each key with the same function to get the key's position.
- The key belongs to the first node found walking clockwise (toward larger hash values) from the key's position. That node is the key's successor.
Each node therefore owns the arc between its predecessor's position (exclusive) and its own position (inclusive). A node's arc is a contiguous range of hash values, which makes range handoff simple.
Looking up an owner
Store the node positions in a sorted list. A lookup is a binary search for the first position greater than the key's hash, with wraparound when the search runs off the end.
import bisect
import hashlib
def h(key: str) -> int:
return int.from_bytes(hashlib.md5(key.encode()).digest()[:8], "big")
class SimpleRing:
"""One point per node. Virtual nodes come in the next chapter."""
def __init__(self, nodes):
self._points = sorted((h(n), n) for n in nodes)
self._hashes = [p[0] for p in self._points]
def owner(self, key: str) -> str:
i = bisect.bisect(self._hashes, h(key)) % len(self._points)
return self._points[i][1]
def mod_owner(key: str, nodes) -> str:
return nodes[h(key) % len(nodes)]
keys = [f"user:{i}" for i in range(10_000)]
nodes4 = ["node-a", "node-b", "node-c", "node-d"]
nodes5 = nodes4 + ["node-e"]
moved_mod = sum(mod_owner(k, nodes4) != mod_owner(k, nodes5) for k in keys)
ring4, ring5 = SimpleRing(nodes4), SimpleRing(nodes5)
moved_keys = [k for k in keys if ring4.owner(k) != ring5.owner(k)]
print(f"hash-mod-N moved: {moved_mod / len(keys):.0%}")
print(f"ring moved: {len(moved_keys) / len(keys):.0%}")
print("all moved keys went to node-e:",
all(ring5.owner(k) == "node-e" for k in moved_keys))Run it and you should see hash-mod-N move around 80% of the keys. The ring moves only the keys that fall in the arc the new node claimed, and the last line prints True. The exact ring percentage depends on where node-e lands. With one point per node, that arc can be much smaller or larger than 1/5 of the ring.
bisect.bisect returns the index of the first element strictly greater than the key's hash. A key whose hash exactly equals a node's position therefore goes to the next node. Any fixed rule works, as long as every node in the cluster uses the same one.
What happens when membership changes
Only the neighbors of a changed position are affected.
- Join: the new node lands between a predecessor and a successor. It takes over the part of the successor's arc that lies before its own position. Data in that range streams from the successor to the new node. No other node is involved.
- Leave or failure: the departed node's arc is absorbed by its successor, which becomes the owner of those keys.
The table compares the two approaches when going from N to N+1 nodes.
| Property | hash-mod-N | Consistent hashing |
|---|---|---|
| Keys moved on join | About N/(N+1) of all keys | About 1/(N+1) on average |
| Nodes that send data | All of them | Usually one (the successor) |
| Lookup cost | O(1) | O(log N) with binary search |
| State each node needs | Node count and list | Sorted list of ring positions |
The extra state is why consistent hashing needs a shared view of membership. If two nodes disagree about who is on the ring, they will disagree about who owns a key. Later chapters cover how gossip keeps these views converging.
Choosing the hash function
The hash only needs to spread inputs uniformly across the ring and give the same answer on every machine and in every client language. It does not need to resist attackers in most stores. MD5 is used above for convenience. Murmur3 and xxHash are common production choices because they are faster. Two rules matter more than the choice:
- Use the same function everywhere. A client library that hashes differently from the servers will route to the wrong node.
- Never use a language's built-in
hash()for placement. Python randomizes string hashing per process, so two processes would build different rings.
Edge cases and gotchas
- Wraparound: a key hashing above the last node position belongs to the first node. The
% len(...)in the lookup handles this. - Position collisions: two nodes hashing to the same position is very unlikely with 64 bits, but a production implementation should detect it and break the tie deterministically, for example by comparing node IDs.
- Uneven arcs: with one point per node, arc sizes follow a random distribution. With 4 nodes, one node can easily own twice the share of another. This is the main weakness of the plain ring.
- Uneven hardware: a plain ring gives a small machine the same expected share as a large one. You cannot weight nodes without adding more points.
- Cascading load: when a node fails, its entire arc lands on one successor. That node's load can double, which can push it over capacity and cause it to fail next.
- Hot keys: hashing balances the number of keys, not the traffic per key. A single extremely popular key still lands on one node.
Looking ahead
The lookup you wrote returns one node. A replicated store needs the next several distinct nodes clockwise from the key. That list is the key's preference list. The ring structure stays the same, and only the walk past the first successor changes.
Exercise
A ring uses positions 0 to 99. node-a sits at 10, node-b at 40, and node-c at 70. (1) Which node owns a key whose hash is 75? (2) A new node-d joins at position 55. Which hash range changes owner, from which node to which?
Show answer
(1) The first node clockwise from 75 is found by wrapping around the end of the ring to node-a at 10, so node-a owns it. (2) Before the join, node-c at 70 owned hashes 41 to 70. After node-d joins at 55, hashes 41 to 55 belong to node-d, and node-c keeps 56 to 70. So only keys with hashes 41 to 55 move, from node-c to node-d. node-a and node-b are unaffected.
Exercise
Why can a client library not simply call the language's built-in hash function to place keys on the ring?
Show answer
Placement must be identical on every client and server. Built-in hash functions may differ between languages, versions, or even processes (Python randomizes string hashing per process). Different processes would then compute different rings and send the same key to different nodes. A fixed, specified function such as Murmur3 or MD5 avoids this.