# Read replicas and read-your-writes: replication lag and LSN waits

Development Radio · field guide · published 2026-11-25

Canonical page: https://developmentradio.dev/guides/read-replicas-read-your-writes/

Written with AI and checked against the cited sources before publication.

Asynchronous replicas are behind by design, so give every read that follows a write proof that it includes that write: carry the commit's LSN or GTID and make the replica wait for it with a short timeout, falling back to the primary. A fixed window such as Rails' default 2 seconds on the primary is cheaper but silently fails whenever lag exceeds it, and one conflicting query on a PostgreSQL standby can hold replay for 30 seconds by default. Tokens protect only the reads that follow a user's own write: in October 2018 GitHub had dozens of read replicas multiple hours behind the primary, users saw inconsistent data, and the way out was more replica capacity.

## The mechanism

A read replica is a promise about throughput, not about freshness. On PostgreSQL and MySQL the default is asynchronous: the primary acknowledges the commit without waiting for any standby. The PostgreSQL manual says "streaming replication is asynchronous by default", with "a small delay between committing a transaction in the primary and the changes becoming visible in the standby", "typically under one second assuming the standby is powerful enough to keep up with the load". A row becomes visible on the standby only "once the commit record for a transaction is replayed". Until then, a user who saved something and reads it back from a replica gets the old version.

### Three lags, not one

A change sent to a standby is written (handed to its operating system), flushed to disk, then replayed, and only replay makes it visible. `pg_stat_replication` on the primary reports a timestamp lag for each of the three:

- `write_lag`: until the standby "has written it (but not yet flushed it or applied it)".
- `flush_lag`: until it "has written and flushed it (but not yet applied it)".
- `replay_lag`: until it "has written, flushed and applied it". For an asynchronous standby, the manual says, "the replay_lag column approximates the delay before recent transactions became visible to queries." That is the number your users feel.

Two traps sit in those columns. They are measurements of recent WAL, "not predictions of how long it will take for the standby to catch up". And on an idle, caught-up system "the lag columns revert to NULL after a short time", so NULL means there was nothing recent to measure, not that something broke. A standby that has disconnected has no row in `pg_stat_replication` at all, so alert on the expected number of rows as well as on lag: a dashboard that reads a missing row as zero lag shows a dead replica as a healthy one. For a byte count, use `pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)`; `sent_lsn` leaves out WAL the primary has not sent yet. On the standby, `pg_last_wal_receive_lsn()` against `pg_last_wal_replay_lsn()` shows WAL that has arrived but not been applied. A big gap there means the WAL has arrived and replay is the bottleneck: blocked by a conflict, or too slow to keep up.

MySQL's `Seconds_Behind_Source` is cruder. It is the gap between the applier thread and the receiver thread, so on a slow link it "often shows a value of 0, even if the replication receiver thread is late", and the manual concludes "this column is useful only for fast networks". In 2017 GitHub measured lag with `pt-heartbeat`, which "inserts a timestamp each 100ms in the master", and compares it on each replica.

Managed storage shrinks the delay but does not remove it. Aurora replicas share the cluster volume, and AWS says the lag "is usually much less than 100 milliseconds", but "during periods where a large amount of write operations occur for the database, you might see an increase in replica lag."

### Why replay stops: queries on the replica

Replay and read queries compete on the standby. Replaying a vacuum cleanup record "conflicts with standby transactions whose snapshots can still 'see' any of the rows to be removed", and an `ACCESS EXCLUSIVE` lock from DDL on the primary conflicts with any read of that table. The standby then waits, up to `max_standby_streaming_delay`, "30 seconds" by default, and cancels the query. That grace period is measured from when the WAL arrived, "so the grace period allowed to any one query on the standby is never more than the delay parameter, and could be considerably less if the standby has already fallen behind".

So one long report on a replica can hold replay, and every other reader's freshness, for up to 30 seconds by default. You get to pick which problem you want:

- **Keep the default.** Conflicts can hold replay for up to 30 seconds before the conflicting queries are cancelled, and the replica then still has to catch up. `pg_stat_database_conflicts` on the standby counts the cancels.
- **Set `hot_standby_feedback = on`** (default off). The standby tells the primary which rows its queries still need, which "can be used to eliminate query cancels caused by cleanup records, but can cause database bloat on the primary". It does nothing for lock conflicts from DDL.
- **Set the delay to -1.** That "allows the standby to wait forever for conflicting queries to complete", and replica lag has no upper bound.

The usual design answer is separate replicas: short delay and no feedback for user-facing reads, a long delay or feedback for analytics. That way the report never stalls the replica a user is reading their own save from.

**Figure 1: A save that disappears on the next read**

1. Browser → Primary: UPDATE start time to 7:30
2. Primary → Browser: COMMIT ok, local flush only
3. Primary → Replica: stream WAL, replay waits on a query
4. After a pause: Browser → Replica: GET preview, 300 ms later
5. Replica → Browser: start time 7:00 (the harmful step)
6. After a pause: Browser → Replica: GET again after replay
7. Replica → Browser: start time 7:30

Mechanism from PostgreSQL docs, streaming replication and hot standby; the timing is illustrative

### The patterns and what each costs

There are five ways to give a user their own write back, and they differ in what they guarantee and who pays.

**1. Read from the primary for N seconds after a write.** Rails ships this: `config.active_record.database_selector = { delay: 2.seconds }` with the `Resolver::Session` context sends GET and HEAD requests to the writer for 2 seconds after the session wrote. The guide says "Rails guarantees 'read your own write'" in that window but "doesn't guarantee 'read a recent write'" for other users. GitHub's older rule routed reads to replicas "only if the last write happened more than five seconds ago". The cost is that N is a guess about lag. When replay stalls for 30 seconds, the window has closed while the data is still missing, and nothing tells you. And it covers only the session that wrote: a background job enqueued by that write has no session.

**2. Route by measured lag.** GitHub's freno reports "the maximum replication lag across the cluster". After a write, the app asks freno, and if "the reported value is below the elapsed time since the last write", the read "can be routed to a replica". This makes the window follow real lag instead of a constant. GitHub reports that "we managed to route to the replicas ~30% of the requests that before were routed to the master". The cost: a lag service, heartbeat resolution (100 ms), and the cluster-wide maximum, so one slow replica keeps every post-write read on the primary.

**3. Carry a position token and wait for it.** Record the primary's WAL position after the commit, carry it with the session, cookie or job payload, and make the replica prove it has applied that position before you read.

- **PostgreSQL 19** (released 19 November 2026) adds the `WAIT` command for exactly this. Its release notes call it "support for 'read-your-writes' consistency on standbys". On the primary after commit, `SELECT pg_current_wal_insert_lsn();`. On the standby, `WAIT FOR LSN '0/306EE20' WITH (TIMEOUT '100ms', NO_THROW);` returns `success`, `timeout` or `not in recovery`. The default timeout of zero "means the command waits indefinitely", so always set one. Only the default `MODE 'standby_replay'` gives read-your-writes; the write and flush modes do not. `WAIT` "cannot be executed while the current transaction holds a snapshot", and on a standby it is rejected if the session already holds a lock, whatever the isolation level. The manual's rule: "Issue WAIT FOR outside a transaction block, or as the first statement of one, before running anything that takes locks." WAIT sessions "may be interrupted by recovery conflicts", so the fallback must handle errors as well as `timeout`. If the standby is promoted mid-wait, the LSN "may refer to WAL from the old timeline". On earlier versions, compare `pg_last_wal_replay_lsn()` with the token and poll. Check before planning around `WAIT` on a managed service: version 19 is days old, and Aurora replicas read shared storage rather than replaying a WAL stream like a streaming standby.
- **MySQL**, with GTIDs enabled (`gtid_mode = ON`; the default is `OFF`), returns the session's GTIDs to the client "as part of the acknowledgement" of each commit when `session_track_gtids = OWN_GTID` (also `OFF` by default). On the replica, `SELECT WAIT_FOR_EXECUTED_GTID_SET('3E11FA47-71CA-11E1-9E33-C80AA9429562:1-5', 1)`, with the GTID set you got back and a timeout in seconds, returns 0 once those transactions are applied and 1 on timeout. The default timeout is 0, which "always waits".

