Sub topic 5
Finding the node for a key
What this chapter assumes
You have read the previous chapter, so you know that nodes and keys are hashed onto the same circular space, the hash ring. You can read simple Python and know how binary search works on a sorted list. This chapter covers the lookup step: given a key, which node owns it?
The rule: the clockwise successor
The ring is a circle of positions. A node sits at the position given by hashing its name. A key sits at the position given by hashing the key. The owner of a key is the first node you meet when you walk clockwise from the key's position.
If the walk reaches the highest position without meeting a node, it wraps around to position 0 and continues. The node with the smallest position therefore owns every key that sits after the node with the largest position.
A node owns the arc between its predecessor (the previous node counterclockwise) and itself. Every key position falls in exactly one arc, so every key has exactly one owner.
A worked example on a tiny ring
A real ring has 2^128 positions with MD5. To follow the logic by hand, use a ring of 100 positions, numbered 0 to 99, with three nodes:
| Node | Position |
|---|---|
| A | 10 |
| B | 40 |
| C | 70 |
Sorted, the positions are [10, 40, 70]. Here is a lookup function for this ring:
import bisect
positions = [10, 40, 70]
owners = {10: "A", 40: "B", 70: "C"}
def find_owner(key_position):
idx = bisect.bisect_right(positions, key_position)
if idx == len(positions):
idx = 0
return owners[positions[idx]]
for p in [5, 10, 25, 40, 69, 70, 85, 99]:
print(p, find_owner(p))bisect_right returns the index where key_position would be inserted to the right of any equal entries. That index is the first element strictly greater than the key position. If the key is greater than or equal to every position, the index equals the list length, and the code wraps it to 0.
The output is:
| Key position | Index returned | Owner | Why |
|---|---|---|---|
| 5 | 0 | A | Next node clockwise is at 10 |
| 10 | 1 | B | Exact tie goes to the next node, 40 |
| 25 | 1 | B | Next node clockwise is at 40 |
| 40 | 2 | C | Exact tie goes to the next node, 70 |
| 69 | 2 | C | Next node clockwise is at 70 |
| 70 | 3, wrapped to 0 | A | Tie, and nothing is greater, so wrap |
| 85 | 3, wrapped to 0 | A | Past the last node, so wrap |
| 99 | 3, wrapped to 0 | A | Past the last node, so wrap |
With this convention, each node owns a half-open arc that includes its predecessor's position and excludes its own. A owns 70 through 99 and 0 through 9, which is 40 positions. B owns 10 through 39, which is 30 positions. C owns 40 through 69, which is 30 positions. The three arcs cover all 100 positions with no overlap.
Why a sorted list and binary search
The lookup needs "the smallest node position greater than x". Scanning every node position works and costs O(n) for n positions. A sorted list answers the same question in O(log n) with binary search.
- Lookup: one hash computation plus one binary search. For 1,000 nodes with 100 virtual nodes each (a technique covered later), the list has 100,000 entries and binary search needs about 17 comparisons. The hash computation usually costs more than the search.
- Memory: one integer per ring position, plus a dictionary from position to node.
- Updates: inserting into a Python list with
bisect.insortis O(n) because later elements shift. Membership changes are rare compared with lookups, so this is acceptable. The next chapters show how updates affect key ownership.
A balanced tree or a skip list gives O(log n) inserts as well. For read-heavy workloads such as cache clients, a plain sorted array is simpler and faster in practice.
Putting real hashes on the ring
The same function works with real hashes. Only the position space changes: MD5 produces a 128-bit integer, so the ring has 2^128 positions. No modulo is needed on the hash, because the integer is already in range.
import bisect
import hashlib
from collections import Counter
def position(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
nodes = ["a", "b", "c", "d"]
owners = {position(n): n for n in nodes}
positions = sorted(owners)
def find_owner(key):
idx = bisect.bisect_right(positions, position(key)) % len(positions)
return owners[positions[idx]]
counts = Counter(find_owner(f"key{i}") for i in range(10000))
print(counts)Two details in this code matter:
% len(positions)is a compact way to write the wrap-around. Whenbisect_rightreturnslen(positions), the remainder is 0.- Nodes and keys go through the same
positionfunction. If they used different hash functions, the two sets of positions would live in unrelated spaces and the clockwise-successor rule would have no meaning.
The same input always produces the same counts, because MD5 is deterministic. The counts are almost certainly uneven. With four nodes and one position each, the arc lengths are four random-looking values, and some nodes own much more of the ring than others. A later chapter addresses this imbalance.
Every client computes the answer alone
A lookup needs only the sorted list of node positions and the hash function. It needs no network call and no coordinator. Any client holding the same list gets the same answer for the same key. This is what makes consistent hashing practical for cache clients and sharded stores: routing is a local computation.
The consequence is that all clients must agree on the membership list. If client X knows nodes [a, b, c, d] and client Y knows [a, b, c], they route some keys differently, and Y may write a value that X cannot find. How membership is distributed is an operational question, not part of the algorithm.
Edge cases and common errors
- Empty ring.
positions[0]or% len(positions)raises an error or divides by zero. Check for an empty ring first and raise a clear exception such asLookupError. - Missing wrap-around. Indexing
positions[idx]without handlingidx == len(positions)raisesIndexErrorfor the keys past the last node. These keys are a large share when the last node sits at a low position, so the bug shows up quickly with real data, but a test that uses only mid-ring keys will miss it. - Single node. The ring has one position. Every lookup returns that node. The code above handles this correctly:
bisect_rightreturns 0 or 1, and the remainder maps both to index 0. - Position collisions. Two nodes that hash to the same position overwrite each other in the
ownersdictionary, and one silently disappears. With 128-bit hashes this is negligible, but with small hash spaces such as 32 bits and thousands of virtual nodes, check for it when adding. - Searching the wrong list. Binary search over node names instead of node positions returns a plausible-looking but wrong answer. Search the sorted hash values, then map back to the name.
- Unsorted list.
bisectdoes not check that its input is sorted. If you append positions without keeping the list sorted, lookups return wrong owners without any error.
What lookup does not tell you yet
You can now answer "who owns this key?" You cannot yet answer "what changes when the node list changes?" Because each node owns only the arc behind it, adding or removing a node alters ownership of just the neighboring arc. The next chapter works through that case.
Exercise
A ring of 100 positions has nodes P at 20, Q at 50, and R at 90, and lookup uses bisect_right with wrap-around. Which node owns keys at positions 0, 20, 49, 50, 91, and 99?
Show answer
Sorted positions are [20, 50, 90]. Position 0: first position greater is 20, so P. Position 20: tie goes to the next greater position, 50, so Q. Position 49: 50, so Q. Position 50: tie goes to 90, so R. Position 91: nothing is greater, so wrap to 20, so P. Position 99: wrap to 20, so P.
Exercise
Your lookup function returns owners[positions[idx]] with idx = bisect.bisect_right(positions, h) and no wrap-around handling. For which keys does it fail, and what error appears?
Show answer
It fails for every key whose hash is greater than or equal to the largest node position. bisect_right returns len(positions) for them, and positions[len(positions)] raises IndexError. The fix is idx % len(positions) or an explicit reset to 0.
Exercise
Two clients route the same key. Client X hashes node names and keys with MD5. Client Y hashes keys with MD5 but computes node positions with Python's built-in hash() on strings. Why do they disagree, and what are the two separate problems?
Show answer
First, hash() on strings is randomized per process, so Y's node positions differ from X's and can change on restart. Second, even within one process, nodes and keys would be in different hash spaces, so the clockwise-successor rule would not describe a meaningful ownership. Nodes and keys must use the same stable hash function on every client.