WAIT FOR LSN in PostgreSQL 19, a 3-part series
Part 1: Stop Fighting Synchronous Replication: Meet WAIT FOR LSN – Understand the benefits Part 2: A walkthrough for DBAs (you are here) Part 3: WAIT FOR LSN under load: numbers, tuning and two bugs I found in PostgreSQL 19.0
In Part 1, I explained why I consider WAIT FOR LSN the most impactful feature of PostgreSQL 19, and how an application can use it instead of synchronous replication to address most of the common problems of synchronous replication. The idea is commit on the primary, take pg_current_wal_insert_lsn() on the same connection, and run WAIT FOR LSN on the standby before telling the user “done”. Theory is fine and architects can take full advantage of this feature. However generally DBAs won’t recommend something unless they could try it themself and see things with their own eyes. The good news is that you don’t need any application to understand this feature. Two psql sessions are enough. In this part, I will show:
read-your-writes on a replica breaking, and getting fixed with WAIT FOR, timeouts, and how to watch waiting sessions, a stuck standby, with synchronous replication and with WAIT FOR, side by side, all the errors and restrictions, and why they exist.
At the end, I will tell the long story of how this feature reached its current shape, and thank the people behind it. Setup. All the outputs below are actual outputs captured from PostgreSQL 19.0, with a primary and one asynchronous streaming standby. In my setup the primary is on port 5433 and the standby on port 5434. If you want the same setup, the waitforlsn directory has a docker-compose.yml which creates both (PG_IMAGE=postgres:19 docker compose up -d –wait, password postgres).
- Check the standby $ psql -h localhost -p 5434 -U postgres -c "SELECT pg_is_in_recovery(), pg_last_wal_replay_lsn();" pg_is_in_recovery | pg_last_wal_replay_lsn -------------------+------------------------ t | 0/0E981C38 (1 row)
- Write on the primary and get the LSN postgres=# CREATE TABLE orders(id bigserial primary key, item text, created timestamptz default now()); CREATE TABLE postgres=# SET synchronous_commit = off; SET postgres=# INSERT INTO orders(item) VALUES ('laptop') RETURNING id; id
1 (1 row)
INSERT 0 1 postgres=# SELECT pg_current_wal_insert_lsn(); pg_current_wal_insert_lsn
0/0E981DB8 (1 row) 3. Wait for it on the standby postgres=# WAIT FOR LSN '0/0E981DB8'; status
success (1 row)
postgres=# SELECT * FROM orders; id | item | created ----+--------+------------------------------- 1 | laptop | 2026-11-28 06:43:07.296491+00 (1 row)
postgres=# WAIT FOR LSN '0/0E981DB8' WITH (MODE 'standby_flush', TIMEOUT '2s'); status
success (1 row) 4. See read-your-writes break, and then fix it This is my favourite demo. It is a single psql script. It writes on the primary, uses \gset to keep the id and the LSN in psql variables, then \c switches to the standby. I used the default WAL writer settings here. ( Standby is available on port 5434 ).-- ryw.sql \timing on SET synchronous_commit = off; INSERT INTO orders(item) VALUES ('phone') RETURNING id \gset SELECT pg_current_wal_insert_lsn() AS lsn \gset \echo inserted id :id, commit LSN :lsn \c "host=localhost port=5434 user=postgres dbname=postgres" SELECT * FROM orders WHERE id = :id; WAIT FOR LSN :'lsn'; SELECT * FROM orders WHERE id = :id;$ psql -h localhost -p 5433 -U postgres -e -f ryw.sql SET synchronous_commit = off; Time: 1.106 ms INSERT INTO orders(item) VALUES ('phone') RETURNING id Time: 2.402 ms SELECT pg_current_wal_insert_lsn() AS lsn Time: 1.043 ms inserted id 2, commit LSN 0/0E981FD8 SELECT * FROM orders WHERE id = 2; id | item | created ----+------+--------- (0 rows)
Time: 2.852 ms WAIT FOR LSN '0/0E981FD8'; status
success (1 row)
Time: 7.513 ms SELECT * FROM orders WHERE id = 2; id | item | created ----+-------+------------------------------- 2 | phone | 2026-11-28 06:45:49.579055+00 (1 row)The first SELECT on the standby found nothing. After a 7.5 ms WAIT FOR, the row is there. This is the bug many applications have today when they send reads to replicas. 5. Timeouts: ERROR vs NO_THROW postgres=# \timing on postgres=# WAIT FOR LSN '1/00000000' WITH (TIMEOUT '2s'); ERROR: timed out while waiting for target LSN 1/00000000 to be replayed; current standby_replay LSN 0/0E981DF0 Time: 2002.458 ms (00:02.002)
postgres=# WAIT FOR LSN '1/00000000' WITH (TIMEOUT '2s', NO_THROW); status
timeout (1 row)
Time: 2001.776 ms (00:02.002)Use NO_THROW when the application has a plan for a timeout (retry, read from the primary, report lag). If the application must not continue without the guarantee, leave it out and let the error stop the flow. 6. You can watch the waiting sessions While a session is waiting, it shows up in pg_stat_activity with its own wait event. The waiter was released as soon as the primary wrote enough WAL:postgres=# SELECT pid, state, wait_event_type, wait_event, query FROM pg_stat_activity WHERE query LIKE 'WAIT FOR%'; pid | state | wait_event_type | wait_event | query ------+--------+-----------------+------------------+------------------------------------------------- 8170 | active | IPC | WaitForWalReplay | WAIT FOR LSN '0/0E9823E0' WITH (TIMEOUT '30s'); (1 row) 7. A stuck standby: WAIT FOR vs synchronous replication Now let us compare the two approaches when the standby has a problem. With synchronous replication (synchronous_standby_names = ‘standby1’), I stopped the standby and ran an insert with a 5-second statement_timeout:postgres=# \timing on postgres=# SET statement_timeout = '5s'; SET postgres=# INSERT INTO orders(item) VALUES ('stuck-2'); -- ... hanging. From another session: postgres=# SELECT pid, wait_event, now()-query_start AS waiting_for, query FROM pg_stat_activity WHERE wait_event = 'SyncRep'; pid | wait_event | waiting_for | query ------+------------+-----------------+---------------------------------------------- 5266 | SyncRep | 00:01:58.749567 | INSERT INTO orders(item) VALUES ('stuck-1'); 5276 | SyncRep | 00:01:57.316447 | INSERT INTO orders(item) VALUES ('stuck-2'); (2 rows)
postgres=# SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE wait_event='SyncRep';And the original session finally says:WARNING: canceling wait for synchronous replication due to user request DETAIL: The transaction has already committed locally, but might not have been replicated to the standby. INSERT 0 1 Time: 122205.763 ms (02:02.206)Two minutes!, and the statement_timeout of 5s did nothing. In production, this is every session of the application piling up. With async replication + WAIT FOR, I simulated a stuck standby by pausing replay (SELECT pg_wal_replay_pause(); on the standby). On the primary, nothing is affected:postgres=# SET synchronous_commit = off; SET Time: 1.245 ms postgres=# INSERT INTO orders(item) VALUES ('tablet') RETURNING id; id
55 (1 row)
INSERT 0 1 Time: 3.176 ms postgres=# SELECT pg_current_wal_insert_lsn(); pg_current_wal_insert_lsn
0/14B651D8 (1 row)On the standby, the application gets a clear answer within the time it chose:postgres=# WAIT FOR LSN '0/14B651D8' WITH (MODE 'standby_replay', TIMEOUT '2s', NO_THROW); status
timeout (1 row)
Time: 2002.121 ms (00:02.002) postgres=# -- Use "standby_flush" instead of "standby_replay" to check whether the LSN reached the standby postgres=# WAIT FOR LSN '0/14B651D8' WITH (MODE 'standby_flush', TIMEOUT '2s', NO_THROW); status
success (1 row)
Time: 1.219 ms postgres=# -- Resume the WAL apply again postgres=# SELECT pg_wal_replay_resume();
postgres=# WAIT FOR LSN '0/14B651D8' WITH (MODE 'standby_replay', TIMEOUT '2s', NO_THROW); status
success (1 row)
Time: 0.896 ms postgres=# SELECT id, item FROM orders WHERE id = 55; id | item ----+-------- 55 | tablet (1 row)Look at the second command: even while replay is paused, standby_flush says success. The data is durable on the standby, it is just not visible yet. So an application that needs only durability is not affected at all by a replay delay (long query conflicts, recovery_min_apply_delay, etc.). With synchronous replication remote_apply, the same situation would make every commit on the primary hang. 8. Wrong server, wrong mode -- on the primary, default mode (standby_replay) postgres=# WAIT FOR LSN '0/0E981DB8'; ERROR: recovery is not in progress HINT: Waiting for the standby_replay LSN can only be executed during recovery.
postgres=# WAIT FOR LSN '0/0E981DB8' WITH (NO_THROW); status
not in recovery (1 row)
postgres=# WAIT FOR LSN '0/0E981DB8' WITH (MODE 'primary_flush'); status
success (1 row)
-- on the standby postgres=# WAIT FOR LSN '0/0E981DB8' WITH (MODE 'primary_flush'); ERROR: recovery is in progress HINT: Waiting for primary_flush can only be done on a primary server. Use standby_flush mode on a standby server.The not in recovery status is useful. If your standby gets promoted, every wait comes back immediately with this status (in my earlier tests it took about 1 ms), and the application knows that it has to re-check the topology. 9. The restrictions (and why they exist) -- After a query in REPEATABLE READ, the transaction holds a snapshot postgres=# BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN postgres=# SELECT count() FROM orders; count
1
(1 row)
postgres=*# WAIT FOR LSN '0/0E981DB8'; ERROR: WAIT cannot be executed while the current transaction holds a snapshot DETAIL: This transaction runs at an isolation level higher than READ COMMITTED, so it holds a snapshot from its first query until it ends.
-- Not inside functions / DO blocks postgres=# DO $$ BEGIN EXECUTE 'WAIT FOR LSN ''0/0E981DB8'''; END $$; ERROR: WAIT can only be executed as a top-level statement DETAIL: WAIT cannot be used within a function, procedure, or DO block. CONTEXT: SQL statement "WAIT FOR LSN '0/0E981DB8'" PL/pgSQL function inline_code_block line 1 at EXECUTE
-- Not while holding a lock (when the target is not reached yet) postgres=# BEGIN; BEGIN postgres=# LOCK TABLE orders IN ACCESS SHARE MODE; LOCK TABLE postgres=# WAIT FOR LSN '0/148DFFE0' WITH (TIMEOUT '1s'); ERROR: cannot wait for a standby LSN while holding locks DETAIL: This session holds a lock on relation 16406 of database 5, which could make recovery wait for this session while this session waits for recovery. HINT: Release the locks, or execute WAIT before acquiring them.
-- The LSN must be a literal, not a bind parameter postgres=# PREPARE w(pg_lsn) AS WAIT FOR LSN $1; ERROR: syntax error at or near "WAIT"All of these have the same reason. If the waiting session holds a snapshot or a lock, the startup process on the standby may have to wait for this session (recovery conflict), while this session waits for the startup process. Nobody can break that cycle. So the simple rule is: run WAIT FOR first, outside a transaction block or as its first statement, and then run your queries. For application developers, the last one means: validate the LSN string in the application, and send it with the simple query protocol. These restrictions are not accidental. Getting this part right is the main reason the feature took so many years. That brings us to the history. A bit of history: a long journey This feature didn’t come easily. It has been in discussion for more than six years, and it was committed and reverted multiple times. Here is the short version:
Up to 2020: BEGIN … WAIT FOR LSN. Ivan Kartyshov and Anna Akenteva from Postgres Professional proposed waiting for an LSN at transaction start. Alexander Korotkov committed it in April 2020 (0f5ca02f53a). It was reverted the next day, because it added three new keywords for a relatively small feature, and it was already past feature freeze, too late to discuss new syntax. April 2024: pg_wal_replay_wait() procedure, for PG17. The second attempt was a stored procedure, to avoid new syntax. It was committed, and then reverted a week later after review by Heikki Linnakangas. August 2024: pg_wal_replay_wait() again, for PG18. Committed again with many improvements (including a no_error option), and reverted again in November 2024. The main reason was a hard one: a procedure runs with a snapshot, and turning the backend into a “snapshot-less” state from inside a procedure needed more hacks than a utility statement would. November 2025: WAIT FOR as a utility command, for PG19. The infrastructure (xlogwait.c, pairing heaps of waiters per wait type, so that the startup process / WAL writer can check the minimum waited LSN in O(1)) and the WAIT FOR command were committed by Alexander Korotkov, with Ivan Kartyshov and Xuneng Zhou as co-authors. January 2026: the MODE option. Xuneng Zhou extended it from “replay only” to standby_write, standby_flush and primary_flush. This is what makes the durability use case possible. 2026: hardening. A long list of fixes landed during the PG19 cycle: deadlocks between waiters holding locks and recovery, re-reading the LSN after recovery ends, waking primary_flush waiters after implicit flushes, timeout overflow, stale wakeups, process-exit cleanup, documenting that it is timeline-blind, and finally the page-boundary fix (see Part 3).
The major challenges, as I understand from the threads and commits:
The snapshot problem. A session that waits for replay while it holds a snapshot can block the replay itself. This is why it could not be a function, why the procedure approach failed, and why it is now a top-level command with strict checks. You saw these checks in demo 9 above. Deadlocks with recovery. The same thing applies to locks. A lock held by the waiter can make the startup process wait for the waiter. There is no lock wait on the waiter’s side, so the deadlock detector can’t see it. Hence the “cannot wait while holding locks” rule. Syntax. New keywords in the grammar are a big deal in PostgreSQL. The final syntax is a single utility statement with a WITH (…) options list, the same style as COPY and EXPLAIN. Efficient wakeups. The startup process replays a huge number of records. Checking waiters must cost almost nothing when nobody is waiting. Edge cases of WAL positions. Timelines, promotion, and as we will see in Part 3, page headers.
Thank you A feature like this is the result of many years of work by many people. A big thank you to:
Alexander Korotkov, who stayed with this feature through every attempt since 2020, was the author and committer of the final version, and also fixed many issues in it, including the page-boundary bug I reported. Xuneng Zhou, co-author of the final infrastructure and command, author of the MODE option and a large number of follow-up fixes, and the first one to find the page-boundary root cause. Ivan Kartyshov and Anna Akenteva, who started this work years ago. The reviewers of the committed versions: Michael Paquier, Peter Eisentraut, Dilip Kumar, Amit Kapila, Alexander Lakhin, Bharath Rupireddy, Euler Taveira, Heikki Linnakangas, Kyotaro Horiguchi, jian he, Álvaro Herrera and Chao Li, and the reviewers of the earlier attempts, including Craig Ringer, Thomas Munro, Robert Haas, Masahiko Sawada, Ants Aasma, Dmitry Ivanov, Simon Riggs and Tom Lane. The reverts were painful, but those reviews are why the final design is a robust one. Alexander Lakhin, for the many bug reports from his testing. Alex Speller and Fujii Masao, for finding and fixing the walsender lost-wakeup bug, which affects synchronous replication as well. Everyone else who took part in the pgsql-hackers discussions, tested the betas and reported issues.
Summary of Part 2
Two psql sessions are enough to learn this feature. Try the read-your-writes demo (demo 4) on your own replicas. You may be surprised how often a read right after a commit misses the row. With synchronous replication, a stuck standby means hanging commits that even statement_timeout can’t stop. With WAIT FOR, the primary is not affected, and the application gets a timeout within the time it chose. standby_flush keeps working even when replay is delayed, so pick the mode by what you really need: durability or visibility. Run WAIT FOR first, before your transaction takes a snapshot or a lock.
Next in this series: Part 3: WAIT FOR LSN under load: numbers, tuning and two bugs I found in PostgreSQL 19.0. It has the throughput and latency numbers against synchronous replication, the demo application I used, and the two stall bugs I hit, including the one which is not fixed in 19.0 and its workaround.
The post Stop Fighting Synchronous Replication: Meet WAIT FOR LSN – Part 2 – walkthrough for DBAs appeared first on Percona.






