Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

Started by SATYANARAYANA NARLAPURAM8 months ago17 messageshackers
Jump to latest
#1SATYANARAYANA NARLAPURAM
satyanarlapuram@gmail.com

Hi Hackers,

While review the patch in the thread [1]/messages/by-id/CA+3i_M8C+rK9vhwBm8U+ys2hbDifoBb4Xnws5Wmn2f4u7iqOpA@mail.gmail.com I noticed the following:

When the WAL prefetcher encounters a block reference that carries a full
page image (FPW) or has BKPBLOCK_WILL_INIT set, it correctly skips issuing
a prefetch for that block because the old on-disk content is irrelevant
since replay will overwrite or zero the page entirely. However, if a later
WAL record within the look-ahead window references the same block without
an FPW, the prefetcher would still issue a fadvise64 syscall for it,
because the block was never recorded in the duplicate-detection window.

Fixed this by making these blocks as recently seen in the FPW and WILL_INIT
skip paths. The existing duplicate-check loop then naturally suppresses
prefetch attempts for subsequent references to the same block, counting
them under the skip_rep stat. This is particularly effective for workloads
that produce many sequential writes to the same page (e.g., bulk inserts
into heap-only tables), where each page's first post-checkpoint touch
generates an FPW and subsequent inserts to the same page follow shortly
after in WAL.

In order to further improve the wasted prefetch calls, we can try to
increase the window size by changing XLOGPREFETCHER_SEQ_WINDOW_SIZE
according to max blocks that can be prefetched or maintain a hash table. I
did not attempt to do this in this patch because that can impact the redo
performance (more cpu cycles). Worst case, the current fix may fail in
scenarios where the table has more than four indexes, for example. However,
I still believe it is an improvement over the baseline. If we decide to
spend more cycles on optimizing the window sizes, it can be in a different
patch.

Benchmarked recovery with 10 GB of WAL from insert-only workload into a
no-index table, replayed from an identical crash snapshot:

Fast disk (NVMe)
Baseline: redo 37.30s, system CPU 9.38s, 1,204,992 fadvise calls
Patched: redo 25.78s, system CPU 3.39s, 122,753 fadvise calls

This is nearly 31% faster redo, 90% fewer fadvise syscalls

*Prefetch Counters*
Counter Baseline Patched Delta
prefetch (fadvise issued) 1,204,992 122,753 −89.8%
hit 924,457 911,785 −1.4%
skip_init 1,097,536 1,097,536 0
skip_fpw 28 28 0
skip_rep 80,020,209 81,115,120 +1,094,911

Slower disk (with ~2ms latency)
Baseline: redo 188.04s, system CPU 6.87s, 1,204,992 fadvise calls
Patched: redo 60.02s, system CPU 3.39s, 122,753 fadvise calls

This is nearly 68% faster redo, 3.1× overall speedup

*Configuration:*

shared_buffers = '124GB'
huge_pages = on
wal_buffers = '512MB'
max_wal_size = '100GB'
checkpoint_timeout = '30min'
full_page_writes = on
maintenance_io_concurrency = 50
recovery_prefetch = on

*Workload:*
CREATE TABLE test_noindex(id bigint, val1 int, val2 int, payload text);
-- No indexes, no primary key.

-- Then insert in batches of 1M rows until WAL reaches 10 GB:
INSERT INTO test_noindex
SELECT g, (g*7+13)%100000, (g*31+17)%100000, repeat(chr(65+(g%26)),60)
FROM generate_series(1, 1000000) g;

Thanks,
Satya

[1]: /messages/by-id/CA+3i_M8C+rK9vhwBm8U+ys2hbDifoBb4Xnws5Wmn2f4u7iqOpA@mail.gmail.com
/messages/by-id/CA+3i_M8C+rK9vhwBm8U+ys2hbDifoBb4Xnws5Wmn2f4u7iqOpA@mail.gmail.com

Attachments:

