Sub topic 2
Finding the Node for a Key
Assume you know hash functions, caches or shards, replicas, and binary search. Consistent hashing maps both keys and nodes into the same circular hash space.
Finding a node on the ring
A hash ring is a sorted circle of hash values. Each physical node owns one or more positions on the circle. To locate a key:
- Hash the key.
- Move clockwise to the first node position at or after that hash.
- Wrap to the smallest position if the search reaches the end.
That node stores the key.
A sorted list and binary search implement this lookup in O(log N) time, where N is the number of ring positions.
import bisect
import hashlib
def hash_value(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
class HashRing:
def __init__(self, nodes):
self.positions = sorted(
(hash_value(node), node) for node in nodes
)
def get_node(self, key):
if not self.positions:
raise LookupError("ring is empty")
hashes = [position for position, _ in self.positions]
index = bisect.bisect_right(hashes, hash_value(key))
return self.positions[index % len(self.positions)][1]
ring = HashRing(["cache-a", "cache-b", "cache-c"])
print(ring.get_node("user:42"))When nodes join or leave
Adding a node changes ownership only for keys between the new position and the preceding position. Removing a node transfers its keys to the next node clockwise. The rest of the ring keeps its assignments.
This is the main advantage over hash(key) % node_count. Changing four nodes to five causes roughly 80% of keys to move. A ring with a new node moves approximately the portion covered by that node.
Why a plain ring can be uneven
With one position per node, random positions can create large and small arcs. A node owning a large arc receives more keys and traffic. A small cluster can therefore become unbalanced even when the hash function is uniform.
Virtual nodes
A virtual node is an additional ring position assigned to a physical node. Each physical node gets many positions, such as 100. The positions divide the ring into smaller intervals, so ownership becomes more even.
Virtual nodes also support weighting. A larger machine can receive more virtual positions than a smaller machine. The trade-off is more memory, more metadata, and more work when nodes change.
Exercise
A ring has 100 virtual positions per physical node. What happens to a key when a physical node is removed?
Show answer
Its virtual positions disappear, and keys in their clockwise intervals move to the next surviving physical node. Other keys keep their owners.