skip to content

read replicas and read-your-writes

sending reads to a standby, the stale read right after a write, and waiting for an LSN.

address
everything.scale.read_replicas
part
part 17, scale and distribution
chapter
chapter 4 of 10
reading time
8 min

a read replica is a standby that replays the primary's WAL and answers read-only queries. it's always a little behind (replication lag), so a read sent there right after a write can miss that write. read-your-writes means a user always sees their own changes: route their reads to the primary for a while, or remember the LSN of their last write and wait until the replica has replayed that far.

the picture

you know how you save your profile, the page reloads, and your old name is still there, and then it fixes itself a second later? that's a read replica answering before it heard about your write.

think of a newsroom (the primary) and a printed copy pinned on a wall down the hall (the standby). anyone can read the wall, which takes load off the newsroom. but the wall is updated by a runner, so for a moment after every story changes, the wall shows the old one.

here it is between two real postgres 18.6 servers. the standby was started with recovery_min_apply_delay = 500ms, so the moment is long enough to catch every time:

primary
·
standby
·
0
UPDATE profiles SET name = 'ada lovelace' WHERE id = 42 RETURNING name;→ name = ada lovelace

the primary commits the new name.

step 1/6
recorded: two throwaway postgres 18.6 clusters on this mac (m4 pro): a primary and a pg_basebackup standby streaming over a unix socket, driven by a node-postgres script. one write and the reads after it, then 300 writes each followed by standby reads until the new value showed
one write on the primary, then reads on the standby. the standby has received the write but not yet replayed it, so it answers ada. after its replay LSN passes the write's LSN, it answers ada lovelace. labels are milliseconds since the write.

the standby isn't broken. it's doing exactly what streaming replication does: WAL arrives, gets written, then gets replayed into pages, and a query on the standby sees whatever has been replayed. the LSNs say precisely how far behind it is.

how much lag

without the artificial delay, on one machine with nothing else running, the standby replays in well under a millisecond. but a read sent right after the commit still usually loses the race:

run 1: median wait0.07 ms
run 1: slowest0.46 ms
run 2: median wait0.11 ms
run 2: slowest1.74 ms
run 3: median wait0.07 ms
run 3: slowest0.47 ms
recorded: two throwaway postgres 18.6 clusters on this mac (m4 pro): a primary and a pg_basebackup standby streaming over a unix socket, driven by a node-postgres script. one write and the reads after it, then 300 writes each followed by standby reads until the new value showed
three recorded runs of 300 writes each, every write followed immediately by reads on the standby until it showed the new value. the first read was stale almost every time, even though the new value arrived a fraction of a millisecond later.

stale first reads: 299 of 300, 298 of 300, 297 of 300. that's the important number. lag isn't a fixed delay you can wait out once; it's a race on every write, and on a loaded server across a network, with a long query on the standby holding replay back, it stretches to seconds. on the primary, pg_stat_replication shows it per standby as write_lag, flush_lag and replay_lag; in the delayed run it said write_lag 0.159 ms, flush_lag 0.195 ms and replay_lag 501.26 ms: the WAL arrived at once, and the 500 ms delay sat exactly where it was configured, in replay.

predict the output
the app commits on the primary, gets COMMIT back, and immediately reads the same row from an async standby. what does it see?
text
primary:  UPDATE profiles SET name = 'ada lovelace' WHERE id = 42;  -- COMMIT returns
standby:  SELECT name FROM profiles WHERE id = 42;                  -- right after

routing reads

a replica only takes load off the primary if reads go to it. something has to decide which reads: a driver setting, the ORM's database router, or a proxy in front. the policy is the interesting part:

reads =
lag =
100 ms
tthe usergoes tosees
0.00 ssaves version 1primary·
0.04 sreloadsstandbynothing yet
0.40 sreloadsstandbyversion 1
1.50 sreloadsstandbyversion 1
2.60 sreloadsstandbyversion 1
3.00 ssaves version 2primary·
3.02 sreloadsstandbyversion 1
3.90 sreloadsstandbyversion 2
6.50 sreloadsstandbyversion 2
stale reads: 2/7reads on the primary: 0time spent waiting: 0 ms

the reload right after a save lands on a standby that hasn't replayed it yet. the user saves, reloads, and their change is gone.

sees their own writestale: doesn't
model: one user, writes to the primary, a standby that replays each write after the lag you pick
one user saving and reloading. pick a routing policy and drag the lag. stale reads are the ones that miss the user's own last save.
  • everything to the replica. fine for reads that can be a little old (dashboards, search, other people's posts). wrong for "show me what I just did".
  • stick to the primary after a write. route a user's reads to the primary for a few seconds after they write. simple, and only as right as your guess about lag.
  • wait for the LSN. after a write, the app reads pg_current_wal_lsn() (or pg_current_wal_insert_lsn()) on the primary and keeps it with the user's session. before reading from a replica, it checks the replica's pg_last_wal_replay_lsn() and waits, or falls back to the primary, until that has passed the saved LSN. exact, and the cost is a short wait right after a write.

both functions run anywhere, and the replay one has a quirk worth knowing. it reports where the last WAL replay ended, standby or not. a primary that was shut down cleanly has never replayed anything and says NULL. the browser's postgres did replay: it starts from a snapshot of a data directory and runs crash recovery on it, so it reports where that ended (a native primary does the same after a crash and restart; checked on a throwaway 18.6):

sqlempty db
SELECT pg_is_in_recovery() AS is_standby, pg_last_wal_replay_lsn() AS replayed;
output, from postgres 18.6
SELECT 1
is_standbyboolreplayedpg_lsn
f0/16EFAA0
(1 row)

so check pg_is_in_recovery() first, and only trust the replay position on a server that says true.

and LSNs compare and subtract like numbers, which is all the wait loop needs:

sqlempty db
SELECT '0/302FCB0'::pg_lsn >= '0/302FC88'::pg_lsn AS caught_up,
       pg_wal_lsn_diff('0/302FCB0', '0/302FC88') AS bytes_behind;
output, from postgres 18.6
SELECT 1
caught_upboolbytes_behindnumeric
t40
(1 row)

those two LSNs are the recorded ones: the write at 0/302FCB0, and the standby's replay position when it answered "ada".

postgres 19 postgres 19 adds a command for the waiting part. run on a standby, it blocks until replay reaches the LSN (or a timeout passes) and returns a status:

text
WAIT FOR LSN '0/302FCB0' WITH (TIMEOUT '1s', NO_THROW);

it has to be a top-level statement, outside a transaction that holds a snapshot or locks, because a waiting session that holds them could block the very replay it's waiting for (the 19 docs). where postgres is going has the rest of 19.

what replicas don't do

replicas scale reads, not writes: every write still goes through the one primary, and every replica replays every write. they don't make a single slow query faster. and a failover promotes a replica that may be missing the last commits unless replication was synchronous. when the write volume itself outgrows one machine, the next step is sharding.

keylines

  • a replica replays the primary's WAL, so it's always a little behind.
  • a read right after a commit can lose that race, even on one machine.
  • route reads that can be old to replicas; route "my own data" carefully.
  • read-your-writes: stick to the primary after a write, or wait for the write's LSN.
  • replicas scale reads, never writes.