GOAT EngineerPreparing your learning space…

System Design · Concept Library · Free article

Leader–Follower Replication — Surviving the Node That Dies at 3 a.m.

How to make a stateful system survive a disk death instead of losing data to it: keep every partition on a live second machine that streams the leader’s writes — and the durability-vs-latency choice (synchronous vs asynchronous) that decision forces on you. From what a replica set is, up through the write path, the crash window, semisync and the ack-count knob, stale reads, and failover — for interns through principal engineers.

Leader–follower replication keeps every partition of your data on more than one machine — one leader that owns the writes, plus a follower that continuously streams the leader’s change log — so a single node death is survivable instead of fatal. A perfectly balanced shard is still one disk failure from disaster if it holds the only copy, and this is the fix: the follower has a live copy of every write and can be promoted to leader when the original dies. The deep choice is when the leader says “done”: synchronous replication waits for the follower to confirm each write, so a crash loses nothing — but every write pays for that confirmation and the wait climbs with load; asynchronous replication answers instantly and ships the copy afterward, so it is fast but a crash erases the writes the follower had not yet received. In between sits semisynchronous (wait for one follower of several), which is the practical default and the doorway to the next question: how many copies must confirm before a write is truly safe? Replication also creates its own gotchas — a lagging or freshly promoted follower can serve a stale read — and it is what makes automatic failover possible. It is distinct from read-replica scaling (that is a sibling topic): here the point is not more read throughput, it is not losing your data when a machine dies.

One disk died, and a fifth of the links vanished

The page comes in at 03:14: shard-04 — unrecoverable disk failure. Hatch had just finished the work everyone was proud of — a five-shard consistent-hash ring, load spread so evenly you could set a watch by it. But a balanced ring and a safe one turned out to be different things. Every shard held its slice of the link store on exactly one machine, and when shard-04’s disk failed there was no second copy anywhere. About 240 GB — roughly 20% of the whole dataset — is simply gone, with nothing to restore from. Millions of redirects for those links start returning errors. The ring did its job perfectly right up until a machine died, and then the design revealed the hole it had been hiding all along.

This is the exact wound the consistent hashing chapter left open. Balancing the ring made sure every node carried a fair share of the traffic — it never made sure any node’s data would outlive the node. Spreading load was never the same as keeping a copy. This page is the fix, and it is the idea that turns a single-machine database into something that can lose a machine and shrug: replication — keeping every piece of data alive on more than one node. By the end you will be able to lose a disk at 3 a.m. and answer the only question that matters — how much did we lose? — with nothing.

Why keep a copy — durability, not read-scaling

You have already built a copy of a database once — but for a completely different reason, and it is worth being precise about the difference, because the mechanism looks identical and the purpose is not. Back when reads from the other side of the world were slow, you stood up a read replica: a second copy that served reads so the primary could focus on writes, and so far-away users read from something nearby. That was about throughput and distance — doing more reads, faster. Useful, but notice it says nothing about what happens when a machine dies.

The problem in front of us is the other half of why you keep copies: durability — not losing the data when a node fails. A single-copy shard is a bet that the machine never dies, and machines always die eventually — a disk wears out, a power supply pops, a rack loses cooling. The fix is the same shape as a read replica (a second machine holding a copy) pointed at a different goal: the copy is there so that when the leader dies, its data does not die with it. Same machinery, different job. Play the single-copy bet below — pull the disk with no follower, then add one and pull it again:

The interactive version of this example is available when JavaScript loads.

Replica set, leader, follower — and the write path

Here is the machine, in three plain nouns. A replica set is a small group of servers that all hold the same data. Inside it, one server is the leader — every write goes to it, and it is the single source of truth. The others are followers, and each one’s whole job is to keep a live, up-to-date copy of the leader’s data, ready to take over if the leader falls. On our ring, each of the five shards stops being a lone node and becomes one of these little sets: a leader that takes the writes for its slice, and a follower shadowing it. Five single points of failure become five pairs.

