Sub topic 5
Finding the node for a key
This chapter assumes you know what a hash function does, can read simple Python, and understand binary search. It also assumes you have seen the hash ring from the previous chapter: keys and nodes are both hashed onto the same circular space.
The lookup rule
To find the node that owns a key, hash the key to a position on the ring. Then walk clockwise until you reach a node position. That node owns the key. This node is the key's successor. If the walk passes the largest position, it wraps around to the smallest.
Each node owns the arc between the previous node's position and its own. In the diagram, node b owns positions 11 to 40, and node a owns positions 71 to 99 and 0 to 10.
Lookup with a sorted list
Scanning every node for each lookup costs O(N). Instead, keep the node positions in a sorted list and use binary search, which costs O(log N). Python's bisect module does the search.
The steps are:
- Hash the key to a position.
- Binary search the sorted positions for the first one greater than or equal to it.
- If the search returns an index past the end of the list, wrap to index 0.
- Look up which node sits at that position.
The example below uses a small hash space of 0 to 99 and fixed node positions, so you can check each result by hand.
import bisect
owners = {10: "a", 40: "b", 70: "c"}
positions = sorted(owners) # [10, 40, 70]
def find_node(position):
idx = bisect.bisect_left(positions, position)
if idx == len(positions):
idx = 0 # wrap around the ring
return owners[positions[idx]]
for p in [5, 10, 11, 41, 71, 99]:
print(p, find_node(p))This prints:
5 a
10 a
11 b
41 c
71 a
99 aPositions 71 and 99 are past the last node at 70. The search returns index 3, which equals the list length, so the code wraps to index 0 and picks a.
Using a real hash
In a real ring, the position is a hash of the key. The hash space is large, for example 128 bits from MD5. A node's position is a hash of its name or address, such as "10.0.0.7:6379".
import hashlib
def ring_hash(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
print(ring_hash("user:42") % 1000)Both nodes and keys must go through the same function. If a client hashes keys one way and the node list was built another way, positions no longer line up, and the client sends keys to the wrong node.
Gotchas
- Wrap-around. Forgetting the
% len(positions)or theidx == len(...)check raisesIndexErrorfor keys whose hash is above the largest node position. These are roughly the keys in the last arc, so the bug appears for some keys and not others. - Ties. The toy code uses
bisect_left, so a key hashing exactly onto a node position goes to that node. TheHashRingclass later in this tutorial usesbisect_right, so an exact tie goes to the next node. Either choice works if every client uses the same one. With 128-bit hashes, ties almost never happen. - Empty ring. With no nodes,
positionsis empty and there is no valid answer. Raise a clear error such asLookupErrorinstead of letting an index error leak out. - Stale sorted list. The list must stay sorted when nodes join or leave. Use
bisect.insortto add a position. Appending to the list and forgetting to sort breaks binary search without raising an error. It just returns wrong answers. - Different views of the ring. Two clients holding different node lists can disagree about a key's owner. Distributing the membership list is a separate problem from lookup.
Cost
| Operation | Cost |
|---|---|
| Find the node for a key | O(log N) for N ring positions |
| Add or remove a position in a Python list | O(N), because of the shift |
| Memory | One entry per ring position |
Lookups are far more common than membership changes, so a sorted list is a good fit. The next chapters look at what happens to key ownership when nodes join or leave.
Exercise
Using the ring with nodes a at 10, b at 40 and c at 70 in a space of 0 to 99, which node owns a key that hashes to 40, and which node owns a key that hashes to 70.5 if positions can be fractional? Use the "first position at or after" rule.
Show answer
A key at 40 goes to b, because 40 is at or after itself and b sits at 40. A key at 70.5 is past c at 70 and there is no later position, so it wraps around to the smallest position and goes to a.