Sub topic 6
What happens when nodes join or leave
This chapter assumes you can read the hash ring and the clockwise-successor lookup from the previous chapter. You should also know the basics of binary search and the difference between a cache and a store with replicas. Here you will work out which keys change owner when the cluster changes, how many keys that is, and what a real system has to do about it.
The two rules
A ring with a few nodes can change in two ways: a node is inserted at a new position, or a node's position is deleted. The lookup rule never changes. A key belongs to the first node found going clockwise from the key's hash. Everything below follows from that rule.
Join. Suppose a new node D lands between node P (its counter-clockwise neighbor) and node S (its clockwise neighbor). Before D arrived, every key in the arc between P and D belonged to S, because S was the first node clockwise from those keys. Now D is first, so those keys move to D. No other key sees a different first node.
Leave. Suppose D is removed. Each key that D owned now continues clockwise past D's old position and reaches S. All of D's keys go to S. Keys owned by other nodes are untouched, because removing D does not change what comes first clockwise for them.
| Event | Keys that move | Moved from | Moved to |
|---|---|---|---|
| Node D joins | Keys in the arc between D's predecessor and D | D's successor | D |
| Node D leaves | All keys D owned | D | D's successor |
Both rows share one property. A key never moves between two nodes that were both present before and after the change. On a join, keys only move to the new node. On a leave, keys only move away from the departing node. Modulo hashing has no such guarantee: changing N from 4 to 5 shuffles keys among the old nodes as well.
A worked example you can run
To see the arcs, we shrink the hash space to 100 positions and place nodes by hand. A real ring uses a 128-bit space and positions derived from a hash of the node name. The structure is the same.
import bisect
class Ring:
"""A plain ring (one position per node) over the hash space 0..99."""
def __init__(self, positions):
self.points = sorted((pos, node) for node, pos in positions.items())
def owner(self, h):
positions = [pos for pos, _ in self.points]
idx = bisect.bisect_left(positions, h) % len(self.points)
return self.points[idx][1]
def moved(before, after):
return [h for h in range(100) if before.owner(h) != after.owner(h)]
def report(label, before, after):
changed = moved(before, after)
print(
label,
len(changed),
min(changed),
max(changed),
{before.owner(h) for h in changed},
{after.owner(h) for h in changed},
)
base = Ring({"A": 15, "B": 45, "C": 80})
joined = Ring({"A": 15, "B": 45, "C": 80, "D": 60})
left = Ring({"A": 15, "C": 80})
report("join D:", base, joined)
report("leave B:", base, left)The output is:
join D: 15 46 60 {'C'} {'D'}
leave B: 30 16 45 {'B'} {'C'}The columns after each label are the number of moved hash values, the lowest moved value, the highest moved value, the old owners, and the new owners.
- Join. D sits at position 60, between B (45) and C (80). It takes hash values 46 through 60 from C, its successor. That is 15 of 100 positions, so 15% of keys move. Every moved key goes from C to D.
- Leave. B owned hash values 16 through 45, which is 30 positions. After B leaves, they all go to C, the next node clockwise. Those 30% of keys move, and A is unaffected.
The wrap-around deserves a check. A owns 81 through 99 and 0 through 15, because the lookup wraps past the end of the sorted list. In owner, the % len(self.points) does that. A join or leave near the wrap point follows the same rules, but the moved arc crosses 99 to 0, so min and max of the moved values would no longer describe a single range.
The join as a sequence of steps
The ring tells you which keys should move. A running system still has to move them. The order of operations matters most for a store, where data cannot simply be recomputed.
Two points in this order are easy to get wrong.
- Publish the new ring after the data has moved. If clients learn about D first, reads for the moved range go to an empty node. For a cache that means misses. For a store it means missing data.
- Delete from the old owner last. C keeps its copy until clients are routing to D. If the transfer fails, you can drop D from the ring and nothing was lost.
How many keys move
If the nodes are evenly balanced, each of N nodes owns about 1/N of the keys. A new node takes its share from its successor, so a join moves about 1/(N+1) of all keys. A leave from a cluster of N moves about 1/N.
| Nodes before the join | Expected share of keys that move |
|---|---|
| 3 | 25% |
| 4 | 20% |
| 9 | 10% |
| 99 | 1% |
The 4-to-5 row is the case from the modulo chapter, where about 80% of keys moved. The ring moves about 20%, which is the minimum possible: the new node must receive 1/5 of the keys, and a ring moves nothing else.
The table assumes balance, and a plain ring does not give it. Each node's share is the length of its arc, and arcs from randomly placed points vary a lot. In the worked example, D took 15% of the space because it landed in the middle of C's 35% arc. A node placed near its predecessor would take almost nothing. A node placed just before a large gap would take a lot. The 1/(N+1) figure is an average over many placements, not a promise for one join. The next chapter looks at that imbalance and the one after it fixes it.
Leaves are not all the same
The ring treats a graceful removal and a crash identically: the keys go to the successor. The data does not.
- Planned decommission. The node streams its keys to its successor, then leaves the ring. Nothing is lost.
- Crash, cache. The successor receives lookups for keys it has never seen. These are misses, and the backing database absorbs the refills. The successor's load rises by the leaver's share of traffic.
- Crash, store with replicas. If the successor already holds a replica of those keys, it can serve them immediately. Placing replicas on successive nodes is covered in a later chapter.
- Crash, store without replicas. The data is gone.
A related decision is how long a failed node stays on the ring. Removing it on the first missed heartbeat moves its keys, then moves them back when it recovers, and both moves cost traffic. Many systems mark a node as down and wait before removing it. A node that restarts with the same name gets the same positions, because positions come from hashing the name. This is why positions should be derived from a stable node name and not from something that changes on restart, such as a process ID.
Edge cases and common errors
- A successor absorbs the whole change. On a leave, one node receives all of the leaver's load. If that node is already busy, it may fail too, and its successor takes over both ranges. This cascade is a known failure mode of plain rings. Spreading each node over many positions removes it, which is the topic of the virtual nodes chapter.
- Clients disagree about membership. If clients learn about a join at different times, two clients can send the same key to different nodes. For a cache this causes duplicate entries and extra misses. For a store it can cause writes to land on the wrong node. Either use a versioned ring published from one place, or design for it: tolerate the stale window and make the old owner forward or reject requests.
- Using Python's built-in
hash(). It is randomized per process for strings, so two clients compute different positions for the same name. Use a fixed hash such as MD5, as in the earlier chapters. - An empty ring. After the last node leaves,
ownercomputes% 0and raisesZeroDivisionError. The ring implementation chapter shows an explicitLookupErrorinstead. - Two nodes hashing to the same position. With 128-bit hashes this does not happen in practice. In a small hash space like the example above, it can. A real implementation needs a rule for ties, or it will silently overwrite one node with another, as the
_ownersdictionary in a later chapter would. - Replacing a node under a new name. If a machine dies and its replacement joins as a new name, the replacement gets new positions and takes different keys. Two arcs change owner, not one. Reusing the old name restores the old arcs.
Summary of the model
Joins and leaves each affect one arc, adjacent to the changed node. Keys move only into a new node or out of a departing node. On a balanced ring, a join moves about 1/(N+1) of the keys and a leave about 1/N. A plain ring is rarely balanced, and its changes are concentrated on a single neighbor.
Exercise
A ring over hash values 0..99 has nodes A at 15, B at 45, and C at 80, using the rule "first node at or after the hash, wrapping around". Node E joins at position 30. Which node loses keys, which hash values move, and what fraction of keys moves?
Show answer
E sits between A (15) and B (45), so its successor is B. E takes the hash values 16 through 30 from B. That is 15 values, so 15% of keys move. All of them go from B to E. A and C are not affected.
Exercise
A balanced ring has 10 nodes, and each owns about 10% of the keys. One node crashes and is removed from the ring. Roughly what fraction of keys changes owner, and which node receives them on a plain ring? Name one risk that follows.
Show answer
About 10% of keys change owner. On a plain ring, all of them go to the crashed node's single clockwise successor. That node's load rises by the crashed node's share, which can overload it. If it fails as well, its successor takes both ranges and the failure can cascade. If the cluster is a cache without replicas, those keys also start as misses at the successor.
Exercise
Why should a node's ring positions be derived from a stable name, not from its current IP address or process ID?
Show answer
Positions decide which keys a node owns. If they change when the node restarts or moves to a new address, the node comes back owning different keys. Two arcs then change owner, and the node's old data does not match its new range. With a stable name, a restarted node gets the same positions and the same keys back.