How does the follower stay a faithful copy? Not by re-running the application’s logic — by replaying the leader’s change log. Every time the leader commits a write it appends the exact change to an ordered log — Postgres calls it the write-ahead log (WAL); MySQL calls it the binlog — and it streams that log to each follower, which applies the same changes in the same order to its own copy. Because it is a strict, ordered replay of what already happened on the leader, the follower ends up byte-for-byte identical, just a little behind. The leader decides; the followers faithfully repeat.

That leaves exactly one decision, and it is the one this whole page turns on: when the leader takes a write, at what moment does it tell the user “done”? Does it answer the instant it has saved the write locally and stream to the follower afterward — or does it hold the answer until the follower has confirmed it too? That single choice is the difference between fast and safe. Send a write through it below and watch where the green ACK lands:

The interactive version of this example is available when JavaScript loads.

Synchronous or asynchronous — the two answers to “when”

The two timings have names, and they are the whole fork. Asynchronous replication is speed-first: the leader saves the write locally, answers the user “success” right away, and streams the change to the follower afterward, in the background. Synchronous replication is safety-first: the leader holds the answer until the follower has confirmed it also saved the write, so “success” means the write is provably on two machines. That is the entire difference — one word, when — and everything else on this page is a consequence of it.

Each buys one thing and pays for the other. Asynchronous is fast and available — the leader never waits, so writes stay quick and a slow or briefly-down follower cannot stall them — but it is lossy on a crash, because a write that was acked before it reached the follower lives on the leader alone until the copy catches up. Synchronous is durable — a crash can never lose an acked write, since the follower already has it — but it is slower and more fragile under stress, because every write waits for the follower and a sick follower drags the whole write path down with it. Fast-but-lossy versus safe-but-slow. Neither is “correct”; the right pick depends on how much recent data you can afford to lose.

The crash window — the writes async leaves behind

Let’s make async’s catch concrete, because “loses un-acked writes” sounds abstract until you count them. Under asynchronous replication the follower is always running a little behind — a few hundred milliseconds is normal (the gap is called replication lag). During that gap, every write the leader has acked but not yet streamed lives on the leader and nowhere else. If the leader’s disk dies in that instant, exactly those writes vanish — the promoted follower comes up missing the last few hundred links, and their creators get errors on links they were just told they created. The size of that lost tail is not a vibe; it is roughly your write rate times the lag, and you can put a number on it. Drag the rate and the lag and watch the crash window:

The interactive version of this example is available when JavaScript loads.

The durability tax — why sync latency climbs with load

Synchronous replication closes the crash window completely — so why not always use it? Because the safety is not free, and the bill grows exactly when you can least afford it. Every write now waits for a round trip to the follower and its confirmation before the user hears “success.” At light load that wait is a few milliseconds, invisible. But as write volume climbs, those confirmations start to contend — for the follower’s disk, for the network, for the leader’s attention — and the wait stretches. The latency does not rise in proportion to a bigger database; it rises because more writes are queued behind each other’s confirmations. Push the traffic below and watch the synchronous line climb while the asynchronous one stays flat:

The interactive version of this example is available when JavaScript loads.

Semisynchronous — and the ack-count knob

Async and sync feel like a binary, but they are really the two ends of a dial, and most real systems live in the middle. The dial is one number: of my N followers, how many must confirm a write before I ack it? Set it to zero and you have pure asynchronous — ack immediately, hope the copies catch up. Set it to all N and you have fully synchronous — wait for everyone. Set it to one and you have semisynchronous replication: the leader waits for just a single follower to confirm, then acks. That one confirmation is enough to guarantee the write survives the leader’s death (it is on at least two machines), while you only ever wait for the fastest follower, not the slowest — so a single sick follower among several doesn’t stall you. It is the sweet spot most production databases default to. Turn the knob and watch durability and latency both move:

The interactive version of this example is available when JavaScript loads.

Stale reads — a follower that hasn’t caught up

Replication solves durability, but it hands you a new gotcha for free, and it bites hardest right after a write. If you route reads to a follower to spread load, and a user reads something they just wrote, the follower may not have received it yet — so it truthfully answers “not found” for a link that genuinely exists on the leader. A moment later replication catches up and the same read succeeds. That is a stale read: a read off a copy that is behind, returning old or missing data. It shows up in two flavours here — reading a lagging follower during normal operation, and reading a freshly promoted follower that came up a hair behind the dead leader.

