wrkm.app
Search
Databases

Jobin Augustine: Stop Fighting Synchronous Replication: Meet WAIT FOR LSN – Part 1

WAIT FOR LSN in PostgreSQL 19, a 3-part series Part 1: Stop Fighting Synchronous Replication: Meet WAIT FOR LSN (you are here) Part 2: Hands-on with WAIT FOR LSN: a walkthrough for DBAs Part 3: WAIT FOR LSN under load: numbers, tuning and two bugs I found in PostgreSQL 19. If someone asks me what would be the biggest impactful feature in PostgreSQL 19, I don’t have any doubt in saying that it is WAIT FOR LSN from standby. PostgreSQL generates a new LSN (Log Sequence Number) where

Editor
Dec 1, 2026 · 12 min read
Jobin Augustine: Stop Fighting Synchronous Replication: Meet WAIT FOR LSN – Part 1

WAIT FOR LSN in PostgreSQL 19, a 3-part series

Part 1: Stop Fighting Synchronous Replication: Meet WAIT FOR LSN (you are here) Part 2: Hands-on with WAIT FOR LSN: a walkthrough for DBAs Part 3: WAIT FOR LSN under load: numbers, tuning and two bugs I found in PostgreSQL 19.

If someone asks me what would be the biggest impactful feature in PostgreSQL 19, I don’t have any doubt in saying that it is WAIT FOR LSN from standby. PostgreSQL generates a new LSN (Log Sequence Number) wherever something is written to WAL. A facility to wait for LSN to reach standby is impactful because it can change the way applications are designed. It is the only feature in which I personally spend time and effort in testing and participating in hackers mailing lists with minor problems before the release of PostgreSQL 19. A word of caution: You may start designing and developing your application around this feature. But I suggest waiting for PostgreSQL 19.1 before going for production, because a critical fix is not included in 19.0. The details, and a workaround for 19.0, are explained in Part 3 of this series. For many years, whenever a customer wanted “the data should not be lost” or “the user must see what he just saved, even if the read goes to a replica”, the answer was mostly one: synchronous replication. And many of those customers came back to us later with a different problem: “the whole database froze”, “all commits are hanging”, “we had an outage because the standby went down”. With PostgreSQL 19, we finally have one more option. The application itself can decide when and where it wants to wait. The content became too big for a single post, so I split it into three. In this first part, I will explain the problem, the feature, and how it can be used as a replacement for synchronous replication. Part 2 shows how DBAs can play with it using just psql, and the long history behind it. Part 3 has the numbers from my tests on the PostgreSQL 19.0 release, and the bugs I found on the way. The troubles with synchronous replication Let me first explain the problem we are trying to solve. Synchronous replication is a good feature, but it comes with a cost, and the cost is not only performance.

Every commit pays the price. Once synchronous_standby_names is set, every transaction that runs with the default synchronous_commit = on  has to wait for the standby. That includes the audit log insert, the session table update and all other things which nobody cares about. If the standby is gone, the primary is also practically gone. The commit is done locally, but the session waits for the standby’s confirmation. If the standby is down or if there is a network partition, the session waits forever. There is no timeout for this. Investing in multiple standby servers with options like FIRST or ANY standby might help to address this problem to some extent. statement_timeout will not save you. Many people believe that setting a statement_timeout will limit this wait. It does not. The documented behaviour is not considering a synchronous standby. In Part 2 you can see a testable case: an INSERT with statement_timeout = '5s'  was waiting for 2 minutes, and it came out only when I cancelled it manually. Cancelling the wait does not undo anything. When you cancel it, PostgreSQL tells you honestly: 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. So the data is already committed and visible to everyone on the primary. The “synchronous” guarantee was gone at that moment anyway. The operations become complex. Because of the above, HA tools like Patroni have to keep changing synchronous_standby_names  when standbys come and go, people configure quorum (ANY 1 (s1, s2)), they need at least two synchronous candidates, and so on. A simple mistake here results in an outage.

Generally the requirement of an application is NOT like “Primary connection needs to wait until the transaction reaches standby on every transaction commit”. What they need is either:

“This particular transaction must be safe on two servers before I tell the user it is done”, or “When I read from the replica, I must see what I just wrote” (read-your-writes).

Both of these are decisions which only the application can make correctly. And that is exactly what WAIT FOR LSN gives. What is WAIT FOR LSN It is a new SQL command in PostgreSQL 19 (the documentation lists it under the name WAIT):WAIT FOR LSN 'lsn' [ WITH ( option [, ...] ) ]

-- where option can be: -- MODE 'standby_replay' | 'standby_write' | 'standby_flush' | 'primary_flush' -- TIMEOUT 'timeout' -- integer milliseconds, or with units: '100ms', '5s' -- NO_THROW -- return a status instead of raising an errorThe command just waits until the server reaches the given WAL position (LSN), and then returns one row with a status column. The value is success, timeout or not in recovery. The MODE decides what “reached” means:

MODE Runs on Returns success when What it guarantees

standby_replay (default) Standby WAL is replayed (applied) The change is visible on the standby. This is read-your-writes

standby_flush Standby WAL is fsynced on the standby The change is durable on the standby

standby_write Standby WAL is written to the OS, not yet fsynced Survives a standby PostgreSQL crash, but not an OS crash

primary_flush Primary WAL is flushed on the primary Useful along with synchronous_commit = off

A few points to keep in mind from day one:

TIMEOUT not given, or TIMEOUT ‘0’, means wait forever. It is not a “check once” option. Always give a timeout from the application. Without NO_THROW, a timeout raises an ERROR. With NO_THROW, you get the status as a row, and the application must check it. It must be a top-level statement. It can’t be used inside a function, procedure or DO block. It can’t run while your transaction holds a snapshot or a lock, because that could block the replay you are waiting for (a self-deadlock). Part 2 shows these errors.

The pattern: commit on primary, wait on standby The idea is very simple:

The application commits the transaction on the primary. On the same connection, it gets the current WAL insert position: SELECT pg_current_wal_insert_lsn(); It goes to the standby and runs WAIT FOR LSN ‘’ WITH (MODE …, TIMEOUT …, NO_THROW); Only when the status is success does it tell the user “done”, or read from the standby.

Why pg_current_wal_insert_lsn()  and not pg_current_wal_flush_lsn() ? If you run with synchronous_commit = off  (I’ll explain below why you will want to), the commit record may not be flushed yet when COMMIT returns. So the flush LSN taken right after the commit can be behind your commit record, and waiting for it can return success too early. The insert position is always at or after the end of your commit record, so it is safe. The PostgreSQL documentation also recommends this. (On 19.0 there is one catch with this function at WAL page boundaries. See Part 3.) One more trap: don’t send the write and the SELECT pg_current_wal_insert_lsn()  as one multi-statement string (simple query protocol). That runs as one implicit transaction, and you will get the LSN from before the commit. How this replaces synchronous replication Here is the interesting part. You can combine WAIT FOR LSN with synchronous_commit = off on the primary:

The primary acknowledges the commit without waiting for its own WAL flush. That is very cheap. A physical walsender only sends WAL that is already flushed on the primary. You can verify this in the source (walsender.c, XLogSendPhysical()  sends only up to GetFlushRecPtr() , and there is a comment saying unflushed WAL must never reach a standby). So when WAIT FOR … MODE ‘standby_flush’ returns success, the transaction is on disk on both the primary and the standby.

That means “async commit + WAIT FOR standby_flush” gives you a durability guarantee which is stronger than plain synchronous_commit = on  without a sync standby (local flush only), and similar to synchronous replication with synchronous_commit = on . With standby_replay, it is similar to remote_apply, and you get read-your-writes too. Let me put the comparison in a table:

Synchronous replication Async replication + WAIT FOR LSN

Who waits Every committing session, decided by server config Only the transactions where the application asks for it

Standby down / very slow Commits hang forever (statement_timeout doesn’t help) The primary keeps running. The wait returns timeout after the time you chose

What to do on a problem Cancel it, and get “already committed locally” The app gets a status and decides: retry, read from the primary, alert, or mark the result as unconfirmed

