Course contents

05. Distributed Databases Lesson 1 of 10

Database Replication

Add read replicas and watch reads scale, lag build up, stale reads appear, sync replication slow writes, and failures hit reads and writes differently.

18 minIntermediate10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Replicas are full copies kept up to date from the primary; they add read capacity and failover targets.
  • Every write still goes through one primary and is replayed on every replica: replication does not scale writes.
  • Asynchronous replicas lag behind, so reads from them can be stale, including a user’s own fresh writes.
  • Synchronous replication keeps replicas fresh but makes every write wait for the slowest replica, and a dead replica can block writes.
  • With async replication, failing over to a replica can lose writes that were already acknowledged.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Replication keeps copies of the same data on several database servers. In the most common setup, primary–replica (also called leader–follower), one server, the primary, accepts all writes. It records each change in a log and ships that log to the replicas, which replay it in the same order. Applications send writes to the primary and can send reads to any replica.

Why it exists

Three reasons, in roughly the order teams meet them:

  • Read capacity. Most applications read far more than they write. One server has a fixed number of connections and a fixed time per query; replicas multiply the read capacity.
  • Availability and durability. If the primary dies, a replica that already has the data can be promoted. Without a copy, a dead disk means restoring from backup and losing everything since.
  • Isolation. Reports, analytics and backups run on a replica so they don't slow the primary down.

How it works

Shipping changes. The primary writes each change to its log (the write-ahead log in PostgreSQL, the binlog in MySQL) and streams it to every replica. A replica applies the changes in order, so it shows the primary's state as of some moment in the past. How far in the past is the replication lag.

Routing. Something has to send writes to the primary and reads to replicas: the application itself (two connection strings), a database proxy (ProxySQL, PgBouncer with routing, a cloud reader endpoint), or the driver. In the lesson a proxy does it.

Asynchronous replication. The primary acknowledges a write as soon as it has stored it locally and ships it afterwards. Writes are fast and unaffected by replicas, but replicas lag, and anything not yet shipped exists only on the primary.

Synchronous replication. The primary acknowledges only after the replicas have the write. Replicas are never behind what clients were told, but every write waits for the slowest replica, and if a replica cannot answer, writes wait or fail.

Semi-synchronous and quorum replication. The middle ground: wait for one replica (MySQL semi-sync, PostgreSQL synchronous_standby_names with ANY 1), or for a majority (consensus systems like etcd, CockroachDB, and the quorum writes of leaderless stores). At least one other machine has every acknowledged write, and one slow or dead replica does not block writes.

Read-your-writes. A user who just wrote something expects to see it. With async replicas that is not guaranteed. Common fixes: read from the primary for a short time after the user writes; remember the log position of the user's last write and read only from replicas that have reached it; or keep the user's session pinned to the primary for writes-then-reads flows.

When to use it

  • Read-heavy workloads where one server's reads are the bottleneck and a little staleness is acceptable for most reads.
  • Any database whose data you cannot afford to lose to a single machine failure (that is: almost every production database).
  • Separating heavy analytical queries or backups from the transactional primary.

When not to

  • Write-bound workloads. Replicas do not add write capacity; each one replays every write. Shard, batch or reduce writes instead.
  • Reads that must be current (balances before a transfer, inventory at checkout, permission checks right after a change): route those to the primary rather than replicas, or use synchronous replication for that data.
  • Before simpler fixes. A missing index or a cache in front of hot reads often removes the read load replicas were meant to absorb.

Trade-offs

Choice You gain You pay
Async replication Fast writes, replicas never block the primary Stale reads; acknowledged writes can be lost on failover
Sync replication (all replicas) Fresh replicas, no loss on failover Write latency of the slowest replica; one dead replica blocks writes
Semi-sync / quorum No single-replica dependency, at least one extra copy of every write Some write latency; still stale reads on replicas outside the quorum
More replicas More read capacity, more failover candidates More replication traffic and lag to monitor; writes unchanged
Reads from replicas by default Offloads the primary Must route read-your-writes and must-be-current reads to the primary

