PostgreSQL 19Dev & Eng

Content type: Hands-on

7 min read

PostgreSQL 19's WAIT FOR LSN Matches Synchronous Replication in Tests, But Carries an Unfixed Bug

Article · Dev & Eng
Reading
7 min
Tables
1
Code
2
In short

Load tests with hundreds of thousands of transactions show that PostgreSQL 19's WAIT FOR LSN delivers consistent reads on replicas without paying the price of traditional synchronous replication, but two bugs found along the way require attention before going to production.

Testes de carga com centenas de milhares de transações mostram que o WAIT FOR LSN do PostgreSQL 19 entrega leitura consistente em réplicas sem pagar o preço da replicação síncrona tradicional, mas dois bugs encontrados no caminho exigem atenção antes de ir para produção.

The WAIT FOR LSN feature, included in PostgreSQL 19, promises to solve an old dilemma for anyone administering replicas: waiting for the commit to be replicated blocks the entire application (synchronous replication), but not waiting means risking reading stale data on a replica (asynchronous replication). In the first two parts of a series on the Percona blog, Jobin Augustine explained the concept and showed the command working via psql. In the third part, published on December 3, 2026, he went beyond the manual demonstration: he wrote a load generator in Rust and ran hundreds of thousands of waits against a real PostgreSQL 19.0 instance.

For anyone deciding whether to adopt a replication feature in production, this is exactly the kind of material that's missing from official announcements: numbers under load, and the bugs that showed up along the way.

How the Test Was Set Up

The program, named waitforlsn, runs in two modes. The --mode sync mode is the baseline: commit on the primary and, optionally, immediate read from the replica to show what happens with no waiting at all. The --mode waitfor mode is the new pattern: asynchronous commit on the primary, followed by WAIT FOR LSN on the replica.

The flow of each worker is relevant to anyone implementing something similar:

  1. Grabs a connection from the primary's pool, executes INSERT ... RETURNING id in autocommit.
  2. Reads pg_current_wal_insert_lsn() in the same session.
  3. Returns the primary's connection to the pool (important: holding this connection until the wait finishes would exhaust the pool under replication lag).
  4. Grabs a connection from the replica's pool and executes WAIT FOR LSN '<lsn>' WITH (MODE ..., TIMEOUT ..., NO_THROW).
  5. Optionally, checks whether the row is already visible on the replica.

The program records HDR histograms for each step and uses two separate connection pools, one for the primary and one for the replica, sized independently via --primary-pool and --standby-pool.

The Numbers, With the Appropriate Caveat

The author himself warns that the tests ran on a single laptop, with the postgres:19 Docker image, primary and replica on the same machine, without real network latency. These aren't formal benchmarks, but they serve to compare relative behavior between strategies. The load was 32 concurrent clients doing small INSERTs, in 20-second windows.

StrategyTPSp50 (ms)p99 (ms)Missing Row on Replica
Asynchronous, synchronous_commit = on, direct read from replica2,35213.419.244,713 of 47,080 (95%)
Synchronous, synchronous_commit = on2,44612.819.06 of 48,965
Synchronous, synchronous_commit = remote_apply2,26413.821.80
WAIT FOR mode standby_replay, tuned WAL writer2,065 to 2,36013.0 to 14.921.6 to 26.00
WAIT FOR standby_replay, default WAL writer108215442not measured

Two points stand out. First: reading from a replica with no synchronization guarantee at all is, in practice, a statistical lie, since 95% of reads didn't find the just-committed row. Even synchronous replication with synchronous_commit = on got it wrong six times, because "written to the replica" isn't the same as "replay applied on the replica."

Second: with wal_writer_delay set to 10ms and wal_writer_flush_after = 0, WAIT FOR standby_replay reached throughput and latency equivalent to synchronous replication, without ever losing a row. Without that tuning, TPS plummets to 108 and p99 goes above 440 ms: the feature becomes unviable for OLTP. The table makes it clear that the gain from WAIT FOR LSN isn't raw speed; it's shifting the decision to wait into the application, keeping the primary always free.

Bug 1: The Wait Gets Stuck on a WAL Page Boundary

The most important finding of the investigation is also the trickiest. About one in every 2,000 waits ran until it blew through the full timeout, and when that happened, every client got stuck on the same LSN, tanking the throughput of an entire closed-loop application.