The cost is plumbing: every path that reads after a write must carry the token, including queues and other services. In return it is the only replica-read pattern that stays correct whatever the lag, across the whole pool, and it falls back to the primary only when the replica really is behind.

**4. Pin a session to one replica.** Shopify adds a comment such as `/* consistent_read_id: ... */` to related queries, with a UUID for the job or series of requests, and its ProxySQL fork hashes the ID to choose "the same pseudorandom result" every time. That gives monotonic reads ("successive reads will follow a consistent timeline, though not necessarily reading the latest data in real time"). It does not give read-your-writes. Shopify considered GTID-based causal consistency and passed, because it needed "software running on each replica which would report its current GTID back to the proxy". The cost: when the pinned replica is down, "a data inconsistency is possible—this is a built-in limitation of our approach."

**5. Make commits wait for replay.** `synchronous_commit = remote_apply` makes "each commit to wait until the current synchronous standbys report that they have replayed the transaction, making it visible to user queries". Every write pays at least "the round-trip time between primary and standby" plus replay time, which is what `replay_lag` measures, and "transaction locks continue to be held until the transfer is confirmed". If a synchronous standby crashes, such commits "may never be completed" until you change `synchronous_standby_names`. It does nothing unless `synchronous_standby_names` is set: with it empty, remote_apply gives "the same local synchronization level as on". And it covers only the standbys the commit waited for (with `ANY 1` of two, only one of them), not potential standbys or the rest of the read pool.

**Figure 2: Read-your-writes with an LSN token**

1. Commit on primary: Then read pg_current_wal_insert_lsn
2. Carry the token: Session, cookie or job payload
3. WAIT FOR LSN on replica: TIMEOUT 100ms with NO_THROW
4. success: read replica: All changes up to the LSN are applied
5. timeout: read primary: Fallback only when the replica is behind

Source: PostgreSQL 19 docs, WAIT command and read-your-writes consistency; timeout value illustrative

## Worked numbers

Illustrative inputs; put in your own. A service does 20,000 reads a second and 400 writes a second. After each write, that user's session makes 3 reads a second. Assume no session writes twice within the window, which makes these upper bounds.