Failover, briefly — promote the follower

A follower is not just a backup copy sitting idle — it is a leader-in-waiting. When the leader dies, you promote a follower to become the new leader and repoint the shard’s traffic at it, and the shard keeps serving. That promotion is called failover, and it is the difference between a node death being a shrug and being an outage. Done by a human paged at 4 a.m., it can take thirty-plus minutes of that shard rejecting writes; done by an automatic controller watching heartbeats, it takes seconds and almost nobody notices. Automatic is the standard answer — waiting for a human is the slow path exactly when minutes matter most.

The durability math — how many copies, and how many nines

So one follower turns a fatal failure survivable. Why do serious systems keep three copies, then, not two? Because durability is a numbers game, and the numbers are lovely. Losing a record means losing every copy of it before you can repair — and if each copy has some small independent chance of dying in a given window, the chance of all of them dying at once is that small number multiplied by itself once per copy. Two copies square the risk; three copies cube it. Each copy you add doesn’t subtract from the danger, it multiplies it away. Drag the copy count and the per-copy risk and watch the durability “nines” climb:

The interactive version of this example is available when JavaScript loads.

Measuring and operating replication

Replication fails quietly. Nothing lights up red when a follower falls behind — writes still succeed, reads still return, and the danger only reveals itself the instant the leader dies and you discover how much the follower was missing. So the whole job of operating replication is to make the invisible visible: measure the gap before it costs you. Two numbers frame everything — RPO (how much data a failure can lose) and RTO (how long you’re down after one) — and the metrics below are how you keep both honest.

What to watch on a replicated cluster

  • *Replication lag, per follower — in time and in log bytes.* Seconds-behind tells you your live RPO under async; bytes-behind (WAL/binlog position) tells you how much unshipped log is piled up. A lag that climbs instead of hovering is a follower that can’t keep up — a future data-loss event forming in slow motion.
  • Follower health and count in-sync. How many followers are currently caught up enough to be promoted? If your durability rests on “at least one synchronous follower” and that count drops to zero, you are running on a single copy again without knowing it.
  • Write-ack latency, split by mode. Under sync, chart the p99 wait for the follower confirmation — this is the durability tax, and a spike here is a sick follower dragging every write down. Alert before it eats your SLO.
  • Un-acked / at-risk write depth (your live RPO). Write rate × lag — the size of the tail that would vanish in a crash right now. Turn it into a dashboard number and an alert, not a post-incident surprise.
  • Failover time (RTO), measured in game-days. Don’t guess how long promotion takes — kill a leader in staging on a schedule and time the whole recovery. An untested failover is a failover that doesn’t work when you need it (more on the failover page).

The cost, and when NOT to reach for synchronous

Replication is not free, and treating synchronous as the always-on default is a classic over-correction. Every copy is a full machine’s worth of storage and compute you now pay for — two copies double your fleet, three triple it — plus the operational weight of streaming, monitoring lag, and running failover. And synchronous specifically buys its zero-RPO with real money: higher write latency on every request, and a new failure mode where a sick follower can stall your writes entirely. The senior move is to match the guarantee to the data, not to reflexively pick the safest-sounding option.

When to dial replication down (or off)

  • Data you can regenerate. A cache, a derived search index, a materialized rollup — if you can rebuild it from the source of truth, you don’t need to replicate it for durability; you need it to reload fast. Spend the durability budget on the source, not the derivative.
  • Loss-tolerant, latency-critical writes. For a metrics firehose or click stream where losing the last half-second in a rare crash is genuinely fine, asynchronous (or a local buffer) is the right call — paying synchronous latency on every event to protect data you’d shrug at losing is a bad trade.
  • A single-node app that isn’t there yet. Early on, a well-backed-up single primary with point-in-time recovery may be enough. Replication earns its cost when downtime or data loss actually hurts — don’t build a five-node replica set for a service ten people use.
  • Fully-synchronous across a wide distance. Waiting for a follower an ocean away means every write pays a cross-region round trip — often 100+ ms. Reserve cross-region synchronous for the rare data that must never lose a write even to a regional disaster; for the rest, replicate async across regions and sync within one.

