Course contents

05. Distributed Databases Lesson 4 of 10

Asynchronous Replication

Fast writes that never wait for replicas, and what you pay instead: lag under write load, stale reads, and confirmed writes lost on failover.

15 minIntermediate6 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • An async primary acknowledges at its local commit and ships changes afterwards; replica distance becomes lag, not write latency.
  • A replica can fail without affecting writes, but the primary keeps its unshipped log until it returns or is rebuilt.
  • Replicas replay with far less parallelism than the primary writes, so write bursts show up as lag and stale reads, not errors.
  • Writes acknowledged within the last lag interval before a primary crash can be lost on failover: the lag is the RPO.
  • Measure lag, promote the most caught-up replica, and add semi-sync to a nearby replica where losing a confirmed write is unacceptable.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

With asynchronous replication the primary commits a write locally, acknowledges it to the client, and sends the change to its replicas afterwards. Replicas apply the stream in order and are always somewhat behind. It is the default in PostgreSQL streaming replication and MySQL replication, and the usual mode for cross-region copies in managed databases.

The Database Replication lesson shows that async replicas lag and can serve stale reads. This lesson looks at why lag grows, what a replica outage really costs, and how much confirmed data a failover can lose.

Why it exists

Because it keeps replicas out of the write path. A write takes as long as the local commit, however many replicas there are and however far away they are, and a slow or dead replica never blocks a write. For most data a short, measured window of possible loss and slightly old reads is a better deal than paying replica latency and replica availability on every write.

How it works

The write path. Client → primary → local commit (log flushed on the primary) → acknowledgement. In parallel, a sender process streams the log to each replica. The lesson shows the response leaving the primary before the replication packets arrive, even at replicas 2 ms away.

Lag. Each replica is behind by network delay plus its queue of unapplied changes. A replica in another region is behind by at least the one-way delay. Lag is usually measured as time (PostgreSQL pg_stat_replication.replay_lag, a heartbeat row written every second and read on the replica) or as log distance (bytes or LSN difference, GTID sets). MySQL's Seconds_Behind_Source is based on event timestamps and can mislead around idle periods and long transactions; a heartbeat table (as pt-heartbeat does) is more reliable.

Why lag grows under write load. The primary executes writes on many connections in parallel. Replay is far less parallel: PostgreSQL's standby replays WAL in a single startup process, and MySQL's multi-threaded applier runs a limited number of workers (replica_parallel_workers, 4 by default since 8.0.27) constrained by transaction dependencies. A write burst, a large batch update, or a long-running query on the replica that conflicts with replay (PostgreSQL max_standby_streaming_delay) all grow the backlog. The primary keeps going; the replica falls further behind; nothing fails.

Replica outages. The primary keeps the log a disconnected replica still needs: a PostgreSQL replication slot retains WAL until the replica confirms it; MySQL keeps binlogs until they expire. A long outage fills the primary's disk unless retention is capped (max_slot_wal_keep_size, binlog_expire_logs_seconds), and a replica that falls past the cap must be rebuilt from a fresh copy. A replica that returns in time replays the backlog at its normal replay speed while new changes keep arriving, so its lag drains slowly: two seconds of outage can take several seconds to make up.

Failover and the loss window. If the primary dies, changes it acknowledged but had not yet shipped exist nowhere else. Promote a replica and they are gone. Roughly, data at risk ≈ write rate × lag at the moment of the crash: 240 writes/s with 450 ms of lag puts about 100 confirmed writes at risk. In the lesson those writes touch about 50 hot keys, and promoting a replica leaves each of them with an older value than the one its writer was told was saved. That is the recovery point objective (RPO) async replication gives you, and it is largest exactly when lag spikes.

When to use it

  • The default for read replicas, analytics copies and cross-region disaster recovery.
  • When write latency matters and a small, measured RPO is acceptable.
  • When replicas are far away or numerous, so waiting for them would be slow or fragile.

When not to

  • For data where an acknowledged write must never be lost (payments, ledgers, orders): add a semi-sync or synchronous replica nearby, or use a consensus-replicated store.
  • For reads that must reflect the latest write: route them to the primary, or wait for the replica to reach the write's log position.
  • When replicas routinely lag by minutes and the application cannot tolerate it: fix the cause (replay parallelism, long queries, undersized replicas) before adding more.

Trade-offs

Aspect Async Sync / semi-sync
Write latency Local commit only Plus the round trip to the replica(s) waited for
Replica outage No effect on writes; primary retains log Blocks or slows writes unless the set adapts
Replica freshness Behind by lag; stale reads possible Fresh only for replicas waited for at apply level
Data loss on failover Up to write rate × lag None for the covered failures
Distant replicas Fine Expensive on every write