Alternatives

  • Caching hot reads (cache-aside) takes load off the database with lower latency than a replica, with its own staleness to manage.
  • Sharding splits data across several primaries, which scales writes as well as reads, at a large cost in complexity.
  • Multi-leader and leaderless replication accept writes in several places (multi-region writes, high write availability) and pay with conflict resolution.
  • Managed distributed SQL (Spanner, CockroachDB, Aurora's shared storage) hides replication behind consensus or a replicated storage layer.

Failure modes

  • Replica failure. Reads on it fail until the proxy stops routing to it; the remaining replicas take its share, so size for N+1. Under sync replication it can also block writes until it is removed from the synchronous set.
  • Primary failure. Writes fail until a replica is promoted and clients are pointed at it. With async replication the promoted replica may be missing the last writes the old primary acknowledged.
  • Split brain. The old primary was not really dead (a network partition) and keeps accepting writes after a replica was promoted. Two primaries diverge. Fencing (revoking the old primary's ability to write) prevents it.
  • Lag spikes. Long transactions, a replica running heavy reports, a write burst or a slow network make lag jump from milliseconds to minutes. Reads that tolerate "a bit stale" may not tolerate that.
  • A replica that falls too far behind can no longer catch up from the primary's retained log and must be rebuilt from a fresh copy.

In production

Monitor replication lag per replica and alert on it; remove replicas from read rotation when lag exceeds what the application tolerates. Automate failover (Patroni, Orchestrator, managed services), test it regularly, and know your recovery point objective (how much data a failover may lose). Use semi-sync or a synchronous standby in another zone when acknowledged writes must survive the loss of the primary. Keep must-be-current reads on the primary.

Common misconceptions

  • "Replicas make the database faster at everything." They add read capacity. Writes go through one primary and are replayed on every replica.
  • "Replication is a backup." A bad DELETE replicates to every replica within milliseconds. Backups and point-in-time recovery protect against mistakes; replicas protect against machine failure.
  • "If the write was acknowledged, it's safe." With async replication it exists on one machine until shipped. Lose that machine and the write is gone.
  • "Synchronous replication is always better." It trades write latency and write availability for freshness. For most data, semi-sync plus sensible read routing is the better balance.

Interview angle

When a design is read-heavy, add read replicas and say how reads are routed. Then expect the follow-ups: what happens to a user who reads right after writing (read-your-writes; route to the primary), what lag you expect and how you monitor it, sync or async and why, how failover works and how much data it can lose, and why replicas don't help a write-heavy workload (that's where sharding comes in). Putting numbers on it ("10k reads/s, 400 per replica at our query cost, so 30 replicas or a cache first") shows you are reasoning, not reciting.

Model assumptions

The simulation in this lesson is a simplified model, not a benchmark. Every database has 12 connections, a 30 ms mean read and a 15 ms mean write (lognormal, cv 0.4); a query waiting more than 500 ms for a connection fails. 10% of queries are writes, over 200 keys with a Zipf(1.0) popularity, so a few keys are hot. A proxy sends writes to the primary and balances reads round robin over healthy replicas (health checks every 500 ms; 2 failures eject). The primary ships each write to every replica after the network hop plus a fixed extra lag; with asynchronous replication applying it costs the replica no time, so lag is measured to arrival. Synchronous mode acknowledges once all replicas have applied the write (a further 15 ms each, their own write time) and their acknowledgements have travelled back, so a synchronous write takes the delay, the apply and the hop home; it keeps its primary connection meanwhile, so the primary has 48 connections in the synchronous steps (12 would run out). A read is counted as stale when the replica has not yet applied a write the primary had already acknowledged for that key. Changes the primary has not delivered when it crashes are lost. Promotion happens at a fixed time (detection and the decision are not modelled): the promoted replica takes over the replication links, the proxy sends writes to it, and the simulation counts the keys whose latest acknowledged write it never applied; the recap hands the role back to the rebuilt original primary. Not modelled here: catch-up of a replica after it restarts (it misses the writes of its outage) and semi-synchronous or quorum modes (see the Synchronous Replication and Quorum lessons). Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. One database does everything

    The app tier sends about 200 queries per second to a single database. Nine in ten are reads (show a product, load a profile), one in ten is a write.

    The database has 12 connections and needs about 30 ms per read, so it can serve roughly 400 reads per second. Right now it is about half busy and every query succeeds.

    Scene: The app tier sends 200 queries per second, 90% reads, to one database. It is about half busy and nothing fails.

    Key idea: Most applications read far more than they write. That ratio decides how replication helps.

  2. 2. Reads swamp the database

    Traffic grows to 450 queries per second: about 405 reads and 45 writes. The reads alone need more than the 400 per second the database can serve.

    All 12 connections stay busy, queries wait for a free one, and those that wait longer than 500 ms fail. The writes are not the problem; they suffer because the reads crowd them out.

    Scene: At 450 queries per second the single database is saturated: every connection is busy, queries wait, and some fail with a pool timeout.

    Key idea: A read-heavy workload saturates a single database on reads long before writes matter.

  3. 3. Copy the data to read replicas

    We add three read replicas: full copies of the database. The primary still takes every write and then ships each change to the replicas (the purple replication packets).

    A database proxy splits the traffic: writes go to the primary, reads are spread over the replicas. Each replica now serves about 135 reads per second, the primary only handles the writes, and the errors stop.

    Note what did not change: every write still lands on the one primary, and every replica has to apply every write too. Replicas scale reads, not writes.

    Scene: A DB proxy sends writes to the primary and reads to three replicas. The primary replicates every write to each replica. Each replica is about a third busy and nothing fails.

    Key idea: Replication scales reads by adding copies. Writes still go through one primary.

  4. 4. Replicas fall behind

    With asynchronous replication the primary answers the write as soon as it has stored it, and sends the change to the replicas afterwards. Normally they apply it a few milliseconds later.

    One second in, the replicas start applying changes 250 ms late: a long-running report on them, a burst of writes, a slower network link. Each replica’s tag now shows its lag. Nothing fails and latency is unchanged, so no alarm goes off.

    Scene: One second in, replication lag rises to about 250 ms on every replica. Requests still succeed with the same latency.

    Key idea: Asynchronous replicas are always somewhat behind. Lag is invisible in latency and error metrics; you have to measure it.

  5. 5. Reading your own old data

    A user changes their display name. The write goes to the primary, which answers "saved". The page reloads, the read goes to a replica that has not applied the change yet, and the user sees their old name.

    The new tile counts these stale reads: replica reads that missed a write the primary had already acknowledged. The hot keys, written and read most often, are hit hardest.

    The usual fixes: read from the primary for a short while after a user writes, or pass the write’s log position along and only read from a replica that has caught up to it.

    Scene: Replicas lag 250 ms behind. A share of replica reads return data older than a write the primary already confirmed: stale reads.

    Key idea: Async replication breaks read-your-writes. Fix it with routing (primary after a write, or position-aware reads), or wait for replicas on write.

  6. 6. Synchronous replication

    Switch the primary to synchronous replication: it answers a write only after every replica has applied it. Once a client hears "saved", any replica it reads from has the change. The stale reads drop to zero.

    The price is in the write path. Every write now waits for the slowest replica (about 250 ms of delay, plus its apply time and the acknowledgement’s way back), so P95 latency jumps. Reads are as fast as before.

    Scene: With synchronous replication there are no stale reads, but every write waits about 270 ms for the replicas, so P95 latency rises.

    Key idea: Synchronous replication trades write latency for fresh replicas: each write waits for the slowest replica.

  7. 7. One replica down, no writes

    One second in, Replica 3 crashes. The proxy soon stops sending it reads; the other two replicas take its share.

    But the primary still waits for Replica 3 to confirm every write, and it never will. Every write fails. With fully synchronous replication, each replica is a single point of failure for writes.

    That is why real systems use semi-synchronous replication or quorums: wait for one replica (or a majority), not all, and drop a dead replica from the set.

    Scene: Replica 3 goes offline. Reads move to Replicas 1 and 2, but every write fails because the primary waits for a confirmation Replica 3 cannot send.

    Key idea: Waiting for every replica makes writes only as available as the least available replica.

  8. 8. Async: a replica failure only costs reads

    Back to asynchronous replication, with Replica 3 still down. Writes succeed again: the primary no longer waits for anyone.

    The proxy has taken Replica 3 out of rotation, so Replicas 1 and 2 serve all 405 reads per second, about half busy each. Losing a replica costs read capacity, so keep enough replicas that the rest can carry the load. And the stale reads are back.

    Scene: Replica 3 is down and out of rotation. Writes succeed again with async replication; Replicas 1 and 2 serve all reads and are about half busy.

    Key idea: With async replication a replica failure reduces read capacity but does not block writes.

  9. 9. The primary crashes

    Replica 3 is back. One second in, the primary crashes. Reads carry on from the replicas. Every write fails: there is exactly one place writes can go, and it is gone.

    The fix is failover: at 3 s Replica 1 is promoted to be the new primary, the proxy sends writes to it, and Replicas 2 and 3 now replicate from it. Writes succeed again. But think about what Replica 1 held: with async replication, writes the old primary acknowledged in its last ~250 ms never reached it. The simulation counts them at the promotion: about 15 keys lose their latest confirmed value. Those confirmed writes are lost.

    Semi-sync replication (at least one replica confirmed every write) or consensus-based failover avoid that loss, at the cost of write latency.

    Scene: The primary goes offline. Reads keep succeeding from the replicas; every write fails until Replica 1 is promoted at three seconds. About 15 keys lose their latest acknowledged write, which existed only on the failed primary.

    Key idea: Async replication plus failover can lose writes the client was told were saved. The lag is the size of the loss window.

  10. 10. What replication gives you, and costs

    The old primary has been rebuilt and given its role back, and everything is healthy again, with replicas a few tens of milliseconds behind. Replication gives you read capacity, copies for failover and a place for reports and backups. It does not give you write capacity: for that you shard.

    Every design picks a point between two risks. Async: fast writes, stale reads, possible loss of acknowledged writes on failover. Sync: fresh replicas and no loss, slower writes, and writes that depend on replica health. Most production setups land in between (semi-sync, quorums) and route read-your-writes traffic to the primary.

    Scene: The primary and all three replicas are healthy. Replication is asynchronous with about 30 ms of lag; reads are spread over the replicas and writes go to the primary.

    Key idea: Replicas scale reads and protect data, but you choose between write latency and freshness, and between availability and durability on failover.