Fix lag columns in pg_stat_replication not advancing when replay LSN stalls
Fujii Masao <masao.fujii@gmail.com>
From: Fujii Masao <masao.fujii@gmail.com>
To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>
Date: 2025-10-17T03:56:55Z
Lists: pgsql-hackers
Attachments
- v1-0001-Fix-lag-columns-in-pg_stat_replication-not-advanc.patch (application/octet-stream) patch v1-0001
Hi, While testing, I noticed that write_lag and flush_lag in pg_stat_replication initially advanced but eventually stopped updating. This happened when I started pg_receivewal, ran pgbench, and periodically monitored pg_stat_replication. My analysis shows that this issue occurs when any of the write, flush, or replay LSNs in the standby’s feedback message stop updating for some time. In the case of pg_receivewal, the replay LSN is always invalid (never updated), which triggers the problem. Similarly, in regular streaming replication, if the replay LSN remains unchanged for a long time—such as during a recovery conflict—the lag values for both write and flush can stop advancing. The root cause seems to be that when any of the LSNs stop updating, the lag tracker's cyclic buffer becomes full (the write head reaches the slowest read head). In this situation, LagTrackerWrite() and LagTrackerRead() didn't handle the full-buffer condition properly. For instance, if the replay LSN stalls, the buffer fills up and the read heads for "write" and "flush" end up at the same position as the write head. This causes LagTrackerRead() to return -1 for both, preventing write_lag and flush_lag from advancing. The attached patch fixes the problem by treating the slowest read entry (the one causing the buffer to fill up) as a separate overflow entry, allowing the lag tracker to continue operating correctly. Thoughts? Regards, -- Fujii Masao
Commits
-
Add comments explaining overflow entries in the replication lag tracker.
- b4810b4bb885 13.23 landed
- 10799d025f2c 14.20 landed
- c16154bfa2a1 15.15 landed
- 4d707f2fd728 16.11 landed
- 8ceab82ca526 17.7 landed
- 5f88da5de3f2 18.1 landed
- abc2b71383b4 19 (unreleased) landed
-
Fix stalled lag columns in pg_stat_replication when replay LSN stops advancing.
- 7d7ebdb800fe 13.23 landed
- a7ab6ce6a0fc 14.20 landed
- 59b215f7217f 15.15 landed
- 2e55cf4efc8d 16.11 landed
- 62d5ee75bbc4 17.7 landed
- 9670032cc51f 18.1 landed
- 883a95646a8e 19 (unreleased) landed