Sub topic 4
Consistent hashing and the hash ring
This chapter assumes you know hash maps, can read short Python snippets, and understand why a key-value store partitions data across nodes. The last chapter covered why we partition. This one covers how to decide which node owns a key without moving most keys when the cluster changes.
The problem with modulo hashing
The simplest scheme is node = hash(key) % N. It works until N changes. Going from 3 nodes to 4 changes the result for roughly three out of four keys, so almost all data must move. In a store holding terabytes, adding one node would trigger a cluster-wide reshuffle.
The hash ring
Consistent hashing removes the dependency on N.
- Treat the output range of the hash function as a circle. The largest hash value wraps around to zero.
- Hash each node's identifier onto the circle. Each node now has a position.
- Hash a key onto the same circle. Walk clockwise until you reach a node. That node owns the key.
Each node owns the arc between its predecessor and itself. When a node joins, it takes over part of one neighbor's arc. When a node leaves, its arc passes to the next node clockwise. Only the keys in that arc move. On average that is about K/N of K keys, instead of nearly all of them.
Implementing a ring
The ring is a sorted list of hash positions. A lookup is a binary search with wrap-around.
import bisect
import hashlib
def h(key: str) -> int:
return int.from_bytes(hashlib.md5(key.encode()).digest()[:8], "big")
class Ring:
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]
keys = [f"user:{i}" for i in range(1000)]
before = Ring(["node-a", "node-b", "node-c"])
after = Ring(["node-a", "node-b", "node-c", "node-d"])
moved = [k for k in keys if before.owner(k) != after.owner(k)]
print("ring moved:", len(moved))
print("all moved keys went to node-d:", all(after.owner(k) == "node-d" for k in moved))
modulo_moved = sum(1 for k in keys if h(k) % 3 != h(k) % 4)
print("modulo moved:", modulo_moved)The % len(self._points) handles the wrap-around. A key hashed past the last node lands on the first one. Every moved key goes to the new node, and no data shuffles between the existing nodes. The modulo count will be far larger.
Common errors
- Using Python's built-in
hash(). For strings it is randomized per process, so two nodes would disagree on ownership. Use a stable hash such as MD5 or MurmurHash. - Forgetting the wrap-around. Keys past the highest node position must map to the lowest one.
- Expecting even load. With one position per node, arc sizes vary a lot, so some nodes own much more data than others. The next chapter fixes this with virtual nodes.
What the ring gives you
| Event | Modulo hashing | Hash ring |
|---|---|---|
| Add a node | Most keys move | About 1/N of keys move |
| Remove a node | Most keys move | Only that node's keys move |
| Lookup cost | O(1) | O(log N) |
The ring also provides the basis for replication. The nodes that follow the owner clockwise can hold copies of the key.
Exercise
A ring has 4 nodes. node-c fails and is removed from the ring. Which keys must be reassigned, and to which node?
Show answer
Only the keys in node-c's arc, meaning the keys that hashed between node-b and node-c. They move to the next node clockwise from node-c, which is node-d. Keys owned by the other nodes stay where they are.