Sub topic 4
The hash ring
This chapter assumes you know how hash functions and hash tables work, what a cache shard is, and how to read simple Python. It also assumes you know binary search. The previous chapter showed that hash(key) mod N remaps most keys when N changes. Here you build the structure that fixes this: the hash ring.
The core idea: one hash space for keys and nodes
Modulo hashing hashes only the key. The node is just a number from 0 to N-1, so the mapping depends on N.
A hash ring hashes both sides into the same fixed range of integers:
- Each node's name or address is hashed to a position in the range.
- Each key is hashed to a position in the same range.
Neither mapping depends on how many nodes exist. A node's position is a function of the node's identity alone. A key's position is a function of the key alone. When a node joins or leaves, no other node and no key changes position. The only open question is which node owns each key, and the ring answers that with a rule based on neighbors rather than on N.
Why it is a ring
Suppose the hash space is the integers 0 to 2^32 - 1. Lay them out on a line. Position 0 is at the left end and 2^32 - 1 is at the right end. Now join the two ends so that 2^32 - 1 is followed by 0. The line becomes a circle, and every position has a next position in the clockwise direction.
The circle matters because of the ownership rule. A key is owned by the first node you meet when you walk clockwise from the key's position. On a plain line, a key hashed beyond the last node would have no node to the right of it. On a circle, the walk wraps past the end and reaches the first node at the start of the range.
The ownership rule
For a key with position p:
- Start at
p. - Move clockwise, which means toward larger positions and wrapping from the maximum back to
0. - The first node position you reach owns the key.
This node is called the successor of the key. Each node therefore owns the arc of the circle that ends at its own position and begins just after the previous node's position. Together the arcs cover the whole circle, so every key has exactly one owner.
Read each arrow as the arc between two neighbors. The arc is owned by the node the arrow points to. The arrow from D to A crosses the point where the range wraps from the maximum to 0.
A worked example on a small ring
Use a tiny hash space of positions 0 to 99 and four nodes at hand-picked positions: A at 10, B at 40, C at 70, and D at 90.
| Node | Position | Owns positions |
|---|---|---|
| A | 10 | 91 to 99 and 0 to 10 |
| B | 40 | 11 to 40 |
| C | 70 | 41 to 70 |
| D | 90 | 71 to 90 |
Now look up some keys by their hash position:
- A key at 25 walks clockwise and reaches B at 40, so B owns it.
- A key at 41 reaches C at 70.
- A key at 40 sits exactly on B's position. Under the "at or after" convention used here, B owns it.
- A key at 95 has no node between 95 and 99. The walk wraps to 0 and continues to A at 10, so A owns it.
Arc sizes vary. A owns 20 positions, B owns 30, C owns 30, and D owns 20. Since keys are spread evenly over positions, a node's expected share of keys is proportional to its arc length. This is the source of the imbalance problem covered in a later chapter.
Here is the same lookup in code. It keeps the node positions in a sorted list and uses binary search to find the successor:
import bisect
nodes = {10: "A", 40: "B", 70: "C", 90: "D"}
positions = sorted(nodes)
def owner(point):
idx = bisect.bisect_left(positions, point) % len(positions)
return nodes[positions[idx]]
for p in (25, 40, 41, 91, 95, 5):
print(p, owner(p))It prints:
25 B
40 B
41 C
91 A
95 A
5 Abisect_left returns the index of the first node position that is greater than or equal to point. If point is larger than every node position, the index equals len(positions). The % len(positions) turns that into index 0, which is the wraparound.
Choosing the hash space and hash function
The toy range of 100 positions is only for reading. Real rings use a very large range so that collisions between two node positions are negligible. Common choices are 32-bit positions (2^32 values) or 128-bit positions from MD5 or similar hashes.
The hash function needs two properties from earlier in this tutorial:
- It must be deterministic, so every client computes the same position for the same string.
- It must spread inputs roughly uniformly, so positions are not clustered.
It does not need to be cryptographically secure. Speed and stability matter more. Do not use Python's built-in hash() for strings. Since Python 3.3 it is randomized per process, so two processes would build different rings.
Here is a ring placement using real hashes. It prints how much of the circle each node owns:
import hashlib
RING_SIZE = 2**32
def position(value):
digest = hashlib.md5(value.encode()).digest()
return int.from_bytes(digest[:4], "big")
names = ["a", "b", "c", "d"]
points = sorted((position(n), n) for n in names)
for i, (pos, name) in enumerate(points):
prev_pos = points[i - 1][0]
arc = (pos - prev_pos) % RING_SIZE
print(f"{name}: position {pos}, owns {arc / RING_SIZE:.1%}")The expression points[i - 1] gives the last node when i is 0, which is the node just before the wrap. The % RING_SIZE keeps the arc length positive for the first node, whose predecessor sits at a larger position. The four shares sum to 100%, and they are generally not equal. Four random points rarely divide a circle into four equal arcs.
Why a sorted list is enough
The ring is a mental picture. In memory it is a sorted array of node positions plus a map from position to node. Finding the successor is one binary search, which costs O(log M) for M positions on the ring. No circular data structure is needed, because the modulo on the index supplies the wrap.
Adding or removing a node means inserting or deleting positions in the sorted list. That costs O(M) with a plain Python list, but it happens rarely compared to lookups. The next chapters cover what these changes do to key ownership. The implementation chapter builds the full class.
Common errors
- Forgetting the wrap. Without the modulo, a key hashed past the last node position raises an
IndexErroror returns nothing. Test keys with hashes above the largest node position and below the smallest. - Hashing keys and nodes with different functions or ranges. If nodes use MD5 truncated to 32 bits and keys use a 64-bit hash, the two sets of positions do not share a space. Ownership then becomes meaningless, since the positions are not comparable.
- Using a per-process hash. The randomized
hash()in Python, and similar defaults in other languages, produce different rings in different processes. Use a fixed hash such as MD5 or MurmurHash. - Sorting nodes by name instead of by position. The list must be sorted by hash position. A list sorted by node name makes binary search return wrong answers.
- Assuming equal shares. A ring with few nodes gives uneven arcs. That is a property of random placement, not a bug in your code.
What the ring does and does not give you yet
The ring gives you a mapping where a node's position does not depend on N. The next chapters use that property. One covers lookup in more detail. Another measures what happens when a node joins or leaves. Another fixes the uneven arcs with virtual nodes.
At this point you have a rule that is stable under membership changes, but you have not yet measured how stable it is, and you have not yet evened out the load.
Exercise
A ring uses positions 0 to 99 with nodes at X=15, Y=50, and Z=85. Which node owns keys at positions 15, 16, 50, 86, and 99 using the "at or after" rule? How many positions does each node own?
Show answer
Position 15 goes to X, because X sits exactly there. Position 16 walks clockwise to Y at 50, so Y owns it. Position 50 goes to Y. Position 86 walks past Z at 85, so it continues to 99 and wraps to 0, then reaches X at 15, so X owns it. Position 99 also wraps to X. Arc sizes: X owns 86 to 99 and 0 to 15, which is 14 + 16 = 30 positions. Y owns 16 to 50, which is 35 positions. Z owns 51 to 85, which is 35 positions. The total is 100.
Exercise
In the lookup code, what would go wrong if you removed % len(positions) from the index calculation, and for which keys would the failure appear?
Show answer
For a key whose hash is greater than every node position, bisect_left returns len(positions). Indexing positions with that value raises an IndexError. Only keys that fall after the last node on the circle trigger it, so tests with a few random keys may pass while a small share of real keys crash the lookup.