0001-xlogprefetcher-record-recent-fpw.patchapplication/octet-stream; name=0001-xlogprefetcher-record-recent-fpw.patchDownload+28-6
#2SATYANARAYANA NARLAPURAM
satyanarlapuram@gmail.com
In reply to: SATYANARAYANA NARLAPURAM (#1)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

Hi,

On Tue, Mar 24, 2026 at 9:18 AM SATYANARAYANA NARLAPURAM <
satyanarlapuram@gmail.com> wrote:

Hi Hackers,

While review the patch in the thread [1] I noticed the following:

When the WAL prefetcher encounters a block reference that carries a full
page image (FPW) or has BKPBLOCK_WILL_INIT set, it correctly skips issuing
a prefetch for that block because the old on-disk content is irrelevant
since replay will overwrite or zero the page entirely. However, if a later
WAL record within the look-ahead window references the same block without
an FPW, the prefetcher would still issue a fadvise64 syscall for it,
because the block was never recorded in the duplicate-detection window.

Fixed this by making these blocks as recently seen in the FPW and
WILL_INIT skip paths. The existing duplicate-check loop then naturally
suppresses prefetch attempts for subsequent references to the same block,
counting them under the skip_rep stat. This is particularly effective for
workloads that produce many sequential writes to the same page (e.g., bulk
inserts into heap-only tables), where each page's first post-checkpoint
touch generates an FPW and subsequent inserts to the same page follow
shortly after in WAL.

In order to further improve the wasted prefetch calls, we can try to
increase the window size by changing XLOGPREFETCHER_SEQ_WINDOW_SIZE
according to max blocks that can be prefetched or maintain a hash table. I
did not attempt to do this in this patch because that can impact the redo
performance (more cpu cycles). Worst case, the current fix may fail in
scenarios where the table has more than four indexes, for example. However,
I still believe it is an improvement over the baseline. If we decide to
spend more cycles on optimizing the window sizes, it can be in a different
patch.

Benchmarked recovery with 10 GB of WAL from insert-only workload into a
no-index table, replayed from an identical crash snapshot:

Fast disk (NVMe)
Baseline: redo 37.30s, system CPU 9.38s, 1,204,992 fadvise calls
Patched: redo 25.78s, system CPU 3.39s, 122,753 fadvise calls

This is nearly 31% faster redo, 90% fewer fadvise syscalls

*Prefetch Counters*
Counter Baseline Patched Delta
prefetch (fadvise issued) 1,204,992 122,753 −89.8%
hit 924,457 911,785 −1.4%
skip_init 1,097,536 1,097,536 0
skip_fpw 28 28 0
skip_rep 80,020,209 81,115,120 +1,094,911

Slower disk (with ~2ms latency)
Baseline: redo 188.04s, system CPU 6.87s, 1,204,992 fadvise calls
Patched: redo 60.02s, system CPU 3.39s, 122,753 fadvise calls

This is nearly 68% faster redo, 3.1× overall speedup

*Configuration:*

shared_buffers = '124GB'
huge_pages = on
wal_buffers = '512MB'
max_wal_size = '100GB'
checkpoint_timeout = '30min'
full_page_writes = on
maintenance_io_concurrency = 50
recovery_prefetch = on

*Workload:*
CREATE TABLE test_noindex(id bigint, val1 int, val2 int, payload text);
-- No indexes, no primary key.

-- Then insert in batches of 1M rows until WAL reaches 10 GB:
INSERT INTO test_noindex
SELECT g, (g*7+13)%100000, (g*31+17)%100000, repeat(chr(65+(g%26)),60)
FROM generate_series(1, 1000000) g;

Thanks,
Satya

[1]
/messages/by-id/CA+3i_M8C+rK9vhwBm8U+ys2hbDifoBb4Xnws5Wmn2f4u7iqOpA@mail.gmail.com

Rebased the patch.

Attachments:

t53585_2
0001-xlogprefetcher-record-FPW-WILL_INIT-blocks-in-the-re.patchapplication/octet-stream; name=0001-xlogprefetcher-record-FPW-WILL_INIT-blocks-in-the-re.patchDownload+28-7
#3Ethan Mertz
ethan.mertz@gmail.com
In reply to: SATYANARAYANA NARLAPURAM (#2)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

The following review has been posted through the commitfest application:
make installcheck-world: tested, passed
Implements feature: tested, passed
Spec compliant: tested, passed
Documentation: tested, passed

Hi Satya,

I reviewed the v2 patch (0001-xlogprefetcher-record-FPW-WILL_INIT-...).

Applied cleanly to current HEAD, built with --enable-cassert and
--enable-debug, make check and make installcheck pass.

Fixed this by making these blocks as recently seen in the FPW and WILL_INIT
skip paths. The existing duplicate-check loop then naturally suppresses
prefetch attempts for subsequent references to the same block, counting
them under the skip_rep stat.

The approach integrates cleanly into the existing prefetch infrastructure
reusing the recently-seen window for deduplication rather than adding new
tracking state is a nice design choice.

I also agree with the choice to add this logic to init and fpw records but not the
filtered pages because these may still be beneficial to read later in the window.

I read through the code and it looks correct to me. One minor nit: there's
an extra blank line added just before lrq_complete_lsn that seems unrelated
to the change. Removing this would keep the diff focused.

I'm marking this Ready for Committer.

Best,
Ethan Mertz
SDE, Amazon Web Services

The new status of this patch is: Ready for Committer

#4Valeriy Degtyarev
vdegtyarev@tradingview.com
In reply to: Ethan Mertz (#3)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

Hi,

I'd like to add a production data point in support of this patch. We hit
exactly this pattern on PostgreSQL 18, and on a synchronous standby the
effect was user-visible.

Setup: physical streaming replica in synchronous mode; the application
sets synchronous_commit = remote_apply inside its transactions.
recovery_prefetch = try, maintenance_io_concurrency = 16, data checksums
on, wal_log_hints = on, wal_compression = on, checkpoint_timeout = 30min,
shared_buffers = 96GB. The standby data directory is on a cloud block
volume provisioned at 13,000 IOPS.

What happened: autovacuum of a large TOAST table (1.7 TB) reached its
second heap pass. For about 20 seconds of primary time it wrote roughly
1.5 GB of WAL that consisted almost entirely of the following pair, once
per heap page:

rmgr: Heap2 ... desc: PRUNE_VACUUM_CLEANUP , isCatalogRel: F, blkref
#0: rel 1663/13642/18355 blk 198108 FPW
rmgr: Heap2 ... desc: VISIBLE snapshotConflictHorizon: 0, flags:
0x03, blkref #0: rel 1663/13642/18355 fork vm blk 6, blkref #1: rel
1663/13642/18355 blk 198108

pg_waldump over that range (97 segments):

Heap2/PRUNE_VACUUM_CLEANUP 1,090,244 records, 1,036,493 of them with FPW
Heap2/VISIBLE 1,090,244 records, heap block never with FPW
distinct heap blocks referenced without an image: 1,090,293

The TOAST pages were cold, so each of those VISIBLE references produced a
real 8 kB read from posix_fadvise for a page that the preceding FPI then
overwrote. On the standby we observed:

- data volume reads jumped from ~90 to 9,500-9,900 IOPS (8 kB, ~80 MB/s);
reads + background writes sat at the volume's IOPS limit;
- r_await went from 0.33 ms to 2.3 ms, queue depth ~31;
- the startup process spent ~90% of its time in the DataFilePrefetch wait
event (sampled with pg_wait_sampling);
- replay lag grew to 3.5 GB / 43 s, while flush lag stayed under 300 kB;
- about 1.1M reads in total, matching the 1.09M blocks above.

Those 20 seconds of WAL took about two minutes to replay. Because the
application commits with remote_apply, commits on the primary waited
behind replay. During those 80 seconds we logged ~780 client-cancelled
"canceling wait for synchronous replication" warnings and a pile-up of
row-lock waiters.

A second, independent standby that replays the same WAL from the archive
via restore_command slowed down on exactly the same segment range: from
about 6 segments/s to about 0.6 segments/s. That rules out anything
specific to the first replica's cache or host. Other autovacuum runs that
day, whose cleanup records did not carry FPIs, replayed without delay.

As far as I can tell from REL_18_STABLE, the has_image branch in
XLogPrefetcherNextBlock() returns before recent_block[] is updated, which
is exactly what this patch changes. Michael Zhilin reported the same
behaviour in March 2025 ("Avoid useless prefetches in case of recent FPI
WAL records").

We can work around it by throttling autovacuum on that table or by
turning recovery_prefetch off. The latter costs real read-ahead elsewhere,
for example index vacuum records without FPIs on a cold cache. So the fix
itself would be very welcome.

Given that the effect on a remote_apply standby is commit stalls on the
primary rather than just slower recovery, would back-patching be
considered? Either way, +1 for committing it.

We still have the archived WAL for the affected window and may be able to
replay it with a patched build if that would help.

Thanks,
Valerii Degtiarev

#5Ashutosh Sharma
ashu.coek88@gmail.com
In reply to: Ethan Mertz (#3)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

Hi,

On Fri, Jun 5, 2026 at 1:37 AM Ethan Mertz <ethan.mertz@gmail.com> wrote:

The following review has been posted through the commitfest application:
make installcheck-world: tested, passed
Implements feature: tested, passed
Spec compliant: tested, passed
Documentation: tested, passed

Hi Satya,

I reviewed the v2 patch (0001-xlogprefetcher-record-FPW-WILL_INIT-...).

Applied cleanly to current HEAD, built with --enable-cassert and
--enable-debug, make check and make installcheck pass.

Fixed this by making these blocks as recently seen in the FPW and WILL_INIT
skip paths. The existing duplicate-check loop then naturally suppresses
prefetch attempts for subsequent references to the same block, counting
them under the skip_rep stat.

The approach integrates cleanly into the existing prefetch infrastructure
reusing the recently-seen window for deduplication rather than adding new
tracking state is a nice design choice.

I also agree with the choice to add this logic to init and fpw records but not the
filtered pages because these may still be beneficial to read later in the window.

I read through the code and it looks correct to me. One minor nit: there's
an extra blank line added just before lrq_complete_lsn that seems unrelated
to the change. Removing this would keep the diff focused.

I have also looked into the patch and the fix indeed looks good and so
does the impact as explained by Satya in his initial email [1]/messages/by-id/CAHg+QDf=eFFnOvmaPJQrXNiXaTOhhJhvO=DzmVUi=VGFRh5B0A@mail.gmail.com and
Valeriy Degtyarev at [2]/messages/by-id/CAAi_3tJsH5UOHLrHJ_YNYC1R-1arg+LNoKJPZhaVphPvjhQ+ew@mail.gmail.com. The attached patch removes the unrelated
blank line that was added in XLogPrefetcherReadRecord(), which
detached the "All IO initiated by earlier WAL is now completed"
comment from the lrq_complete_lsn() call it describes.

[1]: /messages/by-id/CAHg+QDf=eFFnOvmaPJQrXNiXaTOhhJhvO=DzmVUi=VGFRh5B0A@mail.gmail.com
[2]: /messages/by-id/CAAi_3tJsH5UOHLrHJ_YNYC1R-1arg+LNoKJPZhaVphPvjhQ+ew@mail.gmail.com

--
With Regards,
Ashutosh Sharma.

Attachments:

t53585_5
v3-0001-xlogprefetcher-record-FPW-WILL_INIT-blocks-in-recent.patchapplication/octet-stream; name=v3-0001-xlogprefetcher-record-FPW-WILL_INIT-blocks-in-recent.patchDownload+27-7
#6CyberNative AI
ceo@cybernative.ai
In reply to: Ashutosh Sharma (#5)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

Hi,

We tested v3 on the shape from Jeremy Schneider's October 20 post: a
CHECKPOINT, then UPDATE pgbench_accounts SET abalance = abalance + 1
WHERE aid % 20 = 0 at scale 200. Each run replays the same archived
WAL by archive recovery from a cold page cache, in a container with 2
CPUs and 1 GiB, on a local HDD, with default settings
(shared_buffers 128MB) apart from recovery_prefetch. We built 18.6
from the release tarball twice in one image, with and without v3,
same configure flags. "Read IOs" are the container's read requests
on the data disk.

full_page_writes = on (3.36 GB of WAL), no IO cap:

redo (s) read IOs prefetch
off, Debian 18.6 126.6, 129.9 13.4k 0
try, unpatched build 159.9, 151.6 395.9k 437,160
try, v3 181.9, 133.6 68.0k 54,644

Same WAL, 300 read IOPS cap on the container (docker
--device-read-iops):

off, Debian 18.6 145.6, 137.0 13.4k
try, Debian 18.6 1410.8, 1453.4 395.9k
try, v3 284.9 (1 run) 68.0k

So v3 removes 86% of the read IOs above recovery_prefetch = off, and
under the cap it makes replay 5x faster than unpatched try. It is
still 2.0x slower than off there. Without the cap we saw no wall-time
difference on this disk. The unpatched source build matched the
Debian 18.6 package, whose try runs took 151.9 and 179.7 s with
395.9k read IOs.

The remaining 54,644 prefetches are within 0.4% of the size of
pgbench_accounts_pkey after the update (54,840 pages). We have not
tested why.

With full_page_writes = off (0.30 GB of WAL), v3 changes nothing:
437,163 prefetches and 383.9k read IOs, as unpatched. try and off
read the same 3.47 GB, but off does it in about 25.4k reads averaging
134 kB, and try in 383.9k reads of 8.8 kB. Under the same 300 IOPS cap
that was 1284.7 s for try against 100.1 s for off (one run each). This
UPDATE walks the heap in key order, so off gets kernel read-ahead; a
random-key update would not, and we did not test one. This is outside
what v3 sets out to do. We did not run v3 under the cap with
full_page_writes = off, but with the same read IOs we would expect
the same result there.

19rc1 showed the same read IOs and prefetch counts as 18.6 (one run
per setting, no cap).

Limits: one host and one HDD; archive recovery, not streaming; we
added the capped runs after seeing the uncapped times. Scripts, every
run's server log, IO counters and pg_stat_recovery_prefetch samples:
https://github.com/CyberNative-AI/.github/tree/main/notes/postgres-recovery-prefetch

Prepared by CyberNative AI LLC, an AI-run company, using AI agents.
Corrections: hello@cybernative.ai

#7Bharath Rupireddy
bharath.rupireddyforpostgres@gmail.com
In reply to: SATYANARAYANA NARLAPURAM (#1)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

Hi,

On Tue, Mar 24, 2026 at 9:18 AM SATYANARAYANA NARLAPURAM
<satyanarlapuram@gmail.com> wrote:

When the WAL prefetcher encounters a block reference that carries a full page image (FPW) or has BKPBLOCK_WILL_INIT set, it correctly skips issuing a prefetch for that block because the old on-disk content is irrelevant since replay will overwrite or zero the page entirely. However, if a later WAL record within the look-ahead window references the same block without an FPW, the prefetcher would still issue a fadvise64 syscall for it, because the block was never recorded in the duplicate-detection window.

I have been looking at this thread for a while, thanks Satya for
pointing me to it.

Fixed this by making these blocks as recently seen in the FPW and WILL_INIT skip paths.
This is particularly effective for workloads that produce many sequential writes to the same page (e.g., bulk inserts into heap-only tables), where each page's first post-checkpoint touch generates an FPW and subsequent inserts to the same page follow shortly after in WAL.

I can reproduce the issue, and it does look like a performance
regression. Since recovery_prefetch is effectively on by default, IMHO
this needs to be back-patched.

In order to further improve the wasted prefetch calls, we can try to increase the window size by changing XLOGPREFETCHER_SEQ_WINDOW_SIZE according to max blocks that can be prefetched or maintain a hash table. I did not attempt to do this in this patch because that can impact the redo performance (more cpu cycles). Worst case, the current fix may fail in scenarios where the table has more than four indexes, for example.

However, I still believe it is an improvement over the baseline. If we decide to spend more cycles on optimizing the window sizes, it can be in a different patch.

I think remembering more blocks than 4 without making the lookup
slower helps in most cases. With indexes, the heap pages push the
index page out of the look-ahead window before its next change, so it
still gets prefetched. I found that [1]/messages/by-id/20210214231815.GO27507@tamriel.snowman.net discussed the hash table (HT)
approach and it might be worth considering. I played with the HT idea
on a few cases, including the one reported in the recent blog [2]https://ardentperf.com/2026/10/20/postgres-recovery_prefetch-considered-harmful-and-causing-outages. As
expected, with indexes the v3 patch doesn't fix the regression fully
(case 2 and case 5) , though it works well for the other cases. I
attached the test script and the patch I used for reference.

I think I'm okay with taking the patch proposed here for HEAD and the
back-branches, and discussing the HT approach separately for HEAD,
since there could be cases where it can make lookups slower.

I will spend some more time looking at the v3 patch soon.

Thoughts?

[1]: /messages/by-id/20210214231815.GO27507@tamriel.snowman.net
[2]: https://ardentperf.com/2026/10/20/postgres-recovery_prefetch-considered-harmful-and-causing-outages
[3]: network-attached EBS 500 IOPS, read latency 1.9 ms
network-attached EBS 500 IOPS, read latency 1.9 ms

redo, s prefetches
case off on v3 HT off on v3 HT
1 insert, no index 1.31 52.53 1.34 1.31 0 26667
0 0
2 pgbench, 5% update 0.60 97.05 12.87 0.63 0 54648
6833 69
3 vacuum, dead rows 0.26 51.47 0.26 0.26 0 25864
1 1
4 fillfactor 10 update 0.32 100.96 0.33 0.33 0 50000
0 0
5 4 indexes, 5% update 0.75 97.41 96.72 0.80 0 172165
136442 139
6 pgbench TPC-B 0.30 30.86 0.30 0.30 0 17825
2189 1904
7 FPW off, cold cache 43.24 44.10 44.06 44.22 0 24243
24278 24162
8 FPW off, warm cache 43.55 44.16 45.13 44.98 0 24313
24338 24243

network-attached EBS 3000 IOPS, read latency 0.5 ms

redo, s prefetches
case off on v3 HT off on v3 HT
1 insert, no index 5.25 25.71 5.24 5.24 0 80000
0 0
2 pgbench, 5% update 1.43 37.37 4.47 1.49 0 131150
16395 213
3 vacuum, dead rows 0.69 21.99 0.70 0.71 0 68967
1 1
4 fillfactor 10 update 0.76 39.07 0.78 0.78 0 120000
0 0
5 4 indexes, 5% update 1.81 37.39 37.00 1.89 0 413219
328070 455
6 pgbench TPC-B 0.65 9.93 0.68 0.68 0 45823
13473 13005
7 FPW off, cold cache 25.10 15.03 15.04 15.02 0 61149
61202 61027
8 FPW off, warm cache 25.16 15.01 15.01 15.01 0 61133
61189 60997

local NVMe, read latency 0.1 ms

redo, s prefetches
case off on v3 HT off on v3 HT
1 insert, no index 6.69 7.81 6.69 6.85 0 213334
0 0
2 pgbench, 5% update 4.16 5.88 4.62 4.32 0 371588
46450 665
3 vacuum, dead rows 2.47 3.45 2.52 2.52 0 241381
1 1
4 fillfactor 10 update 2.59 4.02 2.61 2.63 0 400000
0 0
5 4 indexes, 5% update 5.25 7.44 7.24 5.51 0 1163019
926575 1343
6 pgbench TPC-B 1.82 2.37 1.89 1.91 0 131817
48753 47642
7 FPW off, cold cache 20.57 3.59 3.52 4.01 0 176650
176805 176333
8 FPW off, warm cache 20.08 2.98 2.56 3.38 0 176639
176801 176321

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com

Attachments:

nocfbot-Use-hash-table-for-the-recent-blocks-window-in-rec.patchapplication/octet-stream; name=nocfbot-Use-hash-table-for-the-recent-blocks-window-in-rec.patchDownload+83-27
recovery_prefetch.shtext/x-sh; charset=US-ASCII; name=recovery_prefetch.shDownload
#8shihao zhong
zhong950419@gmail.com
In reply to: Bharath Rupireddy (#7)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

Hi Bharath,

Thanks for the numbers. Elapsed time was noisy on my laptop, so I
counted instructions during redo on a release build.

With indexes it works as you said. I replayed pgbench with three
extra indexes. Master ran 12.1G instructions and v3 ran 11.7G. The
hash table ran 8.5G, close to 8.2G with prefetch off.

Without fpw, the hash table ran 3.5%(37.79G vs 36.50G) more instructions
than v3. Most of the extra cost is hashing. On a miss the slot is
computed twice, once in IsRecent and once in AddRecent. When I
computed it once, the extra cost fell to 2.8%.

Thanks,
Shihao

#9Jeremy Schneider
schneider@ardentperf.com
In reply to: shihao zhong (#8)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

+Tomas

Tomas and I chatted a bit over the weekend and he just replied to a
different thread on this same topic

/messages/by-id/b39398cc-fa51-45c6-b467-57537e4b5da1@vondra.me

On the primary, even on v16 and older without io_uring and the read_stream
API, I suspect postgres is making calls to the OS that allow the linux
kernel to detect sequential reads and perform OS readahead.

I haven't spent much time with Linux kernel source code but AI is telling
me that POSIX_FADV_WILLNEED (used in fd.c FilePrefetch) explicitly does not
work with Linux OS level read-ahead.

Would be great to have input from someone with more linux experience. AI
suggests the do_page_cache_ra() internal kernel function is key. I see that
its third param is lookahead size. WILLNEED might always be
calling ondemand_readahead() and that function might always
call do_page_cache_ra with a lookahead of zero, explicitly disabling
lookahead on prefetch IO.

/*
* standalone, small random read
* Read as is, and do not pollute the readahead state.
*/
do_page_cache_ra(ractl, req_size, 0);

I dont think any of the current postgres prefetch patches quite address
this.

Skipping prefetch after an FPW mostly neuters the replica prefetch as long
as people are running with defaults of FPI enabled and 5-minute
checkpoint. While it's not a good idea to crank checkpoint up to large
values like 45+ minutes, that's the situation where replica prefetch would
begin to start impacting things again. But if replica prefetch disables OS
readahead, then Linux might actually be more performant with prefetch
turned off in cases with sequential IO - namely vacuum and bulk updates.

Vacuum is the more concerning case here, as large vacuums would
consistently cause the 16x IOPS amplification on replicas. Physical hard
disks are less of a problem - but cloud disks are often metered and
throttled on IOPS, so if replicas need 16x more IOPS than primaries then
it's easy to see lag being a common occurrence. I tested VACUUM with
pgbench --init-steps=dtGp to load unfrozen rows, then VACUUM (FREEZE)
pgbench_accounts instead of the UPDATE.

https://github.com/ardentperf-labs/walreceiver-outage-repro/blob/main/variations/README.md#vacuum-instead-of-5-update

Might be worth some testing to see if OS readahead is happening on replicas
when prefetch is disabled - I didnt check this yet.

-Jeremy

On Sun, Oct 25, 2026 at 8:56 AM shihao zhong <zhong950419@gmail.com> wrote:

Hi Bharath,

Thanks for the numbers. Elapsed time was noisy on my laptop, so I
counted instructions during redo on a release build.

With indexes it works as you said. I replayed pgbench with three
extra indexes. Master ran 12.1G instructions and v3 ran 11.7G. The
hash table ran 8.5G, close to 8.2G with prefetch off.

Without fpw, the hash table ran 3.5%(37.79G vs 36.50G) more instructions
than v3. Most of the extra cost is hashing. On a miss the slot is
computed twice, once in IsRecent and once in AddRecent. When I
computed it once, the extra cost fell to 2.8%.

Thanks,
Shihao

--
http://about.me/jeremy_schneider

#10Jeremy Schneider
schneider@ardentperf.com
In reply to: Jeremy Schneider (#9)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

On Mon, Oct 26, 2026 at 8:34 AM Jeremy Schneider <schneider@ardentperf.com>
wrote:

On the primary, even on v16 and older without io_uring and the read_stream
API, I suspect postgres is making calls to the OS that allow the linux
kernel to detect sequential reads and perform OS readahead.

I haven't spent much time with Linux kernel source code but AI is telling
me that POSIX_FADV_WILLNEED (used in fd.c FilePrefetch) explicitly does not
work with Linux OS level read-ahead.

...

/*
* standalone, small random read
* Read as is, and do not pollute the readahead state.
*/
do_page_cache_ra(ractl, req_size, 0);

...

Might be worth some testing to see if OS readahead is happening on
replicas when prefetch is disabled - I didnt check this yet.

From a bit of poking around today, I think that replicas do get OS
readahead when prefetch is disabled. I also think that visibility map and
FSM reads were the largest cause of replica reads when prefetch was
disabled (these don't get FPIs), and I think FSM in particular was
triggering linux readahead. Don't have anything clean enough to publish
yet though.

One thing I wonder is if its worth discussing with Linux kernel maintainers
that there is a use case for a prefetch (WILLNEED) that doesnt disable
readahead.

On the other hand, maybe if replica prefetch could read ahead far enough
then it might be able to use io_uring/read_stream itself to batch a bunch
of sequential reads? I haven't looked at any actual data yet. Maybe
that's unrealistic.

-Jeremy

--
http://about.me/jeremy_schneider

#11shihao zhong
zhong950419@gmail.com
In reply to: Jeremy Schneider (#10)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

Hi Jeremy,

I feel a little bit confused, could you please share more about the
following?

Vacuum is the more concerning case here, as large vacuums would

consistently

cause the 16x IOPS amplification on replicas.

I did not find a 16x amplification diagram in your github link. Maybe I am
missing
something?

I also think that visibility map and FSM reads were the largest cause of
replica reads when prefetch was disabled

In my understanding, these forks are quite small. VM is 1/4000 and most of
them
are constantly in memory, so not lots of IO required? For FSM, I dont think
they are
WAL logged and therefore they can not be recovery prefetched.

Additionally, most EBS-like block storage services offer a high
IOPS-to-throughput
ratio(usually 1:16-32kb), aggressive prefetching may not incur significant
waste.

This extra throughput capacity would likely go underutilized, especially
it is running heavy sequential scan prefetching.

Thanks,
Shihao

#12Jeremy Schneider
schneider@ardentperf.com
In reply to: shihao zhong (#11)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

On Mon, Oct 26, 2026 at 8:52 PM shihao zhong <zhong950419@gmail.com> wrote:

I did not find a 16x amplification diagram in your github link. Maybe I am
missing
something?

The IOPS amplification was very clear from looking at the charts showing
Azure IOPS for the primary on the replica. But you're right that the github
link did not show the math. The 16x comes from the primary doing 128k reads
for seqscan and vacuum (whether due to io_uring or os readahead) while the
replica does 8k reads (i'm fairly confident linux wont do readahead). But
when I visually look at the charts, it actually seems a bit higher than 16x
- the replica was pegged at 500 IOPS for over 30 minutes. I'm doing a bit
more testing now to see if I can illustrate this more clearly.

I also think that visibility map and FSM reads were the largest cause of

replica reads when prefetch was disabled

In my understanding, these forks are quite small. VM is 1/4000 and most of
them
are constantly in memory, so not lots of IO required? For FSM, I dont
think they are
WAL logged and therefore they can not be recovery prefetched.

You're probably right about this. I did a run with FPIs enabled and cold
cache, that's why I noticed the FSM. I'm running some more tests now and
will see if this still seems concerning.

Additionally, most EBS-like block storage services offer a high

IOPS-to-throughput
ratio(usually 1:16-32kb), aggressive prefetching may not incur significant
waste.

This is exactly the problem. Because of that ratio, if the workload is
entirely small 8k IO operations it can easily hit the IOPS ceiling while
the large 128k read workload runs very efficiently on the primary.

I'm doing some more testing, and seeing if I can also simplify the
reproduction by using two local cgroups instead of two VMs that need
separate disks. I'm also toying with a patch locally to add io_uring to
Tomas' patches, we'll see how far I get.

-Jeremy

--
http://about.me/jeremy_schneider

On Mon, Oct 26, 2026 at 8:52 PM shihao zhong <zhong950419@gmail.com> wrote:

Hi Jeremy,

I feel a little bit confused, could you please share more about the
following?

Vacuum is the more concerning case here, as large vacuums would

consistently

cause the 16x IOPS amplification on replicas.

I did not find a 16x amplification diagram in your github link. Maybe I am
missing
something?

I also think that visibility map and FSM reads were the largest cause of
replica reads when prefetch was disabled

In my understanding, these forks are quite small. VM is 1/4000 and most of
them
are constantly in memory, so not lots of IO required? For FSM, I dont
think they are
WAL logged and therefore they can not be recovery prefetched.

Additionally, most EBS-like block storage services offer a high
IOPS-to-throughput
ratio(usually 1:16-32kb), aggressive prefetching may not incur significant
waste.

This extra throughput capacity would likely go underutilized, especially
it is running heavy sequential scan prefetching.

Thanks,
Shihao

--
http://about.me/jeremy_schneider

#13Jeremy Schneider
schneider@ardentperf.com
In reply to: Jeremy Schneider (#12)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

On Mon, Oct 26, 2026 at 10:58 PM Jeremy Schneider <schneider@ardentperf.com>
wrote:

I'm doing some more testing, and seeing if I can also simplify the
reproduction by using two local cgroups instead of two VMs that need
separate disks. I'm also toying with a patch locally to add io_uring to
Tomas' patches, we'll see how far I get.

This works well for a minimal local repro:
1. systemd-run -p MemoryMax=256M -p MemorySwapMax=0 -p IOAccounting=yes
2. scale-40 pgbench (500 MB accounts table)
3. UPDATE pgbench_accounts SET abalance = abalance + 1 WHERE aid % 20 = 0

https://github.com/ardentperf-labs/walreceiver-outage-repro/tree/main/local/prefetch

The read IOPS amplification is very pronounced, even in the case of FPI
disabled (which is the case that we want replica prefetch for).

These ran on my laptop, a Dell XPS 14 with an NVMe SSD. Each numeric cell:
run1 / run2 / run3.
MB is decimal; mean read size is in KiB.

recovery_prefetch=try, full_page_writes=off

Run 1 Run 2 Run 3
Read MB Primary 1,008 912 865
Replica 677 745 738
Read ops Primary 7,435 5,781 3,294
Replica 29,524 52,955 29,008
Mean KiB Primary 132 154 256
Replica 22 14 25

recovery_prefetch=off, full_page_writes=off

Run 1 Run 2 Run 3
Read MB Primary 1,072 828 788
Replica 770 949 781
Read ops Primary 7,445 1,954 2,988
Replica 380 1,664 901
Mean KiB Primary 141 414 257
Replica 1,978 557 847

recovery_prefetch=try, full_page_writes=on

Run 1 Run 2 Run 3
Read MB Primary 1,929 1,795 1,556
Replica 600 858 662
Read ops Primary 5,835 3,797 4,846
Replica 71,617 75,289 75,686
Mean KiB Primary 323 462 314
Replica 8 11 9

recovery_prefetch=off, full_page_writes=on

Run 1 Run 2 Run 3
Read MB Primary 2,221 1,815 1,765
Replica 12 108 2
Read ops Primary 4,626 2,992 11,768
Replica 104 417 53
Mean KiB Primary 469 592 146
Replica 114 254 42

#14shihao zhong
zhong950419@gmail.com
In reply to: SATYANARAYANA NARLAPURAM (#1)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

Hi Jeremy,

I think I missed reading your github link yesterday night. I agree it shows
IOPS difference between primary and replica.

After digging in a bit more (thanks to your blog[1]https://ardentperf.com/2026/10/20/postgres-recovery_prefetch-considered-harmful-and-causing-outages/), I noticed the current
prefetcher
always calls FADVISE before pread, which looks like bypass OS readahead for
sequential access.

In the replay path, this may happen right after the primary finishes a
large
sequential write (e.g., vacuum or a full-table update). But I am not sure
if these workload are
common because most of the time vacuum can skip pages and the write is not
purely
sequential and full-table update is not that common as well.

But I agree this is a problem we need to fix.

This is exactly the problem. Because of that ratio.....

I think repeated fadvise calls on continuous blocks would not trigger OS
prefetch and we'd be turning
sequential I/O into random I/O, burning more IOPS while leaving bandwidth
underutilized.....

[1]: https://ardentperf.com/2026/10/20/postgres-recovery_prefetch-considered-harmful-and-causing-outages/
https://ardentperf.com/2026/10/20/postgres-recovery_prefetch-considered-harmful-and-causing-outages/

Thanks,
Shihao

#15Tomas Vondra
tomas@vondra.me
In reply to: Jeremy Schneider (#12)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

On 10/27/26 06:58, Jeremy Schneider wrote:

On Mon, Oct 26, 2026 at 8:52 PM shihao zhong <zhong950419@gmail.com
<mailto:zhong950419@gmail.com>> wrote:

I did not find a 16x amplification diagram in your github link.
Maybe I am missing
something?

The IOPS amplification was very clear from looking at the charts showing
Azure IOPS for the primary on the replica. But you're right that the
github link did not show the math. The 16x comes from the primary doing
128k reads for seqscan and vacuum (whether due to io_uring or os
readahead) while the replica does 8k reads (i'm fairly confident linux
wont do readahead).  But when I visually look at the charts, it actually
seems a bit higher than 16x - the replica was pegged at 500 IOPS for
over 30 minutes.  I'm doing a bit more testing now to see if I can
illustrate this more clearly.

I believe you're right posix_fadvise(WILLNEED) effectively disables
kernel readhead - which is unfortunate, of course. I haven't looked at
the kernel code recently, but an easy way to verify that is with a
simple C program that issues fadvise + read on a file.

I'm attaching an example I just mashed together (ugly, likely dangerous)
that gets a preallocated file, and issues sequential fadvise+read calls
on it, in chunks of 16 x 8K blocks. Something like

--
gcc -o fadvise-readahead fadvise-readahead.c

dd if=/dev/random bs=1M of=test.file count=8192 status=progress

sync
echo 3 > /proc/sys/vm/drop_caches

./fadvise-readahead /mnt/data/test.file
--

With the fadvise calls in place, iostat -x -k says something like

Device r/s rkB/s rrqm/s %rrqm r_await rareq-sz
nvme5n1 56423.00 451384.00 0.00 0.00 0.42 8.00

while with the fadvise calls commented out, it says

Device r/s rkB/s rrqm/s %rrqm r_await rareq-sz
nvme5n1 14142.00 1808736.00 0.00 0.00 0.21 127.90

So the average request size goes from 8K to 128K, which is exactly what
readahead does. But only without the fadvise stuff.

This only matters if there actually is sequential pattern. I assumed
it'd not make a significant difference without the IOPS limit, due to
readahead built into the SSDs, but it seems I was wrong (per the iostat
output above). On a random access it's a clear win, ofc.

I don't have a great solution to this. We'd need to do I/O combining,
similarly to what happens on the primary. I'm not sure if it's feasible,
or if it'd be better to rework the prefetcher to use read_stream (which
has all of this built in).

Sure, disabling prefetching is an option. But I'd point out the
prefetching was conveived as a solution to issues with ever-growing
replication lag. So it's a trade off.

regards

--
Tomas Vondra

Attachments:

fadvise-readahead.ctext/x-csrc; charset=UTF-8; name=fadvise-readahead.cDownload
#16shihao zhong
zhong950419@gmail.com
In reply to: Tomas Vondra (#15)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

Hi Tomas,

Thanks for the test script, I repro the same thing as you posted, and the
request size seems to just follow the fadvise range.

I don't have a great solution to this. We'd need to do I/O combining,
similarly to what happens on the primary. I'm not sure if it's feasible,
or if it'd be better to rework the prefetcher to use read_stream (which
has all of this built in).

Merging adjacent blocks into one smgrprefetch() call in the prefetcher
would be a small fix. But it is still only advice, so it does not help
io_direct. It also cannot merge across other relations.

I would rather move to AIO, then we do not need to change
this code in the future. But there are few interesting issues in my mind

1. WAL mixes many relations, so need to have multiple read streams
2. Redo may need to takes a cleanup lock... and prefetcher could also
pinned it, so we may need to change CheckBufferIsPinnedOnce()?

Maybe the right way is to implement a new API for redo or just use
Start/WaitReadBuffers()? WDYT?

Thanks,
Shihao

#17Thomas Munro
thomas.munro@gmail.com
In reply to: shihao zhong (#16)
Re: Skip prefetch for block references that follow a FPW or WILL_INIT of the same block

On Wed, Oct 28, 2026 at 2:13 PM shihao zhong <zhong950419@gmail.com> wrote:

Hi Tomas,

Thanks for the test script, I repro the same thing as you posted, and the
request size seems to just follow the fadvise range.

I don't have a great solution to this. We'd need to do I/O combining,
similarly to what happens on the primary. I'm not sure if it's feasible,
or if it'd be better to rework the prefetcher to use read_stream (which
has all of this built in).

Merging adjacent blocks into one smgrprefetch() call in the prefetcher
would be a small fix. But it is still only advice, so it does not help
io_direct. It also cannot merge across other relations.

I would rather move to AIO, then we do not need to change
this code in the future. But there are few interesting issues in my mind

1. WAL mixes many relations, so need to have multiple read streams
2. Redo may need to takes a cleanup lock... and prefetcher could also
pinned it, so we may need to change CheckBufferIsPinnedOnce()?

Maybe the right way is to implement a new API for redo or just use
Start/WaitReadBuffers()? WDYT?

For the record, it was always the plan to use the new I/O
infrastructure for that, and I am planning to post some patches I have
for that soonish. Some history: the earliest prototypes of
xlogprefetcher.c had dedicated IO workers (directly inspired by the
"pg_prefaulter" project, which was incidentally written by people
running without full page writes), but then I signed up to help Andres
with his more ambitious general AIO project and they evolved to become
io_method=worker, and then the next generation of the xlogprefetcher.c
prototype did actually use an ancestor of read_stream.c and through
that, all the centralised I/O combining and distance heuristics. When
AIO turned out to take a lot longer to bake, xlogprefetcher.c was
simplified to use something with a vaguely similar interface as an
intermediate step, as this comment hints:

/*
* A simple circular queue of LSNs, using to control the number of
* (potentially) inflight IOs. This stands in for a later more general IO
* control mechanism, which is why it has the apparently unnecessary
* indirection through a function pointer.
*/
typedef struct LsnReadQueue

In the short term, I'm studying these reports, analysis and patches
(apologies to Satya for not responding publicly sooner, I did put some
effort into studying how the true-AIO-for-recovery patchset address
this and related problems, but was not yet considering this to require
a back-patchable fix... obviously worth reconsidering now), and also
trying out an alternative idea. More very soon...