TExcelTAD
Home › System Design › Replication and Quorums

Replication and Quorums

Replication keeps copies of the same data on several machines. It serves three goals at once: durability (a dead disk doesn't lose data), availability (another copy can answer) and read scaling (reads spread over copies). The hard part is keeping the copies in agreement while writes keep coming.

Leader-follower (primary-replica)

The most common setup. One node, the leader, accepts all writes and streams its change log to followers. Reads may go to any node.

text
           writes
 client ---------> [ leader ] ---- change log ----> [ follower 1 ]
                        \----------------------------> [ follower 2 ]
 client <------- reads from any node (followers may lag)
Replication mode Leader acknowledges a write after… Durability Write latency
Synchronous every follower has it Best Slowest; one slow follower blocks writes
Semi-synchronous at least one follower has it Good Medium
Asynchronous its own disk has it Recent writes can be lost on failover Fastest

Here's an asynchronous leader whose followers apply the log at different speeds, and what happens when the leader dies:

python · try it yourself
class Node:
    def __init__(self, name):
        self.name, self.log = name, []

leader = Node("leader")
followers = [Node("f1"), Node("f2")]
apply_rate = {"f1": 2, "f2": 1}               # log entries applied per tick

writes_per_tick = [["a=1", "b=2", "c=3"], ["a=4", "d=5", "b=6"], ["e=7", "a=8", "c=9"]]
for tick, batch in enumerate(writes_per_tick, start=1):
    leader.log.extend(batch)                  # acknowledged immediately
    for f in followers:
        catch_up = leader.log[len(f.log):len(f.log) + apply_rate[f.name]]
        f.log.extend(catch_up)
    lag = {f.name: len(leader.log) - len(f.log) for f in followers}
    print(f"tick {tick}: leader has {len(leader.log)} entries, lag {lag}")

print("leader crashes!")
new_leader = max(followers, key=lambda f: len(f.log))   # promote the most up-to-date
lost = leader.log[len(new_leader.log):]
print(f"promote {new_leader.name}; acknowledged writes lost: {lost}")
tick 1: leader has 3 entries, lag {'f1': 1, 'f2': 2}
tick 2: leader has 6 entries, lag {'f1': 2, 'f2': 4}
tick 3: leader has 9 entries, lag {'f1': 3, 'f2': 6}
leader crashes!
promote f1; acknowledged writes lost: ['e=7', 'a=8', 'c=9']

With asynchronous replication, failover can lose writes the client already saw succeed. That's the price of fast writes; systems that can't accept it use synchronous or quorum replication.

Replication lag problems

  • Read-after-write: a user saves a comment, the next read goes to a lagging follower, the comment "disappears". Fix: read your own recent writes from the leader.
  • Monotonic reads: two reads hit followers with different lag and time goes backwards. Fix: pin a user to one follower.
  • Split brain: a network blip makes a follower think the leader died; now two leaders accept writes. Fix: fencing tokens and consensus-based leader election (see Consensus).

Multi-leader and leaderless

Multi-leader replication lets each region accept writes and sync with the others; it gives low local write latency but needs conflict resolution (last-write-wins, merge functions, CRDTs).

Leaderless systems (Dynamo, Cassandra, Riak) send each write to N replicas and each read to several of them. Two numbers control consistency:

text
N  replicas per key
W  replicas that must acknowledge a write
R  replicas that must answer a read
If R + W > N, every read set overlaps every write set in at least one node,
so a read always sees the latest acknowledged write.
python · try it yourself
from itertools import combinations

def check(n, w, r):
    nodes = range(n)
    overlap_always = all(set(ws) & set(rs)
                         for ws in combinations(nodes, w)
                         for rs in combinations(nodes, r))
    return overlap_always

print(" N  W  R  R+W>N  every read overlaps every write?  tolerates down (write/read)")
for n, w, r in [(3, 2, 2), (3, 1, 1), (3, 3, 1), (5, 3, 3), (5, 2, 3)]:
    print(f"{n:2} {w:2} {r:2}  {str(r + w > n):5}  {str(check(n, w, r)):32}  {n - w}/{n - r}")
 N  W  R  R+W>N  every read overlaps every write?  tolerates down (write/read)
 3  2  2  True   True                              1/1
 3  1  1  False  False                             2/2
 3  3  1  True   True                              0/2
 5  3  3  True   True                              2/2
 5  2  3  False  False                             3/2

The brute-force check confirms the rule: overlap is guaranteed exactly when R + W > N. N=3, W=2, R=2 is the classic choice: it survives one node down for both reads and writes.

Quorum reads with versions

Overlap only helps if the reader can tell which copy is newest, so every value carries a version. The reader takes the highest version it got and can read-repair stale replicas on the way:

python · try it yourself
replicas = [{"v": 0, "value": None} for _ in range(3)]

def write(value, version, targets):
    for i in targets:
        replicas[i] = {"v": version, "value": value}

def quorum_read(targets):
    answers = [replicas[i] for i in targets]
    newest = max(answers, key=lambda a: a["v"])
    repaired = [i for i in targets if replicas[i]["v"] < newest["v"]]
    for i in repaired:                         # read repair
        replicas[i] = dict(newest)
    return newest["value"], repaired

write("blue", 1, targets=[0, 1, 2])
write("green", 2, targets=[0, 1])              # W=2: node 2 missed it
print("replicas:", [r["value"] for r in replicas])
value, repaired = quorum_read(targets=[1, 2])  # R=2 overlaps the write at node 1
print("read ->", value, "| repaired nodes:", repaired)
print("replicas:", [r["value"] for r in replicas])
replicas: ['green', 'green', 'blue']
read -> green | repaired nodes: [2]
replicas: ['green', 'green', 'green']

Note: R + W > N is necessary but not sufficient for strong consistency: concurrent writes, "sloppy quorums" during failures and clock-based versions can still produce anomalies. Use consensus (Raft, Paxos) when you need linearisability.

Test yourself

What is the main risk of asynchronous leader-follower replication?

  1. Slow writes
  2. Acknowledged writes can be lost if the leader fails before followers receive them
  3. Followers can't serve reads
  4. It requires an odd number of nodes

With N = 5 replicas and W = 3, what is the smallest R that guarantees reads overlap the latest write?

  1. 1
  2. 2
  3. 3
  4. 5

What does read repair do?

  1. Fixes corrupted disks
  2. Writes the newest value back to replicas that returned an older version during a read
  3. Restarts failed nodes
  4. Rebuilds indexes