Replication
Leader-follower, multi-leader and leaderless topologies; sync vs async and the data-loss window; replication lag and the failover problems it creates.
#Three reasons to replicate
Keep copies of the same data on multiple nodes for:
- Availability — a node dies, another serves.
- Read scale — reads spread across replicas. (Note: writes do not scale this way — that's sharding. Confusing the two is a common early error.)
- Locality — a replica near the user cuts latency.
The whole difficulty is that copies must stay in agreement while accepting writes.
#Leader–follower (primary–replica)
The dominant model. One node accepts writes; changes stream to followers, which serve reads.
writes
│
▼
┌─────────┐
│ LEADER │───── replication log ────┐
└─────────┘ │
│ ┌──────────┼──────────┐
▼ ▼ ▼ ▼
reads FOLLOWER 1 FOLLOWER 2 FOLLOWER 3
│ │ │
└──── reads ──────────┘Simple and effective: one writer means no write conflicts, ever. Used by Postgres, MySQL, MongoDB, Redis, and most relational systems.
#What actually gets replicated
Worth knowing, since it drives real behavior:
- Statement-based — ship the SQL. Compact but dangerous:
NOW(),RAND(), and auto-increment produce different results on each replica. Largely abandoned. - Write-ahead log (physical) — before changing data on disk, the database records the change in an append-only log (the write-ahead log), so it can recover after a crash. Physical replication ships that log: the byte-level page changes. Exact and efficient, but every replica must use the identical on-disk format, i.e. the same database version. So you can't upgrade replicas one at a time while the old leader keeps running, which complicates zero-downtime upgrades.
- Logical (row-based) — ship "row X changed from A to B." Decoupled from storage format, so it supports version-mixed replication and, crucially, change data capture into other systems.
#Synchronous vs asynchronous
The most important tradeoff in replication, and a guaranteed follow-up question. It comes down to one thing: when the leader tells the user "saved", how many copies actually have it?
Asynchronous — the leader saves and replies straight away; copying to the followers happens afterwards, in the background.
- Fast writes; leader unaffected by slow/dead replicas.
- If the leader dies, unreplicated writes are lost. Acknowledged to the user, then gone.
Synchronous — leader waits for replica acknowledgment before responding.
- Zero data loss on failover.
- Every write pays the replica's round trip — and when the replica has a slow moment (a garbage-collection pause, a busy disk), every write waits through it too. If the replica is down or slow, writes block — one replica failure becomes a total write outage.
Semi-synchronous — the practical compromise, and the right thing to propose. Wait for one replica (or a quorum) to acknowledge, others async.
Leader ──ack required──► Replica A (sync: durability)
──fire & forget─► Replica B (async: read scale)
──fire & forget─► Replica CYou get "at least two copies exist" durability without depending on all replicas being healthy. If the sync replica dies, most systems fail over the sync role to another rather than blocking.
#Replication lag and its symptoms
Async replication means followers are behind — usually milliseconds, occasionally minutes under load, hours if something is broken. Each lag symptom maps to a session guarantee:
1. Read-your-writes violation. User updates their profile, the read hits a lagging follower, the change appears lost. Fixes:
- Route that user's reads to the leader for N seconds after they write.
- Pin the session: send all of that user's reads to one replica (or the leader), so they always read from the same copy.
- Have the client remember the log position of its last write ("I wrote at position 1042"), and only let a replica answer once it has applied at least that position.
2. Monotonic reads violation. Refresh shows 51 comments, then 49, then 51 — successive reads hitting differently-lagged replicas. Fix: pin each user to one replica (consistent hash on user ID).
3. Causal violation. A reply arrives before the post it replies to, because they came through replicas with different lag. Fix: causal tracking — each write records which earlier writes it depends on (the reply carries "I depend on post 17"), and a replica holds it back until that dependency has arrived. Or co-locate causally related data on the same partition: store a post and its replies together, so they travel through the same replication stream and always arrive in order.
Always monitor lag. It's a leading indicator of trouble and it silently breaks correctness assumptions that nothing else will surface.
#Failover — where the real problems are
When the leader dies: detect failure, choose a new leader, redirect writes. Every step has a trap, and they compound.
Detection is a guess. You infer death from missing heartbeats. Too aggressive → unnecessary failovers. Too lax → long outages. There is no correct timeout.
Split brain. The old leader isn't dead, just partitioned — cut off from the other nodes by a network fault while clients can still reach it. It keeps accepting writes while the new leader does too. Now two divergent histories exist and someone's writes must be thrown away.
Mitigations:
- Fencing tokens — every new leader gets a number one higher than the last, and storage refuses writes stamped with an older number. So a deposed leader that wakes up mid-write is rejected.
- STONITH ("shoot the other node in the head") — forcibly power off the old leader before promoting the new one.
- Majority elections — a leader needs votes from more than half the nodes. The smaller side of a split can't reach a majority, so it can't crown a second leader at all. Naming fencing tokens specifically is a strong depth signal — see Distributed Locks.
Lost writes. With async replication, a promoted follower is missing the leader's most recent writes. Those writes are gone, but they may have already been consumed elsewhere — if an order ID was returned to the user and cached downstream, discarding it creates inconsistency across systems.
Choosing the right follower. Promote the most up-to-date one (highest log position) to minimize loss.
#Multi-leader replication
Multiple nodes accept writes and replicate to each other. Used for multi-datacenter setups, offline-capable clients, and collaborative editing.
The benefit: writes are local, so latency is low and each region stays available if the link between regions breaks.
The cost: write conflicts are now possible and unavoidable. Two users edit the same record in two regions concurrently; both writes are accepted; they must be reconciled.
Conflict resolution options:
- Last-write-wins — keep the write with the latest timestamp and throw the other away. Simple, but it silently discards data. It also depends on the two regions' clocks agreeing, and real server clocks drift apart by milliseconds or more, so the "later" write may not be the one that actually happened last.
- Per-field merge — apply the latest value per field rather than per record. If one region changed a user's email and the other changed their phone number, both changes survive. Better, but still lossy when both edit the same field.
- CRDTs — data types designed so that concurrent updates can always be merged, in any order, to the same result (a counter where each region tracks its own increments and the total is their sum, for example). The principled answer when the data type allows.
- Surface both versions to the user or application.
- Avoid conflicts by design — route all writes for a given entity to one region ("home region" / partitioned ownership). Very often the right answer, and worth proposing before conflict resolution.
#Leaderless replication
No leader; clients (or a coordinator) write to several replicas directly. The Dynamo model — Cassandra, Riak, DynamoDB internally.
Quorums provide the consistency dial:
N = replicas holding each key
W = replicas that must ack a write
R = replicas that must respond to a read
If R + W > N → read and write sets overlap
→ reads see the latest write
N=3, W=2, R=2 → balanced (the usual default)
N=3, W=3, R=1 → fast reads, writes fail if any replica is down
N=3, W=1, R=1 → fastest, weakest; no overlap guaranteeBecause there's no leader, there's no failover and no split brain — any node can serve any request. That's the model's real appeal: no election, no promotion, no downtime window.
Anti-entropy mechanisms — processes that find and fix differences between replicas — keep them converging:
- Read repair — the coordinator notices a stale replica during a read and sends it the newer value.
- Hinted handoff — a live node temporarily stores writes meant for a down node, and hands them over when it comes back.
- Merkle tree comparison — each replica builds a tree of hashes over its data, where each parent hash summarises its children. Two replicas compare top hashes first and descend only into branches that differ, so they find the few mismatched keys without shipping all their data to each other. See Quorums for why
R + W > Nis weaker than linearizability.
#Choosing a topology
| Requirement | Topology |
|---|---|
| Standard web app, read-heavy | Leader–follower, async, semi-sync for durability |
| Zero data loss on failover | Leader–follower, semi-sync (quorum ack) |
| Multi-region low-latency writes | Multi-leader with per-entity home region |
| Always-writable, partition-tolerant | Leaderless with quorums |
| Strict correctness across regions | Consensus (Raft/Paxos) — see Consensus |
The line to remember for interviews: replication solves reads and availability; sharding solves writes and data volume. Most real systems need both, and stating which problem you're solving before drawing replicas keeps the discussion precise.
#Check yourself
What does replication solve, and what does it not?Show answer
Async versus sync replication: what does each risk?Show answer
Why is semi-synchronous replication the usual recommendation?Show answer
Name the three replication-lag symptoms and a fix for each.Show answer
What is split brain, and how do fencing tokens prevent damage?Show answer
Multi-leader replication makes write conflicts unavoidable. What's often the best way to deal with them?Show answer
In leaderless replication, what does R + W > N guarantee, and what's the model's main appeal?Show answer
How do leaderless systems keep replicas converging?Show answer
#What to carry forward
- Replication buys availability, read scale and locality — not write scale.
- Async risks losing acknowledged writes; sync risks blocking; semi-sync is the usual compromise. Frame it as RPO.
- Replication lag breaks session guarantees — monitor it and route reads deliberately.
- Failover is where it goes wrong: guesswork detection, split brain (use fencing tokens), and lost writes.
- Multi-leader means conflicts — prefer a home region per entity; leaderless uses quorums and anti-entropy instead of failover.