Alternatives

  • Semi-synchronous or quorum commit to one nearby replica, with remote copies left async.
  • Synchronous replication for small, critical datasets.
  • Consensus-replicated databases (CockroachDB, Spanner, YugabyteDB) that commit on a majority.
  • Shared replicated storage (Aurora, AlloyDB), where durability comes from the storage layer and read replicas lag only in their caches.
  • Logical replication / change data capture for feeding other systems, with the same async lag characteristics.

Failure modes

  • Silent lag spikes. Batch jobs, schema changes or long replica queries push lag from milliseconds to minutes; dashboards based on latency and errors stay green.
  • Loss of acknowledged writes on failover, sized by lag at the time.
  • Disk exhaustion on the primary from WAL retained for a dead replica's slot.
  • Replica too far behind to catch up from retained logs; needs a rebuild, during which read capacity is reduced.
  • Promoting the wrong replica: one that is further behind than another loses more data than necessary.
  • Stale reads after writes for users routed to replicas (read-your-writes), covered in the Replication Lag lesson.

In production

Alert on replication lag per replica (time and bytes), not just on replica health. Remove a replica from read rotation when its lag exceeds what readers tolerate (ProxySQL max_replication_lag, custom health checks). Cap retained WAL or binlogs so a dead replica cannot take the primary down. On failover, promote the replica with the highest replayed position; tools like Patroni and Orchestrator do this and can refuse to promote a replica lagging more than a configured threshold (Patroni maximum_lag_on_failover). Write down the RPO you actually have, measured from lag percentiles during your busiest jobs, and add a semi-sync replica where that RPO is not acceptable.

Common misconceptions

  • "Async replicas are a few milliseconds behind." In steady state, often. Under write bursts or long replica queries, lag can reach seconds or minutes.
  • "If it was acknowledged, it's durable." On one machine. Lose that machine before shipping and the write is gone.
  • "A dead async replica is harmless." Writes are fine, but the primary retains its log; left long enough, that can fill the disk.
  • "More replicas reduce lag." Each replica has its own lag; adding replicas changes nothing about how fast any one of them replays.

Interview angle

Default to async replicas for reads and DR, then show you know its price. Quantify the loss window ("about 1,000 writes/s × typical 100 ms lag ≈ 100 writes at risk, more during batch jobs"), say how you would monitor lag, and name the mitigations: promote the most caught-up replica, alert and throttle when lag grows, route read-your-writes traffic to the primary, and add a semi-sync replica in another zone for data that cannot be lost. Mentioning replication slot retention or replay parallelism signals real operational experience.

Model assumptions