- **Everything on the primary:** 20,000 reads a second. Correct, and the replicas are idle.
- **Primary for 5 seconds after a write** (GitHub's old rule): 400 × 5 × 3 = 6,000 reads a second on the primary.
- **Primary for 2 seconds** (the Rails default): 400 × 2 × 3 = 2,400 a second. Cheaper, but during any replay stall longer than 2 seconds, every read after the window closes gets stale data until replay catches up.
- **LSN token with a 100 ms wait:** the same 2,400 post-write reads go to replicas and wait if needed. If 2% of them time out because the replica is more than 100 ms behind, an assumed rate, 48 a second fall back to the primary. Every token read pays one extra `WAIT` round trip, the reads that wait pay up to 100 ms, and the 48 fallbacks pay that plus a primary read.

**Figure 3: Illustrative reads per second sent to the primary, by pattern** (log scale)

| | Primary reads (reads/s) |
|---|---|
| All on primary | 20,000 |
| Primary for 5 s | 6,000 |
| Primary for 2 s | 2,400 |
| LSN token, 100 ms wait | 48 |

Illustrative: 20,000 reads/s, 400 writes/s, 3 reads/s per session after a write, 2% of token waits time out

**Lag under a stall.** With 2 MB/s of WAL (illustrative), a replica held for the full 30-second default has 60 MB to replay when the query is cancelled. It catches up only as fast as its replay rate exceeds the 2 MB/s still arriving. GitHub found in 2018 that catch-up "had adhered to a power decay function instead of a linear trajectory", so your estimate of when lag reaches zero will be optimistic.

## How it fails

- **Replicas hours behind (GitHub, 21 October 2018).** A 43-second network partition led Orchestrator to promote primaries on the US West Coast, and GitHub ran degraded for 24 hours and 11 minutes while it restored service. During recovery there were "dozens of database read replicas that were multiple hours delayed behind the primary", and because GitHub spreads "the read load across a large pool of read replicas", requests landed on lagging ones: "These delayed replicas resulted in users seeing inconsistent data as they interacted with our services." GitHub had begun "provisioning additional MySQL read replicas" in the public cloud, and once they were available, "Reducing the utilization in aggregate across the read replicas allowed replication to catch up." The lesson for routing: a time window of a few seconds means nothing when lag is measured in hours, and a token or post-write lag check protects only the reads that follow a user's own write. Every other read needs a router that takes a replica out of the pool above a lag limit, and when most of the pool is hours behind, that moves the load onto the primary. GitHub's way out was more replica capacity, not smarter routing.
- **Lag that fails requests outright (GitHub, 27 November 2020).** From 16:04 UTC, for one hour and one minute, GitHub Actions was affected. An edge case "triggered a large number of GitHub App token requests", which "caused abnormal levels of replication lag within one of our MySQL clusters". In its December 2020 follow-up, GitHub said some token requests failed "because the database replicas did not have up to date information." Note the loop: load from the feature drove the lag, and the lag broke the feature. GitHub said it was "updating the queries to prevent large quantities of token requests from overloading the database servers".
- **Routing that quietly stops pinning (Shopify, reported 2021).** After shipping hash-based replica selection, Shopify traced an intermittent bug to ProxySQL doing "an additional round of load balancing after initial server selection": in its example, a 1:1 target weighting with connections drifted to 3:1 forced requests onto the underweighted server, overriding the hash. The result was inconsistent reads in "a small percentage of cases". A consistency guarantee implemented in a proxy needs a test that would catch the proxy changing its mind.

### One more trap

- **The lag the replica causes itself.** A standby that lags because of conflicts shows a large receive-to-replay gap and normal network numbers. Check `pg_stat_database_conflicts` before you add hardware.

## Decision table

| Pattern | What it costs | Choose it when |
|---|---|---|
| Critical reads always on the primary | Primary capacity for those reads; no read scaling for them | A small set of reads must be current: balances, permissions, checkout, anything a later write depends on |
| Primary for N seconds after a write | A guess at lag; silent staleness when lag exceeds N; covers only the writing session | Low-stakes pages, a framework that already ships it (Rails `delay: 2.seconds`), lag you have measured to stay well under N |
| Route by measured lag (freno style) | A lag service and heartbeats; one slow replica keeps post-write reads on the primary | Many services share a cluster and you want one control for reads and write throttling |
| LSN or GTID token with a bounded wait | Token plumbing through sessions, queues and services; up to the timeout in latency | Correctness must hold whatever the lag; PostgreSQL 19 `WAIT FOR LSN` or MySQL `WAIT_FOR_EXECUTED_GTID_SET` is available |
| Sticky replica per session or job | Monotonic reads only, not your own writes; breaks when the pinned replica fails | Multi-query jobs and pagination that must not go backwards in time |
| `synchronous_commit = remote_apply` | Every commit waits a round trip plus replay; commits stall if the sync standby fails | Few writes, a small sync set, and reads routed only to the standbys every commit waits for |
| Separate replicas for analytics | More instances | Long queries would otherwise stall replay for user-facing reads |

## A check you can run this week

Run this on the PostgreSQL primary at your busiest hour, then again during your heaviest batch job:

```
SELECT application_name, sync_state, write_lag, flush_lag, replay_lag,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS replay_bytes_behind
FROM pg_stat_replication;
```

And on each standby:

```
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn())) AS received_not_applied,
       now() - pg_last_xact_replay_timestamp() AS since_last_replayed_commit;
SELECT datname, confl_snapshot, confl_lock, confl_bufferpin, confl_deadlock FROM pg_stat_database_conflicts;
```

Read `since_last_replayed_commit` together with `received_not_applied`. When the primary is quiet, the time since the last replayed commit grows even though nothing is waiting to be applied.

Then the review question for one feature. Pick a screen that reads right after a save, such as a preview, a confirmation page or a job that sends an email. Ask: which database does that read hit, and what proves it includes the save? If the answer is "the replica, and nothing", compare its worst `replay_lag` above with the time between the save and the read. Our episode [You Saved It. Why Did It Disappear?](https://developmentradio.dev/episodes/2026-10-19-saved-disappeared-daily/) follows one such edit through a preview and a send.

## Sources

- PostgreSQL documentation: Log-shipping standby servers (streaming, synchronous replication, read-your-writes): https://www.postgresql.org/docs/current/warm-standby.html
- PostgreSQL documentation: Hot standby (query conflicts): https://www.postgresql.org/docs/current/hot-standby.html
- PostgreSQL documentation: WAIT (PostgreSQL 19): https://www.postgresql.org/docs/current/sql-wait.html
- PostgreSQL 19 release notes: https://www.postgresql.org/docs/release/19.0/
- PostgreSQL documentation: The cumulative statistics system (pg_stat_replication, pg_stat_database_conflicts): https://www.postgresql.org/docs/current/monitoring-stats.html
- PostgreSQL documentation: Replication settings (hot_standby_feedback, max_standby_streaming_delay, synchronous_standby_names): https://www.postgresql.org/docs/current/runtime-config-replication.html
- PostgreSQL documentation: Write-ahead log settings (synchronous_commit): https://www.postgresql.org/docs/current/runtime-config-wal.html
- PostgreSQL documentation: System administration functions (replay and receive LSN): https://www.postgresql.org/docs/current/functions-admin.html
- MySQL 8.4 Reference Manual: Functions used with GTIDs (WAIT_FOR_EXECUTED_GTID_SET): https://dev.mysql.com/doc/refman/8.4/en/gtid-functions.html
- MySQL 8.4 Reference Manual: Server system variables (session_track_gtids): https://dev.mysql.com/doc/refman/8.4/en/server-system-variables.html
- MySQL 8.4 Reference Manual: Global transaction ID system variables (gtid_mode): https://dev.mysql.com/doc/refman/8.4/en/replication-options-gtids.html
- MySQL 8.4 Reference Manual: SHOW REPLICA STATUS (Seconds_Behind_Source): https://dev.mysql.com/doc/refman/8.4/en/show-replica-status.html
- Amazon Aurora User Guide: Replication with Amazon Aurora: https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Replication.html
- Rails Guides: Multiple databases with Active Record (automatic role switching): https://guides.rubyonrails.org/active_record_multiple_databases.html
- GitHub Engineering: Mitigating replication lag and reducing read load with freno: https://github.blog/engineering/mitigating-replication-lag-and-reducing-read-load-with-freno/
- Shopify Engineering: Read consistency with database replicas: https://shopify.engineering/read-consistency-database-replicas
- GitHub: October 21 post-incident analysis (2018): https://github.blog/news-insights/company-news/oct21-post-incident-analysis/
- GitHub Availability Report: November 2020: https://github.blog/news-insights/company-news/availability-report-november-2020/
- GitHub Availability Report: December 2020 (follow-up on 27 November): https://github.blog/news-insights/company-news/github-availability-report-december-2020/

## Hear it discussed

- [Read Replica Lag: You Saved It. Why Did It Disappear?](https://developmentradio.dev/episodes/2026-10-19-saved-disappeared-daily/index.md)
- [Microsoft's AI Agent Framework Was Poisoned on PyPI](https://developmentradio.dev/episodes/2026-11-25-microsoft-agent-framework-pypi-daily/index.md)
