improving handling of FPIs during recovery prefetching
improving handling of FPIs during recovery prefetching
От:
Tomas Vondra <tomas@vondra.me>
Дата:
Вложения:
Hi, A couple days back I happened to notice a blog post [1] by Jeremy Schneider, describing how recovery_prefetch can trigger an outage. I happened to be involved in getting that feature into PG 15, so I was curious how it could trigger such failures. After discussing the details with Jeremy over the weekend, I believe it's really a combination of two issues. 1) recovery_prefetch fails to skip prefetches after an FPI, which may significantly increase the number of IO operations, to the point that the replica runs into disk limits etc. This inflates the replay lag. 2) replication behavior after walreceiver exit - In streaming mode, syncrep waits only for confirmation the WAL was flushed, so it works (mostly) OK even if the replay can't keep up. But if the walreceiver disconnects, the replication startup starts to apply WAL - which may be much slower due to the FPI amplification described in (1). Only when that apply of all the received WAL completes will it start streaming again, and confirming commits on the primary. AFAICS the real issue is (2), but it's not great the prefetching can regress the replay like this. That seems unfortunate even ignoring the syncrep aspect, as it may increase replay lag on read replicas etc. As pointed out in the blog post, Stephen mentioned FPIs [2] back in 2021, but we've all been concerned mostly about syscall overhead and buffer lookups. And the conclusion was that it's fine for v1, negligible relative to the benefits, and that if it turns out to be measurable we'll improve it. But as Jeremy demonstrates in his blog post, the actual issue is in issuing unnecessary I/O, saturating the device IOPS limit. In the reproducer, this is done by UPDATE pgbench_accounts SET abalance = abalance + 1 WHERE aid % 20 = 0 which effectively updates all pages of the table - multiple tuples on each. The first modification generates an FPI, and then there's a bunch of "non-FPI" changes. The prefetcher skips the FPI, but then still issues prefetches for that block due to the non-FPI changes. In reality no reads are necessary - replaying the FPI will install the buffer. The blog claims 16x IOPS amplification. I believe that's simply due to the UPDATE benefiting from read-ahead on the primary (reading data in 128K chunks), but standby dealing with 8K pages (because that's what we get in WAL). That's the same volume, but 16x more IOPS. There's a tiny cache of recently prefetched blocks, but it can't really help in this case - FPIs are not added to it, and even if they were it's way too small (just 4 entries). I kinda suspect it's not large enough in general, but that's a separate question. We actually got a report [3] describing this issue about 18 months ago, including a patch leveraging the XLOGPREFETCHER_SEQ_WINDOW_SIZE bit I mentioned above. That probably works for the reported example, but it's not really a proper fix - the default size "4" is way too low for FPIs. But I used it as a starting point, and after a bit of Sunday hacking, I got what I think is a much more complete fix. I'm attaching the whole series, as it's easier to understand the changes like that, but in the end it'd be squashed into a single commit IO think. I tried to explain the changes in commit messages, so only a very brief overview here: 0001-Avoid-useless-prefetches-in-case-of-recent-FPI-WA.patch --------------------------------------------------------------- Pretty much Michael's patch [3] from 2025, no other changes. 0002-Separate-the-FPIs-from-recently-prefetched-blocks.patch --------------------------------------------------------------- Separates the FPI tracking from recent_block, into a separate array with more entries (but still small, with linear search). 0003-Rework-the-FPI-cache-as-a-set-associative-cache.patch --------------------------------------------------------------- Replace the array / linear search with a set-associative cache, inspired by the cache used in fast-path locking. It seems perfect, with minimal overhead, and it's OK to handle overflows by just forgetting old FPIs. 0004-Move-FPI-tracking-into-separate-functions.patch --------------------------------------------------------------- Refactoring, moving code into functions to improve readability. Should squash into 0003. 0005-Use-a-proper-hash-function-for-FPI-history.patch --------------------------------------------------------------- Replace a stupid "hash function" mapping blocks to the set-associative cache with a much better one. Should squash into 0003. 0006-Ignore-replayed-FPIs-in-prefetch-FPI-history.patch --------------------------------------------------------------- At some point I realized the FPI entries become irrelevant once we replay the record. We have the LSN already, and we can just treat the entry as empty if the LSN is before replaing_lsn. It works more or less as an eviction. This way we won't have "stale entries", causing synchronous reads. 0007-Avoid-duplicate-entries-in-FPI-history.patch --------------------------------------------------------------- There's no point in tracking multiple FPIs for the same block, it's enough to track the new one. It's not very common, of course. But it can happen, and it's not more expensive. 0008-Size-recovery-FPI-history-by-the-look-ahead-dista.patch --------------------------------------------------------------- Until now the size of the FPI history was hard-coded, but we can size it based on the prefetch distance, to minimize "premature eviction". The cache is larger (up to ~400kB for maintenance_io_concurrency=1000), but there can only be one such cache in the walreceiver (and instance). Realistic values are a fraction of that. 0009-Skip-FPI-lookups-when-no-FPIs-are-pending.patch --------------------------------------------------------------- An optimization - a quick exit when there are no outstanding FPIs (which can happen close to the end of a checkpoint, etc). regards [1] https://ardentperf.com/2026/10/20/postgres-recovery_prefetch-considered-harmful-and-causing-outages/ [2] https://www.postgresql.org/message-id/20210214231815.GO27507@tamriel.snowman.net [3] https://www.postgresql.org/message-id/9bdb428a-fc8e-4801-8fff-1ad0bc6fa76b%40postgrespro.ru -- Tomas Vondra
Re: improving handling of FPIs during recovery prefetching
Hi Tomas,
I did not find a problem. Everything looks correct.
I did not find a problem. Everything looks correct.
Two small things
1. There is no test for skip_fpi, so I attached a small TAP test.
2. XLogPrefetcherAddFPI() is called when has_image is
set. Maybe call it when this is true instead:
block->apply_image || (block->flags & BKPBLOCK_WILL_INIT)
Redo does not read the page in either case.
set. Maybe call it when this is true instead:
block->apply_image || (block->flags & BKPBLOCK_WILL_INIT)
Redo does not read the page in either case.
Thanks,
Shihao
Re: improving handling of FPIs during recovery prefetching
От:
Jan Nidzwetzki <jan@planetscale.com>
Дата:
Hi Tomas, hi Shihao, Thank you so much for working on this, Tomas. The series applies cleanly to master and check-world passes. I also did a quick check with crash recovery: pgbench scale 10, a CHECKPOINT, "UPDATE pgbench_accounts SET abalance = abalance + 1 WHERE aid % 20 = 0", an immediate stop, then recovery with recovery_prefetch = on. The posix_fadvise() calls dropped from 23,502 on master to 821 with the series. On 30.10.26 21:58, shihao zhong wrote: > 1. There is no test for skip_fpi, so I attached a small TAP test. Thanks for adding the test, Shihao. I checked the WAL from the TAP test using pg_waldump and saw that the images aren't from the UPDATEs. The cluster has data checksums enabled by default, and allows_streaming => 1 sets wal_log_hints to on. So, the first seqscan UPDATE on each table writes an XLOG/FPI_FOR_HINT for every page of t and u, and the UPDATE records don't have images. When I set no_data_checksums => 1 and wal_log_hints = off, the images move to the Heap/LOCK record written by the first update of each page, as intended in the comments. But then the test fails: skip_fpi is 755, since each page of t gets three more references (HOT_UPDATE, LOCK, UPDATE+INIT) and each page of u one (HOT_UPDATE) while its image is still pending. So, the skips are correct, but the bounds are not. Maybe keep allows_streaming => 1, but add no_data_checksums => 1 and wal_log_hints = off, and then check skip_fpi against a range derived from the number of pages of t and u? Best regards Jan -- Jan Nidzwetzki PlanetScale
Re: improving handling of FPIs during recovery prefetching
Hi Jan,
Thanks for digging into this. You're right, the static count in the test is brittle.
Thanks for digging into this. You're right, the static count in the test is brittle.
The updated TAP test addressed your concern.
Thanks,
Shihao
Thanks,
Shihao
Re: improving handling of FPIs during recovery prefetching
От:
Jan Nidzwetzki <jan@planetscale.com>
Дата:
Hi Shihao,
On 07.11.26 16:08, shihao zhong wrote:
> The updated TAP test addressed your concern.
Thank you so much for the updated test. I can confirm that the page
image is now part of the actual update. On my system, the test passes
without any errors against the patch series and fails without "Ignore
replayed FPIs in prefetch FPI history".
I think I found a race condition in the TAP test. It executes:
---
$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
my $end_lsn = $primary->safe_psql('postgres',
'SELECT pg_current_wal_lsn()');
my $walfile = $primary->safe_psql('postgres',
"SELECT pg_walfile_name('$end_lsn'::pg_lsn - 1)");
---
If WAL records are written between pg_switch_wal() and
pg_current_wal_lsn(), $walfile points to a WAL segment that is not
archived, and the test will time out. For example, this could be the
periodically written running_xacts record. I could force this directly
by adding:
---
$primary->safe_psql('postgres',
'SELECT pg_log_standby_snapshot(); SELECT pg_sleep(0.5)');
---
between the two calls, which makes the test die with "timed out waiting
for WAL to be archived".
In 042_low_level_backup.pl, a similar operation is performed, but the
WAL file name is directly taken from the LSN returned by
pg_switch_wal(). What do you think about changing the code in the same
way? With the change below, the test passes even with the injected
pg_log_standby_snapshot() line.
---
my $end_lsn = $primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
my $walfile = $primary->safe_psql('postgres',
"SELECT pg_walfile_name('$end_lsn')");
---
Apart from this, the test looks good to me.
Best regards
Jan
--
Jan Nidzwetzki
PlanetScale
Re: improving handling of FPIs during recovery prefetching
От:
Tomas Vondra <tomas@vondra.me>
Дата:
On 11/10/26 13:10, Jan Nidzwetzki wrote:
> Hi Shihao,
>
> ...
>
> In 042_low_level_backup.pl, a similar operation is performed, but the
> WAL file name is directly taken from the LSN returned by
> pg_switch_wal(). What do you think about changing the code in the same
> way? With the change below, the test passes even with the injected
> pg_log_standby_snapshot() line.
>
> ---
> my $end_lsn = $primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
> my $walfile = $primary->safe_psql('postgres',
> "SELECT pg_walfile_name('$end_lsn')");
> ---
>
> Apart from this, the test looks good to me.
>
Thanks for looking at the patch and for the TAP test.
FYI I had a chat with Thomas Munro, who wrote the current recovery
prefetcher, and he has some ideas for an alternative (simpler, better)
way to make it skip FPIs. I don't have an ETA for his version, but an
optimist me expects it to be posted soon-ish. So maybe let's not waste
too much time reviewing this patch yet, we can revive it if the better
version does not arrive.
That being said, I think it'll need some sort of TAP test too, so the
one posted here might be useful.
FWIW one aspect of my patch worth checking would be the cost for "normal
cases" where recovery works perfectly fine without the patch. The lookup
in the new "history" cache might be adding measurable CPU overhead, or
something like that. I don't think it does (and I haven't managed to
construct such case), but if someone else verified it, that'd be good.
regards
--
Tomas Vondra
Re: improving handling of FPIs during recovery prefetching
Hi Jan,
Thanks for finding the race. I changed the test the way you
suggested, and take the end LSN from pg_switch_wal().
Thanks for finding the race. I changed the test the way you
suggested, and take the end LSN from pg_switch_wal().
Thanks,
Re: improving handling of FPIs during recovery prefetching
От:
Jan Nidzwetzki <jan@planetscale.com>
Дата:
Hi Shihao, On 10.11.26 16:57, shihao zhong wrote: > Thanks for finding the race. I changed the test the way you > suggested, and take the end LSN from pg_switch_wal(). Thanks for the updated TAP test. The v3 test passes reliably here, also with extra WAL written after pg_switch_wal(). Looks good to me. Best regards Jan -- Jan Nidzwetzki PlanetScale
Re: improving handling of FPIs during recovery prefetching
От:
Jan Nidzwetzki <jan@planetscale.com>
Дата:
Hi Tomas, On 10.11.26 13:20, Tomas Vondra wrote: > FYI I had a chat with Thomas Munro, who wrote the current recovery > prefetcher, and he has some ideas for an alternative (simpler, better) > way to make it skip FPIs. Thanks for the update. Looking forward to seeing Thomas Munro's approach. > FWIW one aspect of my patch worth checking would be the cost for "normal > cases" where recovery works perfectly fine without the patch. The lookup > in the new "history" cache might be adding measurable CPU overhead, or > something like that. I don't think it does (and I haven't managed to > construct such case), but if someone else verified it, that'd be good. I also tried to construct such a case: pgbench -N at scale 1 with frequent checkpoints (max_wal_size = 64MB). After every checkpoint, the first change to every page writes a new FPI. However, the table is small enough that its pages remain in shared buffers. As a result, the master branch issues very few unnecessary prefetches (1,659 during the whole run), so the patch provides no benefit here. I replayed the same WAL (3 million transactions) from a base backup with the data already in the page cache. The master branch took 2.81 seconds, and with the patch it took 2.83 seconds (medians of 10 alternating runs), which is within normal variation. So I did not observe any measurable overhead either. In another run, I added temporary counters to XLogPrefetcherHasFPI(). Out of 9.0 million block references, 5.8 million reached the check. The quick exit from 0009 returned early for 5.3 million of those, and the history was searched 567,000 times, which is 6.3% of all block references. Best regards Jan -- Jan Nidzwetzki PlanetScale