The simulation 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). The app tier sends 400 queries/s, 30% writes, over 300 keys (Zipf 1.0); a proxy sends writes to the primary and reads to Replicas 1 and 2 by least connections. The primary answers at its local commit and ships each change to every replica after the network hop (2 ms in Region A, 70 ms to Replica 3 in Region B). Each replica replays changes one after another, at most 200 per second, so lag is the hop plus replay time plus the queue in front of replay: about 10 ms normally, growing without bound while writes exceed 200 per second. The primary keeps the log for a replica that is down and sends it when the replica returns (catch-up); disk usage of that log is not modelled. When the primary crashes, changes it had not yet delivered are lost. Promotion is a modelled failover: the promoted replica takes over the replication links and settings, the proxy sends writes to it, and the simulation counts the keys whose latest acknowledged write the promoted replica never applied (several lost writes to one hot key count once). A read is stale when the replica has not applied a write the primary had already acknowledged for that key. Not modelled: choosing the most caught-up replica, fencing, and the time detection and promotion take in practice. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Acknowledge first, ship later

    The primary replicates asynchronously. It commits a write locally, answers at once, and ships the change to the replicas afterwards. The response leaves the primary while the purple replication packets are still on their way, even to the replicas next door.

    That makes write latency independent of the replicas. Replica 3 sits in another region, 70 ms away, and writes do not pay for it: the median write still takes under 30 ms. Each replica simply runs behind by its distance plus its replay time: about 10 ms for Replicas 1 and 2 (a 2 ms hop, then replay, which handles one change at a time, up to 200 per second), about 80 ms for Replica 3.

    Scene: The primary answers each write right after its local commit and ships the change afterwards. Replicas 1 and 2 run about 10 ms behind, the remote Replica 3 about 80 ms; writes take under 30 ms.

    Key idea: Async replication takes the replicas out of the write path. Their distance turns into lag instead of write latency.

  2. 2. A replica fails; writes don’t notice

    One second in, the remote Replica 3 fails. Nothing happens to writes: no errors, the same latency. The primary was never waiting for it.

    The cost moves elsewhere. While a replica is away the primary must keep the log it has not received (a PostgreSQL replication slot, MySQL binlogs), so the primary’s disk fills up the longer the outage lasts. At 3 s Replica 3 comes back and replays two seconds of backlog: the lag tile jumps to about 2 s and drains only slowly, because the replica replays at most 200 changes per second while 120 new ones keep arriving. Had the needed log been dropped (max_slot_wal_keep_size, binlog expiry), it would have to be rebuilt from a fresh copy instead.

    Scene: The remote replica fails one second in and returns at three seconds. Writes keep succeeding with unchanged latency and there are no errors. After its return the replica replays the retained log: its lag jumps to about two seconds and then drains.

    Key idea: Async replicas can fail without touching writes, but the primary retains their unshipped log, and a returning replica spends a while catching up.

  3. 3. Writes surge, replicas fall behind

    One second in, a batch job starts: the write share jumps from 30% to 60%. The primary takes it in stride, applying writes on many connections in parallel. Replay on a replica is far less parallel (PostgreSQL replays WAL in a single process; MySQL replicas use a limited pool of applier threads), and here each replica replays at most 200 changes per second. 240 writes per second arrive, so a backlog builds and keeps growing: lag climbs to about 250 ms at 2.5 s and past 700 ms by 6 s, for as long as the burst lasts.

    The stale reads tile climbs with it, because more keys have changes the replicas have not applied yet. Writes stay fast and nothing fails: by every latency and error metric the system looks healthy.

    Scene: The write share doubles to 60%, more than the replicas can replay. Replica lag keeps growing, past 700 ms after five seconds, and stale reads climb, while write latency and errors stay unchanged.

    Key idea: Under async replication a write surge shows up as lag and stale reads, not as errors. Only a lag metric reveals it.

  4. 4. The primary crashes mid-lag

    The burst goes on: replicas are about 450 ms behind and the primary commits about 240 writes per second. One second in, the primary crashes. From then on writes fail; reads continue on the replicas.

    The important number is what the replicas did not have at the moment of the crash: roughly the last 450 ms of acknowledged writes, about 100 writes (240 per second × 0.45 s) that clients were told were saved. They were still queued in the primary’s log, and they die with it: the replicas’ lag freezes because nothing more arrives.

    Scene: With replicas about 450 ms behind, the primary crashes. About 100 writes acknowledged in the last 450 ms had not been applied on any replica and never will be. Writes now fail; reads continue.

    Key idea: The data at risk in an async failover is roughly write rate × replication lag at the moment of the crash.

  5. 5. Promote, and confirmed writes are gone

    The same crash at 1 s, and this time a failover follows: at 2 s Replica 1 is promoted. The proxy sends writes to it, Replicas 2 and 3 now replicate from it, and writes succeed again.

    At the moment of promotion the simulation compares what the old primary had acknowledged with what Replica 1 had applied: about 50 keys lose their latest confirmed value (the ~100 lost writes, several of them to the same hot keys). Users who saved those changes reload the page and see older data. Nothing reports an error; as far as the new primary is concerned, those writes never happened.

    This is the recovery point objective of async replication: the lag at crash time. Promoting the most caught-up replica keeps it as small as possible; semi-synchronous commit to one nearby replica removes it for single-node failures.

    Scene: The primary crashes at one second; at two seconds Replica 1 is promoted and writes succeed again on it. About 50 keys lose their latest acknowledged write, because those changes never left the old primary.

    Key idea: Async failover can silently drop writes that were acknowledged. The lag is your RPO.

  6. 6. Fast writes, bounded risk

    The old primary has been rebuilt and handed the primary role back in a planned switchover; every replica is up and about 10 ms (Region A) or 80 ms (Region B) behind, and the write share is back to 30%.

    Async replication gives you writes that never wait for or depend on replicas, which is why it is the default for most databases and for nearly every cross-region copy. You pay with lag (stale reads, measured, not prevented) and with an RPO equal to the lag at the moment the primary dies. Manage both: alert on lag, keep it small, route must-be-fresh reads to the primary, and add a semi-sync replica nearby where losing a confirmed write is unacceptable.

    Scene: Everything is healthy again: 400 queries per second, 30% writes, async replication with about 10 ms of lag in Region A and 80 ms to Region B. No errors.

    Key idea: Async = no write-path dependency on replicas, paid for in lag and a non-zero RPO. Measure the lag; it is both your staleness and your data at risk.