Which guarantee One setting for everyone (on, remote_write, remote_apply) Chosen per call: standby_write, standby_flush, standby_replay

Which standby Defined in synchronous_standby_names, managed by the HA tool Whichever standby the application reads from

HA tool complexity Must manage synchronous_standby_names Nothing special: plain async replication

Promoted standby — Returns not in recovery immediately, so the app knows the topology changed

Be honest about what it is not I don’t want to hype this feature up too much and cause unrealistic expectations. Please understand the differences before you drop synchronous replication:

The primary acknowledges before the standby has it. If the primary crashes after COMMIT returned but before the wait succeeded, that transaction can be lost on failover (and with synchronous_commit = off, even a primary-only crash can lose it). This is exactly why the application must not report success until the wait returns success. A timeout should be treated as “outcome unknown”, the same way a network error during COMMIT is treated. Honestly, this is not very different from synchronous replication, where a cancelled wait or a lost connection also leaves you with an unknown outcome. Other sessions can see the data on the primary before it is on the standby. This is true for synchronous replication also, so nothing new here. But don’t assume otherwise. The guarantee lives in the application code. A developer who forgets the wait gets plain async replication. With synchronous replication, the server enforces it for everyone. Wrap it in your data-access layer or library, don’t scatter it everywhere. Connection pools need to be sized. A session waiting on the standby holds its standby connection for the whole wait. In my tests with 32 clients, the standby pool averaged 24 of 32 connections in use, while the primary pool needed only about 7! (Rule of thumb: standby pool ≈ clients × wait time / total time.) See how the traditional connection overhead is shifted from Primary to Standby. Interestingly, this affects the traditional read-write split considerations also.

The setting that makes or breaks it: the WAL writer When I started testing, the first numbers were terrible. With default settings, the WAIT FOR part was taking around 200–400 ms. The reason is what I explained above: the walsender sends only flushed WAL, and with synchronous_commit = off  the flushing is done by the WAL writer process, which wakes up every wal_writer_delay  (default 200ms). Reading XLogSetAsyncXactLSN()  in xlog.c gave the answer. If wal_writer_flush_after = 0 , every async commit wakes up the WAL writer, and it flushes right away. So these two settings on the primary are very important for this pattern:ALTER SYSTEM SET wal_writer_flush_after = 0; -- default 1MB ALTER SYSTEM SET wal_writer_delay = '10ms'; -- default 200ms SELECT pg_reload_conf(); -- both are reloadable, no restart neededNote that these settings affect only async commits, so sessions using synchronous_commit = on are not affected. With the defaults, I measured only 108 TPS. After this tuning, it was above 2,000 TPS, in the same range as synchronous replication. The full numbers are in Part 3. Summary of Part 1 WAIT FOR LSN moves the “wait for the standby” decision from the server configuration into the application, where it belongs. That gives us:

No more global hangs because one standby is sick. The primary keeps running, and the application gets a timeout it can handle. A choice per transaction: durability (standby_flush), visibility (standby_replay) or nothing at all. Real read-your-writes on replicas, which most “read from replica” setups don’t have today. Simpler HA: plain async replication, no synchronous_standby_names juggling.

But remember the homework:

Tune wal_writer_flush_after = 0 and a small wal_writer_delay if you use synchronous_commit = off, otherwise every wait costs around 200 ms. Always use a TIMEOUT, and treat timeout as “outcome unknown”, not as success. Don’t report success to the user before the wait returns success. Size the standby connection pool for the waiting sessions.

This feature took more than six years and many people to reach this shape. I tell that story, and thank everyone involved, at the end of Part 2. Next in this series: Part 2: Hands-on with WAIT FOR LSN: a psql walkthrough for DBAs. You will see read-your-writes break and get fixed, a stuck standby with and without synchronous replication, and all the restrictions, with actual outputs from PostgreSQL 19.0. The post Stop Fighting Synchronous Replication: Meet WAIT FOR LSN – Part 1 appeared first on Percona.

Kaynak: Planet PostgreSQL

#PostgreSQL
Share

From other categories