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_replicationon the primary haswrite_lag,flush_lagandreplay_lagper standby; on a standby,now() - pg_last_xact_replay_timestamp()(misleading when the primary is idle). MySQL'sSeconds_Behind_Sourcecompares 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(), MySQLWAIT_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_Sourceof 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.