Percona PostgreSQL Blog· Jobin Augustine·· 1d ago
PostgreSQL 19 WAIT FOR LSN: How to Read Your Writes on an Async Standby
Stop Fighting Synchronous Replication: Meet WAIT FOR LSN – Part 2 – walkthrough for DBAs
Key Takeaway
A PostgreSQL 19.0 demo shows how WAIT FOR LSN lets an async standby serve reads of just-committed writes. With replay paused, primary writes continued and standby_replay timed out after about 2 seconds, while standby_flush confirmed WAL was durable on the standby.
Why It Matters
If only some requests need to read their own writes from a standby, applications can wait selectively but must decide whether to retry or read from the primary on timeout.
Technical Breakdown · Distilled from the original source
Reading Just-Committed Writes on a Standby
- After committing on the primary, capture the target with
pg_current_wal_insert_lsn()on the same connection, then runWAIT FOR LSNon the standby. In the PostgreSQL 19.0 demo with twopsqlsessions, the first primary-key lookup on the standby missed the inserted row; the lookup after a roughly 7.5 ms wait found it. TIMEOUTraises an error by default; addingNO_THROWreturns atimeoutstatus instead. Waiting sessions are visible inpg_stat_activityunder theWaitForWalReplayevent.
Distinguishing Flush from Replay
- Pausing replay did not affect writes on the asynchronous primary. On the standby,
standby_replaytimed out whilestandby_flushsucceeded. Replay makes the data visible, whereas flush only confirms the WAL is durable on the standby. - In the synchronous replication comparison, stopping the standby left a primary commit waiting despite a 5-second
statement_timeout. After manual cancellation, PostgreSQL reported that the transaction had committed locally but might not have replicated.
Server Roles and Transaction Restrictions
- The default
standby_replaymode requires recovery. After promotion,NO_THROWcan returnnot in recovery, giving the application a signal to recheck the topology.primary_flushruns only on the primary. WAIT FOR LSNmust run as a top-level statement and takes a literal LSN. It cannot run while the transaction holds a snapshot. If the standby has not reached the target, a session holding locks cannot wait either, because the session and recovery could block each other.
Source: Percona PostgreSQL Blog· percona.com
PG Radar summarizes verified changes and impact. Read the original post for full technical details and code samples.