Course contents

05. Distributed Databases Lesson 9 of 10

Replication Lag

Measure lag, see stale reads grow with lag and write rate, and fix read-your-writes and monotonic reads without losing read scaling.

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

Summary

  • Lag is measurable per replica (replay lag, heartbeats, log positions); stale reads are its visible consequence.
  • Stale reads grow with lag × write rate on the keys being read; hot keys suffer first, and latency and error metrics do not show it.
  • Read-your-writes is a per-session guarantee: route sessions that just wrote to the primary, or to a replica that has passed their write.
  • Sending every read to the primary removes staleness and the read scaling with it.
  • Replicas at different lags can show a user newer then older data; pinning a session to one replica gives monotonic reads, not fresh ones.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Replication lag is how far a replica is behind its primary: the time (or the amount of log) between a change being committed on the primary and being visible on the replica. With asynchronous replication it is never zero. What users notice is not the lag itself but the anomalies it causes: stale reads, not seeing their own writes, and data going backwards between page loads.

The Database Replication lesson introduces lag and stale reads; Asynchronous Replication shows why lag grows under write load. This lesson is about measuring lag and about the routing techniques that decide which anomalies users actually see.

Why it exists

Replicas replay the primary's change log in order, after it has been shipped over the network. Network delay, the replica's replay speed (far less parallel than the primary's writes), long queries on the replica that conflict with replay, and write bursts all put the replica behind. You cannot remove lag from async replicas; you can bound it, measure it, and route reads so it does not matter where it would hurt.

How it works

Measuring lag.

  • Time-based, from the database: PostgreSQL pg_stat_replication on the primary has write_lag, flush_lag and replay_lag per standby; on a standby, now() - pg_last_xact_replay_timestamp() (misleading when the primary is idle). MySQL's Seconds_Behind_Source compares event timestamps and can be wrong around idle periods and long transactions.
  • Heartbeat: the primary updates a row with the current time every second; each replica reports now - heartbeat. Simple, works on any engine, and measures what readers experience (pt-heartbeat does this for MySQL).
  • Log position: bytes or LSN difference (pg_wal_lsn_diff), GTID sets in MySQL. Useful for "has this replica got write X yet?" questions.

Lag × write rate = staleness. A read is stale when its key changed within the lag window. In the lesson, 20 ms of lag with 50 writes/s makes about 3% of replica reads stale; quadrupling the writes at almost the same lag (about 30 ms) triples that; once a write surge beyond what the replicas can replay pushes lag past half a second, more than half of replica reads are stale. Hot keys, written and read most often, are stale first. None of this changes request latency or error rates.

Read-your-writes. A user saves a change and reloads; the read hits a replica that has not applied it. Fixes that keep read scaling:

  • Recent writers to the primary: record the time of a session's last write (cookie, session store) and send its reads to the primary for a window longer than the worst lag you tolerate. Only a small share of traffic moves to the primary.
  • Position-aware reads: return the commit's log position with the write (PostgreSQL pg_current_wal_lsn(), MySQL GTID). Before reading, check the replica has replayed it (pg_last_wal_replay_lsn(), MySQL WAIT_FOR_EXECUTED_GTID_SET) or pick one that has; otherwise wait briefly or fall back to the primary. No guessed window.
  • Read from the client: for a single field the user just changed, show the value the client already has.

Sending every read to the primary also works and throws away the reason replicas exist: in the lesson the primary's median latency goes from about 35 ms to about 200 ms.

Monotonic reads. Different replicas lag by different amounts. If consecutive reads of one user land on different replicas, the user can see a newer state and then an older one. Pinning a session to one replica (hash its id, or keep the connection) fixes this, because one replica only moves forward. It does not make reads fresher, it can make load uneven (hot sessions land on one replica), and a failover of the pinned replica can move the session backwards once.

Bounded staleness. Take replicas out of read rotation when their lag exceeds a threshold (ProxySQL max_replication_lag, health checks that read the heartbeat). Readers then get data no older than the threshold, at the cost of capacity during lag spikes.

When to use it

Every system that reads from async replicas needs a lag policy:

  • Alert on lag per replica, with thresholds tied to what readers tolerate.
  • Use recent-writer routing or position-aware reads for flows where users read right after writing (settings, profiles, carts, comments).
  • Use sticky routing where users page through or refresh data and backwards jumps would confuse them.
  • Use bounded staleness for reads that tolerate "a few seconds old" but not "minutes old".

When not to

  • Reads that must be current for correctness (balances before a transfer, stock at checkout, permission checks right after a change): read from the primary, always; no window or stickiness is a substitute.
  • Very write-heavy, read-light data: replicas give little; read from the primary and avoid the complexity.
  • Global stale-read counts as a target: they will never be zero with replicas, and need not be. Target the guarantees users need instead.

Trade-offs

Technique Guarantee Cost
All reads on the primary Fresh reads for everyone No read scaling; primary becomes the bottleneck
Recent writers to the primary Read-your-writes (if the window exceeds the lag) Some extra primary load; window must be sized for worst-case lag
Position-aware reads (LSN/GTID) Read-your-writes, causal reads Plumbing the position through the app; occasional waits or fallbacks
Sticky replica per session Monotonic reads No freshness gain; uneven load; reset on replica failure
Lag-based ejection Bounded staleness Less read capacity exactly when lag spikes
Synchronous replication (apply level) Fresh replicas Write latency and availability tied to replicas

Alternatives

  • Caches with explicit invalidation for hot data, where the application controls freshness directly.
  • Synchronous or quorum replication with apply-level waits for the subset of data that must be fresh on replicas.
  • Databases with built-in follower reads and bounded staleness (Spanner and CockroachDB follower reads at a chosen timestamp, DynamoDB eventually vs strongly consistent reads, Cosmos DB consistency levels including session and bounded staleness).

Failure modes

  • Silent lag spikes during batch jobs or schema changes, unnoticed because latency and errors stay flat.
  • A routing window sized for typical lag that fails during spikes.
  • Lag metric that lies: Seconds_Behind_Source of 0 on a stalled replica, or a replay timestamp that is old only because the primary was idle.
  • Ejecting every replica at once when lag rises everywhere, pushing all reads onto the primary and overloading it.
  • Sticky routing to a replica that falls behind, giving its users consistently old data.
  • Monotonic-read jumps after failover when sessions are re-pinned.

In production

Run a heartbeat and graph lag per replica as a percentile over time, not just the current value. Set alerts on the lag your read paths tolerate. Size recent-writer windows from observed worst-case lag (or use position-aware reads and skip the guess). Decide per read path which guarantee it needs: primary, read-your-writes, monotonic, bounded staleness, or anything goes. Cap how many replicas lag-based ejection may remove, so a global spike degrades freshness gracefully rather than overloading the primary. Treat a lag incident as an incident even if no request failed.

Common misconceptions

  • "No errors, so replicas are fine." Lag shows up as old data, not errors.
  • "More replicas reduce lag." Each replica has its own lag; more of them only spread reads.
  • "Sticky sessions fix stale reads." They fix backwards jumps (monotonic reads), not staleness or read-your-writes.
  • "Read-your-writes means everyone sees my write immediately." It only means I do. Others may see it later, which is allowed.
  • "Zero stale reads is the goal." With async replicas the goal is the right guarantee per read path.

Interview angle

When you put reads on replicas, say how you handle lag before the interviewer asks: measure it (heartbeat), route read-your-writes traffic (recent writers to the primary, or LSN/GTID-aware reads), and name monotonic reads and sticky routing if users paginate or refresh. Size the window from worst-case lag, explain why "all reads to the primary" defeats the purpose, and note which reads must always go to the primary. Distinguishing session guarantees (read-your-writes, monotonic reads) from global freshness shows you understand consistency models, not just replication.

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). Queries use 1,000 keys with Zipf(1.0) popularity, so a few keys are hot. A proxy sends writes to the primary and reads to three replicas (least connections; in the sticky step, a consistent-hash ring on the request key, standing in for a session id). Replication is asynchronous: each write reaches a replica after the network hop plus a fixed 15 ms, and each replica applies writes one after another, at most 250 per second. Lag is therefore about 20 ms at 50 writes/s, about 30 ms at 200 writes/s (with brief bumps when writes cluster), and grows for as long as writes exceed 250 per second, as in the lag-spike step. Replica 3's slow replay in the time-travel step is modelled as an 800 ms link. The primary keeps the log for a replica that is down and sends it when the replica returns, so a recovered replica catches up at its replay speed. A stale read is a replica read of a key whose latest acknowledged write the replica has not applied yet; it is counted for every replica read, whoever reads. The engine has no sessions: "Recent writers" is a separate traffic source whose reads and writes go to the primary, and "Readers" are read-only sessions; the user's own save-and-reload and the two reloads in the time-travel step are scripted packets in slow motion, not to scale. Replay does not use replica connections. Not modelled: position-aware reads and lag-based ejection (explained in the text). Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Lag is a number you can watch

    Three async replicas each run about 20 ms behind the primary; the tag on each replica and the lag tile show it. In production you get this number from the database (PostgreSQL’s replay_lag, MySQL’s replica status) or, more reliably, from a heartbeat: the primary writes the current time to a row every second and each replica compares it with its own clock.

    The second tile counts stale reads: replica reads of a key that has a newer, already-acknowledged write the replica has not applied. With 50 writes per second and 20 ms of lag, about 3% of replica reads are stale, nearly all of them on the few hot keys.

    Scene: The app sends 500 queries per second, 10% writes. Three async replicas each run about 20 ms behind the primary, and about 3% of replica reads are stale.

    Key idea: Lag is measurable per replica, and stale reads are its visible consequence. Track both.

  2. 2. Same lag, more stale reads

    One second in, the write share rises from 10% to 40%. The lag barely moves, from about 20 to about 30 ms (each replica replays up to 250 writes per second, and 200 keep it busier). Yet the share of stale reads triples.

    Staleness depends on two things: how far behind a replica is, and how often the data being read changes within that window. Four times as many writes means many more keys with a change “in flight” at any moment, and the hot keys, written and read most often, have one most of the time. The same lag hurts a write-heavy, hot-key workload far more than a calm one.

    Scene: The write share rises to 40% while lag only moves from about 20 to about 30 ms. The share of stale replica reads triples.

    Key idea: Stale reads grow with lag × write rate on the keys being read. Hot keys feel lag first.

  3. 3. Lag spikes under sustained writes

    One second in, a batch import pushes the write share to 60%: 300 writes per second. The primary commits them on many connections at once, but each replica replays one write after another, at most 250 per second (replay is far less parallel than the primary’s writes). 50 writes per second more arrive than a replica can apply, so a backlog builds and lag climbs about 150 ms every second: roughly 300 ms at 3 s, 750 ms at 6 s, and it keeps going as long as the import runs.

    Once lag passes half a second, more than half of replica reads return old data: most keys being read have a newer write the replicas have not applied yet. Latency and errors are unchanged: from the outside the system looks perfectly healthy.

    Scene: A batch import raises writes to 300 per second, more than the replicas can replay. Lag grows by about 150 ms every second, past 700 ms after six seconds, and more than half of replica reads become stale; latency and errors do not change.

    Key idea: Lag spikes turn “a little stale” into “mostly stale” without moving latency or error metrics.

  4. 4. A user can’t see their own change

    Follow one user (the slow-motion packets): she saves a new display name. The write goes to the primary, which answers “saved”. The page reloads, the proxy sends the read to Replica 2, which the import has pushed more than half a second behind (and falling further), and she sees her old name.

    This is a read-your-writes (read-after-write) violation. Other users seeing her old name for half a second is usually fine; *she* seeing it looks like a bug, and users react by saving again.

    Scene: Scripted overlay on the running simulation: a user saves a new name on the primary, reloads, and the read goes to Replica 2, more than half a second behind, which returns the old name.

    Key idea: Read-your-writes is a per-session guarantee: a user must see their own writes, even if others may lag.

  5. 5. Blunt fix: every read from the primary

    The import has finished (write share back to 40%). The quickest fix for Ada: send every read to the primary. The proxy loses its replica routes and stale reads drop to zero, because there are no replica reads left.

    But the primary now carries 300 reads plus 200 writes per second, which keeps every one of its connections busy. Queries queue for a connection: median latency jumps from about 35 ms to about 200 ms and P95 passes 300 ms. Three replicas sit idle. We fixed one user’s problem by recreating the bottleneck replicas were added to remove.

    Scene: All reads go to the primary. There are no stale reads, but the primary’s connections are all busy: median latency rises from about 35 ms to about 200 ms while the replicas are idle.

    Key idea: Reading everything from the primary removes staleness and the read scaling with it.

  6. 6. Targeted fix: primary only after a write

    Better: when a session writes, remember the time (in a cookie or the session) and send that session’s reads to the primary for a few seconds, longer than the worst lag you tolerate. Everyone else keeps reading from replicas.

    The scene now has two kinds of traffic. Recent writers (sessions that wrote in the last 5 s, and every write comes from one) go straight to the primary: 200 writes and 50 reads per second. Readers go through the proxy to the replicas. The primary is under half busy, nothing fails, and no recent writer ever reads from a replica.

    The stale-read tile does not drop to zero, and does not need to: those are readers seeing other people’s changes a bit late, which async replication allows. Read-your-writes is a per-session guarantee.

    Scene: Sessions that wrote in the last 5 seconds read and write on the primary; read-only sessions read from the replicas. The primary is under half busy, nothing fails, and stale reads remain only for read-only sessions.

    Key idea: Route only the sessions that just wrote to the primary. Staleness for everyone else is the normal, allowed cost of replicas.

  7. 7. Different replicas, different pasts

    With the import over, Replicas 1 and 2 are back to about 30 ms of lag (with brief bumps when writes cluster), but Replica 3 is now far behind, about 800 ms: it is running a heavy report that slows its replay. Each replica lives at its own point in the past.

    Follow one reader reloading a page twice. The first read goes to Replica 1 and shows a new comment. The second goes to Replica 3 and the comment is gone: data appeared and then vanished. That breaks monotonic reads, the promise that once you have seen something, you will not later see an older state.

    The tile confirms where staleness comes from: Replica 3 produces most of the stale reads.

    Scene: Replicas 1 and 2 are about 30 ms behind, Replica 3 about 800 ms. A scripted reader reloads twice: Replica 1 shows a new comment, Replica 3 does not. Replica 3 produces most stale reads.

    Key idea: With several replicas at different lags, spreading one user’s reads over them can move that user backwards in time.

  8. 8. Pin each user to one replica

    Switch the proxy to hashing: every read for the same key (standing in for the same user or session) goes to the same replica. A replica’s state only moves forward, so a user pinned to it never sees time go backwards: monotonic reads restored.

    What stickiness does not do is make reads fresher. Users hashed to Replica 3 consistently see data about 800 ms old, and the stale-read tile barely moves. Load now follows the keys, too: the replica that owns the hot keys is several times busier than the others. If a pinned replica fails, its users move to another one and can jump backwards once. For read-your-writes you still need the previous fix.

    Scene: The proxy hashes each key to one replica, so a key’s reads never move between replicas. Stale reads continue at about the same rate, mostly from Replica 3, and one replica is much busier than the others.

    Key idea: Sticky routing gives monotonic reads, not fresh reads. It is a different guarantee from read-your-writes.

  9. 9. Measure it, then pick the guarantee you need

    Replica 3 has finished its report and is back to about 30 ms. The setup now combines both fixes: recent writers read from the primary, everyone else reads from a replica they are pinned to. In the sandbox, a replica you fail and recover replays the log the primary kept for it: watch its lag spike and drain over several seconds as it catches up.

    Lag is unavoidable with async replicas; what you choose is which anomalies users may see. Read-your-writes: send a session that just wrote to the primary, or remember its write position (PostgreSQL LSN, MySQL GTID) and read only from a replica that has replayed past it. Monotonic reads: pin a session to one replica. Bounded staleness: take replicas out of rotation when their lag exceeds a limit. And always alert on lag itself.

    Scene: All replicas are about 30 ms behind. Recent writers use the primary; read-only sessions are pinned to one replica each by the proxy. No errors.

    Key idea: Lag is a fact of async replication; anomalies are a routing choice. Route by the guarantee each read needs.