Where this runs — Postgres, MySQL, Kafka, Mongo

Every serious datastore ships leader–follower replication, and once you know the shape you’ll spot it everywhere: one node owns the writes, a change log streams to copies, and a knob decides how many must confirm before an ack. The names differ; the machine is identical.

The replication landscape — the same leader-follower machine, and each system’s knob for how many copies must confirm a write.
SystemHow it replicatesThe sync knob
PostgreSQLStreams the write-ahead log (WAL) to standby serverssynchronous_commit + synchronous_standby_names (e.g. ANY 1 (s1, s2)); async by default
MySQL / MariaDBShips the binlog to replicas that replay itAsync by default; the semisync plugin waits for one replica to ack
MongoDBReplica set; secondaries tail the primary’s oplogPer-write writeConcern: w:1 (fast) up to w:"majority" (durable)
Apache KafkaPartition leader replicates to in-sync replicas (ISR)acks=all + min.insync.replicas=2 — the producer-side ack count
RedisAsync replication to replicas by defaultThe WAIT numreplicas command asks for N acks on demand
Managed (RDS / Aurora / Cloud SQL)Multi-AZ synchronous standby, promotion handled for youA checkbox: “Multi-AZ” turns on a synchronous standby + auto-failover

Notice the last column is the same idea every time — Postgres’s synchronous_standby_names, MySQL’s semisync, Mongo’s w:"majority", Kafka’s acks=all with min.insync.replicas — all of them are the ack-count knob from earlier, wearing different config syntax. Learn the knob once and every product’s durability settings read like dialects of one language.

Show me the shape

You almost never hand-roll replication — the database does it — so the “code” that matters is the write path it runs and the config knob you set. Here is the shape in words you can turn into any system.

  1. A write lands on the leader. The leader appends the change to its ordered log and applies it locally: wal.append(change); apply(change). This log is the single source of truth the followers replay.
  2. The leader streams the log to each follower, which replays it in order: follower.apply(wal.since(follower.position)). The follower’s position is how far it has caught up — the gap to the leader’s head is the replication lag.
  3. Asynchronous: the leader acks the client the moment step 1 finishes — return ok — and step 2 happens in the background. Fast; a crash before the follower catches up loses the tail.
  4. Synchronous / semisync: the leader waits for confirmations before acking — await confirmsFrom(followers, requiredAcks); return ok. Set requiredAcks to your knob: 0 (async), 1 (semisync), all (fully sync). This one line is the whole durability-vs-latency tradeoff.
  5. On leader death, a controller detects the missing heartbeat, promotes the most-caught-up follower (newLeader = mostCaughtUp(followers)), and repoints the router — the failover path. Picking a follower and agreeing on it safely is where consensus enters, next chapter.

Pitfalls that bite in production

  • Assuming asynchronous means “no data loss.” It doesn’t — async acks before the follower has the write, so a leader crash loses the un-acked tail. If your product promised zero loss, async quietly broke that promise. Know your RPO.
  • Reaching for fully-synchronous everywhere. Waiting for all followers means one slow or dead follower stalls every write, and latency scales with load. Semisync (wait for one) gives you crash-durability without hostage-taking the write path.
  • Reading your own write off a lagging follower. Route a just-written key to a behind follower and the user sees their own change vanish. Pin recent writers to the leader — see read replicas.
  • Replicas that share a failure domain. Three copies in one rack or one region die together — the durability math assumes independence you didn’t buy. Spread copies across racks, zones, and (for critical data) regions.
  • No tested failover. A follower that can be promoted “in theory” is worthless if promotion has never been rehearsed. Game-day it; an untested failover fails when you need it.
  • Ignoring replication lag until it’s an incident. A silently climbing lag is a growing RPO and a slower failover. Alert on lag (time and bytes), not just on the leader being up.
  • Forgetting the split-brain risk. If a promoted follower and a recovered old leader both accept writes, you get divergent data. Fencing the old leader is essential — the failover page goes deep.

