Sub topic 3
Implementing a Consistent Hash Ring in Python
Assume you know hash functions, caches, shards, replicas, and binary search. A ring stores sorted hash positions for physical nodes and virtual nodes. A virtual node is one of several positions assigned to the same physical node.
Implementing a ring
Hash keys and node positions into the same numeric space. To locate a key, find the first ring position at or after the key's hash. If the search reaches the end, wrap to position zero.
import bisect
import hashlib
def hash_value(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
class HashRing:
def __init__(self, nodes=(), virtual_nodes=100):
self.virtual_nodes = virtual_nodes
self.positions = []
self.owners = {}
for node in nodes:
self.add_node(node)
def add_node(self, node):
for number in range(self.virtual_nodes):
position = hash_value(f"{node}#{number}")
bisect.insort(self.positions, position)
self.owners[position] = node
def get_node(self, key):
if not self.positions:
raise LookupError("ring is empty")
key_hash = hash_value(key)
index = bisect.bisect_right(self.positions, key_hash)
index %= len(self.positions)
return self.owners[self.positions[index]]
ring = HashRing(["cache-a", "cache-b", "cache-c"])
print(ring.get_node("user:42"))The sorted list makes lookup logarithmic in the number of virtual positions. Adding or removing a node requires updating the ring consistently on every client.
Choosing replicas on the ring
For replication, walk clockwise from the key position and collect distinct physical nodes. Skip additional virtual positions owned by a node already selected. This prevents one physical node from receiving multiple replica slots.
| Choice | Effect |
|---|---|
| More virtual nodes | Smoother balance, but more ring metadata |
| More replicas | Better availability, but more storage and writes |
Giving bigger nodes more of the ring
Assign larger nodes more virtual nodes. For example, a node with twice the capacity can receive twice as many positions. This improves average balance but does not guarantee equal load, especially when traffic is skewed.
> callout tip > Virtual nodes improve distribution; they do not solve hot keys. A frequently requested key may still overload every replica that stores it.
Alternatives
Rendezvous hashing scores every node for a key and chooses the highest score. It is simple and often supports membership changes without ring metadata. Jump consistent hash is very compact and fast for integer bucket IDs, but it handles ordered bucket counts better than arbitrary node names.
Consistent hashing in practice
Use stable node identities, monitor ownership and hot keys, and version ring changes carefully. Replicas also need failure-aware placement so copies do not all share one host or zone.
Exercise
A ring has 100 virtual positions per node. What happens to a key when one node is removed?
Show answer
Keys assigned to that node move clockwise to the next surviving position. Other keys usually keep their owners.