Sub topic 9
Implementing a ring in Python
This chapter assumes you know how a hash ring maps keys and nodes to one hash space, how virtual nodes smooth the load, and how binary search works. Here you turn that model into a small class that you can run.
Design
The ring needs two structures:
- A sorted list of hash positions. Each position belongs to one virtual node.
- A dictionary from position to the physical node that owns it.
The sorted list makes lookup fast. The dictionary tells you which node owns the position you found.
| Operation | Cost | Why |
|---|---|---|
| `get_node` | O(log V) | Binary search over V positions |
| `add_node` | O(v · V) | `insort` shifts list elements for each of v virtual nodes |
| `remove_node` | O(v · V) | `list.remove` scans the list for each virtual node |
V is the total number of virtual nodes on the ring and v is the number per node. These costs are fine for clusters with hundreds of nodes. Lookups dominate in practice, because nodes change rarely.
The code
import bisect
import hashlib
def _hash(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
class HashRing:
def __init__(self, nodes=(), vnodes=100):
self.vnodes = vnodes
self._hashes = []
self._owners = {}
for node in nodes:
self.add_node(node)
def add_node(self, node):
for i in range(self.vnodes):
h = _hash(f"{node}#{i}")
bisect.insort(self._hashes, h)
self._owners[h] = node
def remove_node(self, node):
for i in range(self.vnodes):
h = _hash(f"{node}#{i}")
self._hashes.remove(h)
del self._owners[h]
def get_node(self, key):
if not self._hashes:
raise LookupError("ring is empty")
idx = bisect.bisect_right(self._hashes, _hash(key)) % len(self._hashes)
return self._owners[self._hashes[idx]]How each part works
The hash function is MD5, used here only for its even spread and because it returns the same value on every run. It is not used for security. Do not use Python's built-in hash() for a ring. For strings it changes between processes, so two servers would disagree about where a key lives.
Each virtual node is named "{node}#{i}". Hashing these names places the node at vnodes scattered positions. The name is derived from the node and the index, so remove_node can recompute the same positions and delete them.
get_node hashes the key and calls bisect_right to find the first position greater than the key's hash. The % len(self._hashes) handles the wrap-around. If the key hashes past the last position, the index equals the list length, and the modulo turns it into 0, the first position on the ring.
Trying it
This script checks how evenly keys spread over three nodes.
from collections import Counter
ring = HashRing(["a", "b", "c"])
counts = Counter(ring.get_node(f"key{i}") for i in range(10000))
print(counts)Each node should receive roughly a third of the keys. Try vnodes=1 and run it again. The counts become far more uneven, which shows the imbalance that virtual nodes fix.
Common errors
- Empty ring.
get_noderaisesLookupErrorinstead of failing on% 0. Handle this explicitly. - Exact position match.
bisect_rightsends a key whose hash equals a position to the next position. With 128-bit hashes this almost never happens. All callers see the same rule, so the result stays consistent. - Hash collisions between virtual nodes. Two virtual nodes with the same hash would overwrite each other in
_owners. With MD5 this is vanishingly unlikely, but a ring with a tiny hash space, such as% 360for debugging, can hit it. - Concurrency. The class is not thread-safe. Changing
_hasheswhile another thread callsget_nodecan give wrong answers. Guard changes with a lock, or build a new ring and swap the reference.
Checking the movement
Compare owners before and after adding a node, as the earlier chapters did with modulo hashing:
ring = HashRing(["a", "b", "c", "d"])
keys = [f"key{i}" for i in range(10000)]
before = {k: ring.get_node(k) for k in keys}
ring.add_node("e")
after = {k: ring.get_node(k) for k in keys}
moved = sum(1 for k in keys if before[k] != after[k])
print(moved / len(keys))The result should be close to 0.2, about one fifth of the keys. Every moved key goes to e, because e only takes over arcs that other nodes used to own. Modulo hashing moved about 80% in the same situation.
Exercise
In get_node, what happens if the key's hash is larger than every position in the list, and which line handles it?
Show answer
bisectright returns len(self.hashes). The expression % len(self._hashes) turns that into index 0, so the key wraps around to the first position on the ring, which closes the circle.
Exercise
Why does this chapter's ring use hashlib.md5 instead of Python's built-in hash() for strings?
Show answer
Built-in string hashing is randomized per process, so different servers would compute different positions for the same key. md5 returns the same value everywhere, and its output is evenly spread.