The cause: when the last WAL record ends exactly at a page boundary, pg_current_wal_insert_lsn() returns the boundary plus the size of the next page's header (24 bytes, or 40 at the start of a segment). The problem is that all the positions WAIT FOR compares against (primary flush, replica write/flush/replay) stay stuck at the boundary until some other transaction generates WAL. In a reproduction with four clients, a three-second timeout, and the --raw-insert-lsn option (which disables the fix), the author recorded:

wait_for_lsn error: timeout waiting for LSN 0/03302018
(target=0/03302018 | standby receive=0/03302000 replay=0/03302000
| primary flush=0/03302000 write=0/03302000 insert=0/03302018
walsender sent=standby1:0/03302000)

The bug was reported by Xuneng Zhou on the pgsql-hackers list, and the fix ("Don't make WAIT FOR LSN depend on WAL written after a page boundary") was committed by Alexander Korotkov on November 18, 2026, under hashes 24723e7cf39 (master) and 19aa5713be2 (REL_19_STABLE). The problem is that the 19.0 release tag was cut on November 16, two days earlier. In other words: the fix only lands in 19.1, and anyone already on 19.0 needs a workaround.

The proposed workaround is a SQL function that corrects the LSN before using it in the wait:

sql
CREATE FUNCTION wal_insert_end_lsn(l pg_lsn DEFAULT pg_current_wal_insert_lsn())
RETURNS pg_lsn LANGUAGE sql STABLE AS $$
 SELECT CASE
 WHEN (l - '0/0'::pg_lsn) % pg_size_bytes(current_setting('wal_segment_size'))
 < current_setting('wal_block_size')::int
 THEN CASE WHEN (l - '0/0'::pg_lsn) % current_setting('wal_block_size')::int = 40
 THEN l - 40 ELSE l END
 ELSE CASE WHEN (l - '0/0'::pg_lsn) % current_setting('wal_block_size')::int = 24
 THEN l - 24 ELSE l END
 END
$$;

With this fix applied, the test that previously piled up timeouts closed out 144,724 waits with zero failures, and throughput rose from 385 to 470 TPS in the reproduced scenario. For anyone putting WAIT FOR LSN into production before 19.1 ships, swapping pg_current_wal_insert_lsn() for this function throughout the application isn't optional.

Bug 2: The Walsender That Forgets to Wake Up

Even with the page-boundary workaround in place, two rare hangs showed up in about 140,000 waits, at ordinary LSNs, unrelated to WAL pages. The diagnosis: the primary had already flushed the WAL, but the walsender process hadn't sent anything and sat idle for the full three seconds of the timeout.

The hypothesis is a "lost wakeup": the walsender reads the flush position in XLogSendPhysical() and only afterward joins the condition variable's wait list in WalSndWait(). If a flush and its broadcast happen exactly in that window, nobody wakes the walsender up, and it stays asleep until the next status message or keepalive from the replica.

This behavior had already been identified and fixed outside the context of WAIT FOR LSN: the commit "Fix lost wakeups in physical WAL senders", authored by Alex Speller and committed by Fujii Masao (a9b32f4c818), was backported all the way to version 16, where the wakeup condition variable was introduced. In Speller's original report, synchronous commits hung for as long as about 10 seconds, which shows the bug affects traditional synchronous replication too, not just the new feature. This one, unlike the first, is already fixed in 19.0 itself (in later tests with 470,000 waits, there was no timeout attributable to it).

What Changes for Those Running Databases in Production

The practical takeaway from the series, reinforced by this part with numbers, is that WAIT FOR LSN delivers real read-your-writes on replicas without the cost of blocking every commit on the primary, as long as a few conditions are respected:

  • Set wal_writer_flush_after = 0 and a small wal_writer_delay when synchronous_commit = off is in use; without this, each wait can cost around 200 ms more.
  • Always set a TIMEOUT and treat a timeout as an "unknown result", never as a silent success.
  • Size the replica's connection pool for the number of sessions that will be waiting, since each wait holds a connection.
  • On PostgreSQL 19.0, apply the wal_insert_end_lsn() workaround instead of using pg_current_wal_insert_lsn() directly, until 19.1 ships.

For anyone designing distributed data architecture, the central point is that the decision to wait (or not) for a replica stops being a global server configuration and becomes a per-transaction choice, made in the application code. That's power, but it's also responsibility: the same flexibility that avoids blocking the entire primary requires every call to correctly handle timeouts, connection pools, and, for now, an edge-case bug that the community has already fixed but that hasn't yet reached the stable package.

Translated from the Brazilian Portuguese original · Read the original

Read also