Best practices

  • Default to semisynchronous — wait for one follower to confirm. It closes the crash window (the write is on two machines) while you only ever wait for the fastest follower, not the slowest.
  • Keep 3 copies for data you cannot lose, and place them in different failure domains (racks / zones / regions) so a shared fate can’t take them all at once.
  • Match the guarantee to the data — fully-sync for money and orders, async for metrics and click streams, none for anything you can regenerate. Don’t pay one price for every write.
  • Route reads deliberately — keep read-your-own-writes and any must-be-current reads on the leader; send the staleness-tolerant majority to followers for the read-scaling bonus.
  • Instrument RPO and RTO as live numbers — replication lag (time and bytes), in-sync follower count, at-risk write depth, and a game-dayed failover time — and alert on the gap, not just liveness.
  • Automate failover, and fence the old leader — promote on heartbeat loss in seconds, and make sure the deposed leader can never accept a write again (no split-brain).
  • Let the database do it — Postgres, MySQL, Mongo, Kafka, and managed clouds all ship this; your job is to set the ack-count knob and the topology, not to build replication by hand.

The interview deck — intern to principal

What is leader–follower replication and why do you need it? (intern)
A replica set is a leader that takes all writes plus followers that keep live copies by replaying the leader’s change log. You need it for durability and availability: if a node holds the only copy of its data, a disk death loses that data forever — a follower means the write survives and the shard keeps serving after promotion.
Synchronous vs asynchronous replication — the tradeoff? (intern → SDE2)
It’s about when the leader acks. Async acks immediately and ships to the follower in the background — fast, and a slow follower never blocks writes, but a crash loses any write the follower hadn’t received (non-zero RPO). Sync waits for the follower to confirm before acking — zero data loss, but every write pays a round trip and a sick follower stalls writes.
How much data can you lose, and how do you make it zero? (SDE2 → senior)
That’s your RPO. Under async it’s roughly write-rate × replication-lag — the tail acked but not yet replicated. You drive it to zero with synchronous (or semisynchronous) replication, which refuses to ack until the write is on a second machine. The price is write latency that climbs with load.
What is semisynchronous replication, and why is it the usual default? (senior)
Wait for one of several followers to confirm before acking, rather than all of them. That single confirmation guarantees the write is on two machines (survives the leader’s death), while you only ever wait for the fastest follower — so one slow or dead follower doesn’t stall writes. It’s the practical middle of the async–sync dial.
How many copies, and where do you put them? (senior → staff)
Three is the common default for must-not-lose data — losing it means losing all three at once, an astronomically small probability if they fail independently. They don’t if they share a rack, zone, or region, so spread copies across failure domains. Three copies in three zones beats three in one.
A user creates a link and immediately gets a 404 on it — what happened? (staff)
A stale read: the read was routed to a follower that hadn’t yet received the just-created write, so it truthfully returned “not found.” A moment later replication caught up and it worked. Fix by pinning recent writers’ reads to the leader for a window longer than your worst lag — don’t reach for full sync just to fix read consistency.
When the leader dies, what still isn’t solved? (principal)
Failover promotes a follower, but two hard questions remain: who decides which follower is promoted, and how many copies must confirm a write before it’s safe — with the network splitting and nodes disagreeing. Naive answers give you split-brain (two leaders) or data loss. Solving agreement safely is consensus (quorums, leader election, Raft/Paxos) — the next chapter.

The one thing to carry

The whole page collapses to a single sentence: *any data that lives on exactly one machine is one failure from gone, so keep every partition on a live follower that streams the leader’s writes — and choose when the leader acks based on how much recent data you can afford to lose. A copy turns a fatal node death into a survivable one. Synchronous never loses an acked write but taxes every write’s latency; asynchronous is fast but leaves a crash-sized tail behind; semisynchronous — wait for one of several — is the sweet spot most systems live in. And every copy you keep multiplies your durability, if* you place it somewhere that won’t die at the same time.

By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.