Sub topic 9
Implementing a ring in Python
This chapter turns the hash ring into working code. It assumes you can read simple Python, know what hashlib and binary search do, and have read the earlier chapters on the ring, clockwise lookup, and virtual nodes. By the end you will have a HashRing class with add_node, remove_node, and get_node, and you will know where its edge cases are.
Design: two structures, one invariant
The ring is a circle of hash values. A computer can't store a circle, but it can store a sorted list of positions and treat the end of the list as connected to the start. The implementation needs two things:
_hashes: a sorted list of integer positions, one per virtual node. It answers "which position comes next after this key?"_owners: a dictionary from position to physical node name. It answers "who owns that position?"
The invariant is that every value in _hashes is a key in _owners, and the reverse. Every method must leave the two structures consistent.
Lookup then takes three steps.
The hash function
Both nodes and keys must go through the same function, and every client must get the same answer for the same string.
import bisect
import hashlib
def _hash(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)MD5 returns 128 bits, so positions range from 0 to 2^128 - 1. We use it for its speed and even spread, not for security. Any well-mixed hash works, such as SHA-1, MurmurHash, or xxHash.
The HashRing class
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 virtual nodes are named
Each physical node a gets vnodes positions, computed from the labels a#0, a#1, up to a#99. The labels are deterministic. This matters for removal: remove_node recomputes the same labels and so finds exactly the positions that add_node created. It does not need to store which positions belong to which node.
How lookup works
bisect_right(self._hashes, h) returns the index of the first position strictly greater than h. That is the clockwise successor. The % len(self._hashes) handles wraparound. If the key hashes past the last position, bisect_right returns len(self._hashes), and the modulo turns that into index 0, the first position on the ring.
You can check the index arithmetic on a plain list:
import bisect
positions = [10, 20, 30]
print(bisect.bisect_right(positions, 15) % 3) # 1 -> position 20
print(bisect.bisect_right(positions, 35) % 3) # 0 -> wraps to position 10
print(bisect.bisect_right(positions, 20) % 3) # 2 -> position 30The last line shows a convention. A key whose hash equals a position exactly goes to the next position, because we used bisect_right. With bisect_left it would go to that position itself. Either is fine, but every client must use the same one. Exact ties are astronomically rare with 128-bit hashes, so this matters mainly in tests with tiny hand-made rings.
Checking the claim: how many keys move
The earlier chapters claimed that adding one node to a four-node ring moves only about one fifth of the keys. You can measure that.
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 printed value is near 0.2. It varies a little with the hash function and the number of virtual nodes, because the new node's share is a random quantity. Compare this with the roughly 0.8 you get from h(k) mod 4 versus h(k) mod 5.
It is also worth verifying the stronger property: every moved key moved to the new node, never between two old nodes.
assert all(after[k] == "e" for k in keys if before[k] != after[k])If this assertion fails, the ring has a bug. For example, positions may be computed differently in add_node than at construction.
To see the load balance, count keys per node:
from collections import Counter
counts = Counter(ring.get_node(k) for k in keys)
print(sorted(counts.items()))With 100 virtual nodes per node, each of the five counts should be within a modest margin of 2000. Try vnodes=1 and compare. The spread widens sharply, which is the imbalance that virtual nodes exist to fix.
Complexity
Let V be the number of virtual nodes on the ring (physical nodes times vnodes).
| Operation | Cost | Why |
|---|---|---|
| `get_node` | O(log V) plus one hash | Binary search on a sorted list, then a dictionary lookup |
| `add_node` | O(vnodes × V) worst case | Each `insort` finds its spot in O(log V) but shifts list elements in O(V) |
| `remove_node` | O(vnodes × V) | `list.remove` scans linearly and shifts |
| Memory | O(V) | One list entry and one dictionary entry per virtual node |
For a cluster of 100 nodes with 100 virtual nodes each, V is 10,000. Shifting a list of that size is microseconds, so the simple version is fine. Lookups dominate in real workloads, and they stay fast. If you build very large rings, collect all new positions first and sort once, instead of inserting one at a time.
Edge cases and failure modes
Empty ring
get_node raises LookupError when there are no positions. Without that check, % len(self._hashes) would raise a confusing ZeroDivisionError. Callers should decide what an empty ring means, for example failing the request or falling back to the origin.
Removing a node that is not there
list.remove raises ValueError for a missing value. A partly failed remove_node can also leave the structures inconsistent: some positions are removed and the rest are not. A safer version checks membership first and treats removal as idempotent.
Adding the same node twice
Calling add_node("a") twice inserts every position twice into _hashes. The owners dictionary stays the same size, so the two structures disagree. Later, one remove_node("a") removes one copy of each position and deletes the dictionary entry. The leftover duplicates in _hashes then point to nothing, and get_node raises KeyError. Track the set of physical nodes and ignore a repeated add.
Hash collisions between virtual nodes
If two labels hash to the same position, the second overwrites the first in _owners. With 128-bit hashes the chance is negligible. With a short hash, such as 32 bits and many virtual nodes, collisions become realistic, and you would need to handle them.
Concurrent access
add_node inserts into _hashes before it writes _owners. A reader in another thread can find a position that has no owner yet and get a KeyError. Two common fixes:
- Guard both structures with a lock.
- Treat the ring as immutable. Build a new ring on membership change and swap the reference in one assignment, so readers always see a complete ring.
Replication on the same structure
For replication, the owner is the first node clockwise, and the next distinct physical nodes clockwise hold the other copies. The word distinct matters. Walking clockwise, many consecutive virtual nodes may belong to the same physical node, and placing two replicas on one machine defeats the purpose.
def get_replicas(ring, key, count):
if not ring._hashes:
raise LookupError("ring is empty")
start = bisect.bisect_right(ring._hashes, _hash(key))
replicas = []
for step in range(len(ring._hashes)):
node = ring._owners[ring._hashes[(start + step) % len(ring._hashes)]]
if node not in replicas:
replicas.append(node)
if len(replicas) == count:
break
return replicasThe loop is bounded by len(ring._hashes), so it ends even when count exceeds the number of physical nodes. In that case it returns every node, fewer than count. Callers should check the length of the result if they need a guaranteed replication factor.
print(get_replicas(ring, "key42", 3))The first element equals ring.get_node("key42"), because both start at the same index.
Summary of what the code guarantees
- The same key and the same membership give the same node, in every process.
- Adding a node only moves keys to the new node.
- Removing a node only moves that node's keys, each to the next owner clockwise.
- Balance depends on
vnodes. More virtual nodes give smoother load but cost more memory and slower membership changes.
Exercise
A ring has positions [10, 20, 30] and uses bisect_right with wraparound. Which position owns a key that hashes to 30, and which owns a key that hashes to 31?
Show answer
A key hashing to 30 goes to position 10. bisect_right returns 3, because every position is at or below 30, and 3 % 3 is 0, so the key wraps to the first position. A key hashing to 31 also goes to position 10 for the same reason. Position 30 is the owner only for hashes from 21 to 29.
Exercise
After calling ring.addnode("a") twice on the same ring, a later ring.removenode("a") leaves the ring in a broken state. What goes wrong, and how would you prevent it?
Show answer
The second add inserts a duplicate copy of each position into hashes, while owners keeps one entry per position. removenode removes one copy of each position and deletes the owners entry, so the remaining duplicates in hashes have no owner. getnode can then raise KeyError. Prevent it by keeping a set of physical node names and making addnode do nothing when the node is already present, and by making removenode do nothing for an unknown node.
Exercise
Why does getreplicas loop over at most len(ring.hashes) positions, and what does it return if count is larger than the number of physical nodes?
Show answer
The bound guarantees the loop ends after one full trip around the ring, even if there are not enough distinct nodes. If count exceeds the number of physical nodes, the loop visits every node once and returns a list with all of them, which is shorter than count. A caller that needs a fixed replication factor must check the length of the result.