Sub topic 10
Choosing replicas on the ring
This chapter assumes you have read the earlier chapters on the hash ring, clockwise lookup, and virtual nodes. You should be comfortable with bisect and with the HashRing class built in the implementation chapter. It extends single-owner lookup so each key lives on several distinct nodes.
Why one owner is not enough
The lookup so far returns one node per key. That node is a single point of failure. If it crashes, every key it owned is unreachable until the data is rebuilt somewhere else. In a cache this means a burst of misses. In a data store it means lost availability, or lost data if the disk is gone too.
The usual fix is replication. Each key is stored on R nodes, where R is the replication factor (commonly 3). Reads can use any live copy, and writes go to all of them or to a quorum.
Replication raises a placement question: which R nodes hold a given key? The answer must have three properties:
- Deterministic. Every client computes the same set from the same ring, with no coordination.
- Distinct. The
Rcopies must be onRdifferent physical machines. Two copies on one machine give no protection against that machine failing. - Stable. When a node joins or leaves, few keys should change their replica set.
The ring gives all three through one rule: start at the key's position and walk clockwise, collecting nodes.
The clockwise walk
The first owner is the node found by the normal lookup. The second replica is the next distinct node clockwise, and so on until you have R nodes. The key word is distinct. With virtual nodes, consecutive positions on the ring often belong to the same physical node. If you took the next R positions, you could get three virtual nodes of node a and end up with one real copy.
The walk visits at most one full lap of the ring, so it is bounded by the number of virtual node positions. In practice it stops after a handful of steps, because with many vnodes per node a new physical node appears quickly.
Implementation
The block below is complete and runnable. It repeats the ring from the earlier chapter, then adds get_replicas.
import bisect
import hashlib
def _hash(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
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]]
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 replicas
ring = HashRing(["a", "b", "c", "d"])
for i in range(5):
key = f"key{i}"
print(key, get_replicas(ring, key, 3))Key points in the code:
bisect_rightfinds the first position strictly after the key's hash. This is the same starting pointget_nodeuses, soget_replicas(ring, key, 1)[0]always equalsring.get_node(key).- The modulo
% len(ring._hashes)wraps the walk past the end of the list back to the start. This is the "ring" part. node not in replicasis a list scan, which is fine for smallR. For largeR, keep asetalongside the list.- The loop bound
range(len(ring._hashes))limits the walk to one lap, so the function cannot loop forever.
The first replica in the list is the primary. Many systems treat the rest as followers, so the order carries meaning. Do not sort or deduplicate with a set and lose it.
Checking the properties
Test the three properties directly instead of trusting them. The script below continues from the block above.
keys = [f"key{i}" for i in range(10000)]
R = 3
# Distinct, and the primary agrees with get_node
for k in keys:
reps = get_replicas(ring, k, R)
assert len(reps) == R and len(set(reps)) == R
assert reps[0] == ring.get_node(k)
before = {k: get_replicas(ring, k, R) for k in keys}
# Remove node "d": a key's set changes only if it contained "d"
ring.remove_node("d")
after = {k: get_replicas(ring, k, R) for k in keys}
changed = 0
for k in keys:
if "d" in before[k]:
changed += 1
survivors = [n for n in before[k] if n != "d"]
assert after[k][:len(survivors)] == survivors
else:
assert after[k] == before[k]
print("keys that lost a replica:", changed / len(keys))The two assertions in the removal step describe how replica sets behave when a node leaves:
- A key whose replica set did not contain the removed node is untouched. Its first
Rdistinct nodes are the same as before. - A key whose set contained the removed node keeps its surviving replicas in the same order. The next distinct node clockwise is appended at the end. Only one copy has to be created per affected key, and the surviving copies are the source for it.
With 4 nodes and R = 3, a key avoids a given node only if that node is the one left out of the three. The printed fraction is therefore around 0.75, not 0.25. This is expected. Replication multiplies the share of keys that touch any one node.
How much data moves
Distinguish keys whose replica set changes from copies that must be transferred.
| Event | Keys whose replica set changes | Copies to create |
|---|---|---|
| Add a node to `N` nodes | about `R / (N + 1)` of keys | about `1 / (N + 1)` of all copies |
| Remove a node from `N` nodes | about `R / N` of keys | about `1 / N` of all copies |
For 4 nodes growing to 5 with R = 3, about 60% of keys gain the new node as a replica. The new node ends up holding about 20% of all stored copies (6,000 of 30,000 with 10,000 keys). Each affected key needs only one new copy, and that copy goes to the new node. Compare this with modulo hashing, where roughly 80% of keys change their primary and the copy pattern is unrelated before and after.
Plan for this transfer. Rebuilding one node's share means reading about 1/N of all data from its peers. With a large vnode count, that read load spreads across all surviving nodes. This is a concrete benefit of virtual nodes during recovery: no single neighbor is overwhelmed.
Edge cases and failure modes
Fewer nodes than R. get_replicas returns a shorter list when the ring has fewer than count physical nodes. It does not raise. Callers that assume R copies will silently under-replicate. A stricter version fails fast:
def get_replicas_strict(ring, key, count):
replicas = get_replicas(ring, key, count)
if len(replicas) < count:
raise ValueError(
f"need {count} distinct nodes, ring has {len(replicas)}"
)
return replicasChoose based on policy. A cache can tolerate fewer copies. A store that promises durability should refuse the write.
Dead nodes. The ring describes intended placement, not health. If a replica is down, do not recompute the ring without it for a short outage. Doing that moves data for a transient fault. Keep the node on the ring, and have the client skip it for reads or hold the write for later delivery. Remove the node from the ring only when you decide the loss is permanent. Dynamo-style systems call the extra nodes consulted during an outage the walk beyond the preference list.
Uneven failure domains. The walk knows nothing about racks or availability zones. Three distinct machines can all sit in one rack. If you need zone safety, extend the skip rule: keep a node only if its zone is not already represented, falling back to repeating zones when there are not enough zones. This costs a longer walk and can leave a zone with a larger share of the data when zones differ in size.
Few vnodes. With a small vnode count, the walk may need many steps to find distinct nodes, and replica load is as uneven as primary load. The balance guidance from the virtual nodes chapter applies to replicas too.
Hash stability. Every client must use the same hash function and the same vnode naming scheme (node#i). If one client hashes differently, it computes different replica sets and reads from nodes that never received the data. Pin both in a shared library or a versioned configuration.
Summary of the rule
| Concern | Rule |
|---|---|
| Starting point | `bisect_right` on the key's hash, the same as single lookup |
| Direction | Clockwise, wrapping with modulo |
| Selection | First `R` distinct physical nodes |
| Termination | At most one lap of the ring |
| Too few nodes | Decide explicitly: return fewer or raise |
| Primary | The first element of the list |
Exercise
A ring has 6 physical nodes and replication factor R = 3. You add a seventh node. Approximately what fraction of keys gain the new node in their replica set, and what fraction of all stored copies must be created on the new node?
Show answer
About R / (N + 1) = 3 / 7, roughly 43%, of keys gain the new node in their replica set. The new node holds about 1 / (N + 1) = 1/7, roughly 14%, of all copies, so that is the share that must be created. Each affected key needs exactly one new copy.
Exercise
get_replicas(ring, "k", 3) returns ["a", "b"] on a ring built with HashRing(["a", "b"]). Why does it return two nodes, and how would you change the behavior so the caller cannot miss this?
Show answer
The ring has only two distinct physical nodes, so the walk covers the whole ring and finds only two. The function returns what it found without checking the count. Wrap it so it raises an error when len(replicas) < count, as in get_replicas_strict, or add nodes until the ring has at least R distinct nodes.
Exercise
Node "d" is removed from a ring. A key had replicas ["b", "d", "a"] before the removal. What are its replicas afterward, assuming the next distinct node clockwise after "a" was "c"?
Show answer
["b", "a", "c"]. The surviving replicas keep their order, and the next distinct node clockwise is appended at the end.