Sub topic 6
Replicating each key to N nodes
This chapter assumes you have read the chapters on partitioning, consistent hashing, and virtual nodes. You should know that a hash ring maps each key to a position, and that each physical node owns many positions (virtual nodes). You should also be able to read short Python snippets.
Partitioning decides which node owns a key. On its own it gives you scale but not durability. If the owner's disk fails, the keys on it are gone. If the owner is unreachable, those keys are unavailable. Replication fixes both problems by storing each key on several nodes.
The replication factor N
The replication factor, written N, is the number of nodes that store a copy of each key. Common values:
| N | Typical use | Tolerates losing |
|---|---|---|
| 1 | Caches, test clusters | Nothing |
| 3 | Default for most production stores | 2 copies lost before data is gone |
| 5 | Very high durability, cross-region setups | 4 copies lost |
N is a per-cluster or per-keyspace setting, and it is usually fixed when you create the data. Raising it later means copying data to new nodes. A higher N improves durability and read availability. It also multiplies storage cost and adds write work, because every write must reach N machines.
N is not the number of nodes in the cluster. A 100-node cluster with N=3 stores each key on exactly 3 of the 100 nodes. Each node holds roughly 3/100 of the total data.
Preference lists
The preference list for a key is the ordered list of nodes responsible for storing it. The ring defines it:
- Hash the key to a position on the ring.
- Find the first virtual node at or after that position, moving clockwise.
- Keep walking clockwise, collecting the physical node behind each virtual node.
- Skip any physical node you have already collected.
- Stop when you have N distinct physical nodes.
The first node in the list is often called the coordinator for the key. It receives the request and forwards it to the others. The remaining nodes are the other replicas.
The skip rule in step 4 matters because of virtual nodes. Each physical node owns many points on the ring, so neighbouring points often belong to the same machine. If you took the next N points without checking, you could place all N copies on one machine. That would give you no fault tolerance at all.
import bisect
import hashlib
def h(key: str) -> int:
return int.from_bytes(hashlib.md5(key.encode()).digest()[:8], "big")
class Ring:
def __init__(self, nodes, vnodes=64):
self._points = sorted(
(h(f"{node}#{i}"), node) for node in nodes for i in range(vnodes)
)
self._hashes = [p[0] for p in self._points]
def preference_list(self, key: str, n: int):
"""Return up to n distinct nodes, walking clockwise from the key's position."""
start = bisect.bisect(self._hashes, h(key)) % len(self._points)
result = []
for i in range(len(self._points)):
node = self._points[(start + i) % len(self._points)][1]
if node not in result:
result.append(node)
if len(result) == n:
break
return result
ring = Ring(["node-a", "node-b", "node-c", "node-d"])
print(ring.preference_list("user:42", 3))Here is how the code works:
bisect.bisectfinds the first point whose hash is greater than the key's hash. The% len(self._points)wraps around to the start of the ring when the key hashes past the last point.- The loop walks at most one full lap of the ring. The
node not in resultcheck enforces distinct physical nodes. - If the cluster has fewer than N physical nodes, the function returns fewer than N entries. A real system should treat that as a configuration error or a degraded state, not silently accept it.
The output depends on the hash, so the exact three nodes can differ from what you expect. The result is the same on every run, because MD5 is deterministic. That property matters: every node that holds the same ring computes the same preference list without talking to anyone.
How a write reaches the replicas
When a client writes a key, the coordinator computes the preference list and sends the write to all N replicas in parallel. It does not send to one replica and wait for that one to forward it. Parallel sends keep latency close to the slowest of the replicas it waits for, instead of the sum of all of them.
The coordinator does not have to wait for all N acknowledgements. How many it waits for is the write quorum W, covered in the quorum chapter. For now, treat W as "the number of acks before we tell the client success".
The third replica still receives the write. The coordinator simply does not make the client wait for it. If that replica never answers, the store has a stale copy that later repair mechanisms fix.
A small simulation shows the fan-out. It is self-contained, so you can run it as is.
def replicate_put(replicas, key, value, up, stores):
"""Write to every replica that is up. Return the nodes that acknowledged."""
acked = []
for node in replicas:
if node in up:
stores[node][key] = value
acked.append(node)
return acked
stores = {"node-a": {}, "node-b": {}, "node-c": {}}
replicas = ["node-a", "node-b", "node-c"]
acked = replicate_put(replicas, "user:42", "alice", up={"node-a", "node-b"}, stores=stores)
print(acked) # ['node-a', 'node-b']
print(stores) # node-c has no copy of user:42With W=2 the write counts as successful, yet node-c is now missing the key. This is the central fact about replication: copies can diverge. Every later chapter on versioning, hinted handoff, and anti-entropy exists to deal with this.
Reading from replicas
Reads follow the same path. The coordinator asks some or all replicas in the preference list for the key. If all replicas held identical data, any one would do. They do not always, so the coordinator typically asks R replicas and compares the answers. If the answers differ, it must decide which is newer, using the version information described later in this tutorial.
Design decisions in replica placement
The clockwise-walk rule is simple, but it leaves several decisions open.
Failure domains
Distinct physical nodes are not always independent. Two machines in the same rack share a power supply and a switch. Two racks in the same data centre share a building. A preference list of three distinct nodes can still sit in one rack and be lost together.
Production systems extend the walk with a placement rule. For example, skip a candidate node if another node from the same rack or availability zone is already in the list. The table shows the usual trade-off.
| Placement rule | Survives | Cost |
|---|---|---|
| Distinct nodes only | Single machine failure | Lowest latency, simplest |
| Distinct racks | Rack or switch failure | Slightly more cross-rack traffic |
| Distinct zones or regions | Zone or region outage | Higher write latency, since replicas are farther apart |
The rule changes the walk in only one place. The check node not in result becomes a check on the node's rack or zone label.
Replicas are per range, not per node
A node does not mirror another node. Because of virtual nodes, each node's data is replicated across many different peers. When a node dies, its data is recovered from many nodes at once, and the recovery load is spread out. Pairing nodes as fixed mirrors would put the whole recovery load on one partner.
Membership changes move replica sets
When a node joins or leaves, the preference lists for the key ranges near its virtual nodes change. A joining node must receive copies of the ranges it now replicates. A leaving node's ranges need a new replica to restore N copies. This transfer is background work, and it competes with normal traffic for bandwidth and disk.
Common errors
- Taking the next N ring points instead of N distinct nodes. With virtual nodes this can place several copies on one machine.
- Computing preference lists differently on different nodes. If two nodes disagree about the ring, they disagree about who owns a key. Reads and writes then hit different replicas and data appears to vanish. Gossip, covered later, keeps the ring views consistent.
- Assuming N copies exist at all times. After a failure, fewer than N may exist until repair completes. Treat N as a target, not a guarantee.
- Setting N equal to the cluster size. Every node then stores everything, which removes the scaling benefit of partitioning.
- Confusing replication with backup. Replication copies a bad write or a delete to every replica. It protects against hardware loss, not against a client that deletes the wrong key.
Exercise
A cluster has 6 physical nodes, each with 128 virtual nodes, and N=3. A developer implements the preference list by taking the next 3 virtual-node points clockwise from the key's hash, without checking which physical node owns them. What goes wrong, and how do you fix it?
Show answer
Neighbouring virtual nodes can belong to the same physical node, so all 3 "replicas" may sit on one machine, and one machine failure loses every copy. The chance is real because each node owns 128 of the points on the ring. The fix is to walk clockwise and skip any virtual node whose physical node is already in the result, stopping at 3 distinct physical nodes. If failure domains matter, also skip nodes that share a rack or zone with a node already chosen.
Exercise
With N=3, a write is acknowledged by node-a and node-b, while node-c is down. The coordinator returns success. List two consequences for later reads and name what must happen for node-c to catch up.
Show answer
First, a read that contacts only node-c can return an old value or no value, so it can be stale. Second, the cluster currently holds only 2 up-to-date copies instead of 3, which lowers durability until repair. For node-c to catch up, the store needs a repair mechanism, such as hinted handoff while node-c is briefly down, read repair when a read notices the mismatch, or anti-entropy comparison of the data in the background.