[RFC PATCH v1] On-demand WAL replay: accept connections before crash recovery has applied the WAL

Поиск
Список
Период
Сортировка
Искать

[RFC PATCH v1] On-demand WAL replay: accept connections before crash recovery has applied the WAL

От:
Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Дата:
Вложения:
Hi,

After a crash, the server cannot accept connections until all WAL written
since the last checkpoint has been replayed and, for crash recovery, until
the end-of-recovery checkpoint has written the result back to disk.  Both
are proportional to the amount of WAL, so time-to-connect after a crash is
bound by WAL volume.

The attached patches let the startup process scan that WAL without
applying the records that modify relation pages.  It replays everything
else eagerly (transaction status, multixacts, smgr and database
operations, ... anything without a block reference, which is cheap and has
no later page read that could trigger it), and records, per page, the LSNs
of the records that touch it, in a dshash table in dynamic shared memory.
Then the server opens.  A page is recovered the first time any process
reads it from disk, and a new auxiliary process recovers the rest in the
background; once it has finished, the index is destroyed and a checkpoint
is requested.

Where replay happens turned out to be the whole design, so that part
first.  On-demand replay runs inside StartReadBuffersImpl(), the common
path of ReadBuffer() and the read streams: a page with pending records is
read synchronously under its BM_IO_IN_PROGRESS flag, replayed, and only
then marked BM_VALID.  Nothing new is added to the buffer manager's
protocol: other backends that want the page wait in WaitIO() as they would
behind a slow disk, and since no backend has been handed the page, none can
hold pointers into it, which is why redo may take an exclusive lock on it
where it would normally need a cleanup lock (the same reasoning as in
ZeroAndLockBuffer()).  Redo is handed the buffer being filled instead of
reading the page again.  A record's other blocks report BLK_DONE, which
redo routines must handle anyway, because after a crash during recovery any
block may already be past the record's LSN; blocks a record initializes
get a scratch local buffer.  A page is replayed exactly once (full-page
images restore unconditionally, so replaying twice would rewind it), and
redo of an indexed page never reads another indexed page, so replays do
not nest.

I went through a series of crashes before arriving there, and they are
probably the most useful part of this mail for anyone touching the buffer
manager: a double content lock, unbounded recursion when redo re-read its
own page through the hook, "incorrect local pin count: 2" because a
cleanup-lock record saw the caller's pin and redo's, ItemIdIsNormal
failures in a parallel worker that had read the page through a read stream
(which bypassed my earlier hook) and kept line pointers under a pin while
another backend replayed a prune, and full-page images rewinding pages that
had been modified after recovery.  All of them came from one thing: the
page was visible before it was current.

Other design points:

- Checkpoints.  A checkpoint promises that everything before its redo point
  is on disk; pending pages would break that, so CreateCheckPoint() refuses
  while the LSNindex exists, unwaited requests are postponed, and a clean
  shutdown waits for the worker.  A request that waits for the checkpoint
  (CHECKPOINT, pg_backup_start(), CREATE/DROP DATABASE) therefore fails
  with "checkpoint request failed" during the window; for a base backup
  that is the right answer, since it would copy pages that are not current
  yet.  Whether such requests should wait for the worker instead is a
  question for this thread (see below).  An earlier version stopped the
  checkpointer altogether, which hung startup in RegisterSyncRequest(): it
  is also the process that absorbs every fsync request.

- Which records are eager.  The rule is "defer only if there is a trigger
  and a gain": a later page read that will find the record, and page I/O
  that is avoided by waiting.  An previous version deferred CLOG, and the
  first commit on a CLOG page that had never been created failed; the quiet
  failure mode would have been committed rows as aborted.

- Relations and databases dropped or truncated later in the WAL forget
  their pending pages.  A truncation is the one eager record that reads
  relation pages (the last FSM and VM page, to clear their tails).  When
  the next record for such a page arrives, the startup process writes the
  page out and drops it from shared buffers before indexing the record, so
  that no resident page has pending records when the server opens.  An
  earlier version instead kept such a page current by replaying every later
  record for it at once; that read those records' heap pages too, which
  then had to be kept current the same way, and one VACUUM truncation of a
  table under 255 MB (one VM page) made the rest of that table's records
  eager, each reading its heap page in the startup process (E below).

- Redo routines check InRecovery (visibilitymap_set() asserts it); it is set
  for the duration of on-demand redo.

- The feature applies to crash recovery under the postmaster only.  Archive
  recovery, standby mode and single-user mode log a message and replay WAL
  as usual.

Numbers.  Measured with a harness that crashes a pgbench run with
pg_ctl -m immediate, recovers the same crashed files twice (stock, and with
fast_crash_recovery on), and compares per-table hashes, an index-path read,
the tpcb balance invariant and pg_amcheck --heapallindexed right after the
server opens, after the worker has drained the index, and after a clean
restart.  No checkpoint runs during the workload.  The machine is a 6-vCPU
VMware VM with a virtual NVMe disk backed by the host, 15 GB RAM; the build
is -O2 without assertions.

A. pgbench scale 100 , with 2.0 GB of WAL, 5.4 M records, 220,823 distinct
pages, shared_buffers 128 MB, warm page cache:

                                                    stock      on-demand
  time to accept connections       15.1 s     2.7 s   (5.5x)
  redo / scan                                 5.8 s     2.7 s
  end-of-recovery checkpoint        9.2 s     0
  first seq scan after ready             1.3 s     2.4 s
  background drain                             -       37.2 s

B. Same scenario, cold page cache (2.7 GB of WAL, 9.0 M records,
270,127 pages):

  time to accept connections       96.1 s    43.0 s   (2.2x)
  redo / scan                                65.7 s    42.2 s
    of which I/O wait                     50.8 s    35.5 s
  end-of-recovery checkpoint      30.4 s     0.8 s
  first seq scan after ready          1.7 s     3.2 s
  background drain                      -       73.3 s

C. pgbench scale 200, shared_buffers 4 GB, 9.9 GB of WAL, 57.6 M records,
648,284 pages, cold cache (the hardest case: a large window with a big
shared_buffers, so stock recovery is mostly CPU):

  time to accept connections      199.4 s   106.4 s   (1.9x)
  redo / scan                               173.3 s   106.4 s
    of which CPU / I/O wait          52.3 / 121.1 s   47.4 / 59.0 s
  end-of-recovery checkpoint       26.1 s     0
  first seq scan after ready          10.4 s    72.6 s
  background drain                         -      506.8 s

D. pgbench scale 100, full_page_writes = off, 1.8 GB of WAL, 18.4 M
records, 323,250 pages, cold cache (the best case: every record needs its
page read):

  time to accept connections      197.2 s    40.0 s   (4.9x)
  redo / scan                               165.7 s    39.9 s
    of which I/O wait                     150.2 s    28.2 s
  end-of-recovery checkpoint       31.6 s     0
  first seq scan after ready            1.5 s     3.9 s
  background drain                           -       45.3 s

E. The truncation case from the design notes: pgbench scale 100 + a
140 MB table that VACUUM truncates three times during the run while clients
update it, 1.5 GB of WAL, shared_buffers 128 MB, files cached, so this
measures the scan's own work.  Before and after the eviction fix, same
workload, different crashes:

                                        kept current   evicted
  scan (time to accept connections)       4.8 s         3.6 s
  startup: relation pages read / written  23,942 / 4,654    8 / 5
  startup: WAL read beyond the window     905 MB        303 MB
  first scan of that table after ready    95 ms        600 ms

These runs show a reliable 2x to 5x reduction in hard downtime across
scenarios A–D. The exact multiple depends on how much I/O write-back
stock recovery is forced to do and also by completely bypassing the
massive end-of-recovery checkpoint, we shift the bottleneck entirely
away from disk writes down to raw scan CPU. This is a deliberate
architectural trade-off of total background work in exchange for
immediate availability. The deferred costs behave exactly as expected:
the first full scan of a hot table post-recovery is 1.5–7x slower due to
on-first-touch replay, and the background drain ultimately spends more
total time re-decoding WAL than stock recovery did. But the primary goal
of drastically shrinking the window where the database cannot accept
connections is achieved.

Two things I learned from measuring that I had wrong before.  With
full_page_writes on, stock crash recovery reads almost no data pages (the
first record for each page after the checkpoint carries the page), so its
critical path is CPU to apply + the write-back, not random reads.  And
the scan can be too fast for its own good: at -O2 it outran the kernel's
readahead window for 8 kB reads and spent 40 of 46 seconds waiting for
WAL, slower than stock recovery on the same files; a posix_fadvise
(WILLNEED) on each segment as it is opened fixed that, and the cold runs
above include it.

I intend to repeat the 10 and 50 GB points on EC2 with gp3 storage, where
the write-back and the evictions cost what they cost in production rather
than what a laptop's virtual disk feels like that minute.

Known limitations and also unknown :), which I would like to discuss:

1. The index is not bounded.  It is roughly 5-15% of the WAL volume and
   lives in DSM, which is /dev/shm, thinking to spill when hits a cap.
2. Also the fast crash recovery worker could be parallel, which makes
   replaying all the pending pages recovered , so the queries won't be slow.
3. Pending pages are read synchronously, one at a time, and look like
   buffer hits to the read stream, which shrinks its look-ahead, need
   to add AIO magic here, trying to figure out how.
4. A checkpoint requested during the window fails ("checkpoint request
   failed") rather than waits: CHECKPOINT, pg_backup_start() and
   CREATE/DROP DATABASE included.  The alternative is to have such a
   request wait for the worker in RequestCheckpoint(), since the caller
   was going to wait for the checkpoint anyway; I have that written, but
   kept the error in v1 so that we can decide here.  One visible
   consequence: with the fast_crash_recovery forced on, 018_wal_optimize can fail,
   because it issues CHECKPOINT right after a crash restart.

0001 is the feature
0002 adds a TAP test (src/test/recovery/t/060) and documentation.

check-world passes with the setting forced on through TEMP_CONFIG,
including the whole recovery suite, whose logs show the worker replaying
pages after every crash.  The one exception is 018_wal_optimize, which
can fail for the reason given in 4 above when the machine is loaded.

--
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/

Fwd: [RFC PATCH v1] On-demand WAL replay: accept connections before crash recovery has applied the WAL

От:
Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Дата:
Вложения:



---------- Forwarded message ---------
From: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Date: Sat, Oct 10, 2026 at 4:14 PM
Subject: [RFC PATCH v1] On-demand WAL replay: accept connections before crash recovery has applied the WAL
To: pgsql-hackers <pgsql-hackers@postgresql.org>


Hi,

After a crash, the server cannot accept connections until all WAL written
since the last checkpoint has been replayed and, for crash recovery, until
the end-of-recovery checkpoint has written the result back to disk.  Both
are proportional to the amount of WAL, so time-to-connect after a crash is
bound by WAL volume.

The attached patches let the startup process scan that WAL without
applying the records that modify relation pages.  It replays everything
else eagerly (transaction status, multixacts, smgr and database
operations, ... anything without a block reference, which is cheap and has
no later page read that could trigger it), and records, per page, the LSNs
of the records that touch it, in a dshash table in dynamic shared memory.
Then the server opens.  A page is recovered the first time any process
reads it from disk, and a new auxiliary process recovers the rest in the
background; once it has finished, the index is destroyed and a checkpoint
is requested.

Where replay happens turned out to be the whole design, so that part
first.  On-demand replay runs inside StartReadBuffersImpl(), the common
path of ReadBuffer() and the read streams: a page with pending records is
read synchronously under its BM_IO_IN_PROGRESS flag, replayed, and only
then marked BM_VALID.  Nothing new is added to the buffer manager's
protocol: other backends that want the page wait in WaitIO() as they would
behind a slow disk, and since no backend has been handed the page, none can
hold pointers into it, which is why redo may take an exclusive lock on it
where it would normally need a cleanup lock (the same reasoning as in
ZeroAndLockBuffer()).  Redo is handed the buffer being filled instead of
reading the page again.  A record's other blocks report BLK_DONE, which
redo routines must handle anyway, because after a crash during recovery any
block may already be past the record's LSN; blocks a record initializes
get a scratch local buffer.  A page is replayed exactly once (full-page
images restore unconditionally, so replaying twice would rewind it), and
redo of an indexed page never reads another indexed page, so replays do
not nest.

I went through a series of crashes before arriving there, and they are
probably the most useful part of this mail for anyone touching the buffer
manager: a double content lock, unbounded recursion when redo re-read its
own page through the hook, "incorrect local pin count: 2" because a
cleanup-lock record saw the caller's pin and redo's, ItemIdIsNormal
failures in a parallel worker that had read the page through a read stream
(which bypassed my earlier hook) and kept line pointers under a pin while
another backend replayed a prune, and full-page images rewinding pages that
had been modified after recovery.  All of them came from one thing: the
page was visible before it was current.

Other design points:

- Checkpoints.  A checkpoint promises that everything before its redo point
  is on disk; pending pages would break that, so CreateCheckPoint() refuses
  while the LSNindex exists, unwaited requests are postponed, and a clean
  shutdown waits for the worker.  A request that waits for the checkpoint
  (CHECKPOINT, pg_backup_start(), CREATE/DROP DATABASE) therefore fails
  with "checkpoint request failed" during the window; for a base backup
  that is the right answer, since it would copy pages that are not current
  yet.  Whether such requests should wait for the worker instead is a
  question for this thread (see below).  An earlier version stopped the
  checkpointer altogether, which hung startup in RegisterSyncRequest(): it
  is also the process that absorbs every fsync request.

- Which records are eager.  The rule is "defer only if there is a trigger
  and a gain": a later page read that will find the record, and page I/O
  that is avoided by waiting.  An previous version deferred CLOG, and the
  first commit on a CLOG page that had never been created failed; the quiet
  failure mode would have been committed rows as aborted.

- Relations and databases dropped or truncated later in the WAL forget
  their pending pages.  A truncation is the one eager record that reads
  relation pages (the last FSM and VM page, to clear their tails).  When
  the next record for such a page arrives, the startup process writes the
  page out and drops it from shared buffers before indexing the record, so
  that no resident page has pending records when the server opens.  An
  earlier version instead kept such a page current by replaying every later
  record for it at once; that read those records' heap pages too, which
  then had to be kept current the same way, and one VACUUM truncation of a
  table under 255 MB (one VM page) made the rest of that table's records
  eager, each reading its heap page in the startup process (E below).

- Redo routines check InRecovery (visibilitymap_set() asserts it); it is set
  for the duration of on-demand redo.

- The feature applies to crash recovery under the postmaster only.  Archive
  recovery, standby mode and single-user mode log a message and replay WAL
  as usual.

Numbers.  Measured with a harness that crashes a pgbench run with
pg_ctl -m immediate, recovers the same crashed files twice (stock, and with
fast_crash_recovery on), and compares per-table hashes, an index-path read,
the tpcb balance invariant and pg_amcheck --heapallindexed right after the
server opens, after the worker has drained the index, and after a clean
restart.  No checkpoint runs during the workload.  The machine is a 6-vCPU
VMware VM with a virtual NVMe disk backed by the host, 15 GB RAM; the build
is -O2 without assertions.

A. pgbench scale 100 , with 2.0 GB of WAL, 5.4 M records, 220,823 distinct
pages, shared_buffers 128 MB, warm page cache:

                                                    stock      on-demand
  time to accept connections       15.1 s     2.7 s   (5.5x)
  redo / scan                                 5.8 s     2.7 s
  end-of-recovery checkpoint        9.2 s     0
  first seq scan after ready             1.3 s     2.4 s
  background drain                             -       37.2 s

B. Same scenario, cold page cache (2.7 GB of WAL, 9.0 M records,
270,127 pages):

  time to accept connections       96.1 s    43.0 s   (2.2x)
  redo / scan                                65.7 s    42.2 s
    of which I/O wait                     50.8 s    35.5 s
  end-of-recovery checkpoint      30.4 s     0.8 s
  first seq scan after ready          1.7 s     3.2 s
  background drain                      -       73.3 s

C. pgbench scale 200, shared_buffers 4 GB, 9.9 GB of WAL, 57.6 M records,
648,284 pages, cold cache (the hardest case: a large window with a big
shared_buffers, so stock recovery is mostly CPU):

  time to accept connections      199.4 s   106.4 s   (1.9x)
  redo / scan                               173.3 s   106.4 s
    of which CPU / I/O wait          52.3 / 121.1 s   47.4 / 59.0 s
  end-of-recovery checkpoint       26.1 s     0
  first seq scan after ready          10.4 s    72.6 s
  background drain                         -      506.8 s

D. pgbench scale 100, full_page_writes = off, 1.8 GB of WAL, 18.4 M
records, 323,250 pages, cold cache (the best case: every record needs its
page read):

  time to accept connections      197.2 s    40.0 s   (4.9x)
  redo / scan                               165.7 s    39.9 s
    of which I/O wait                     150.2 s    28.2 s
  end-of-recovery checkpoint       31.6 s     0
  first seq scan after ready            1.5 s     3.9 s
  background drain                           -       45.3 s

E. The truncation case from the design notes: pgbench scale 100 + a
140 MB table that VACUUM truncates three times during the run while clients
update it, 1.5 GB of WAL, shared_buffers 128 MB, files cached, so this
measures the scan's own work.  Before and after the eviction fix, same
workload, different crashes:

                                        kept current   evicted
  scan (time to accept connections)       4.8 s         3.6 s
  startup: relation pages read / written  23,942 / 4,654    8 / 5
  startup: WAL read beyond the window     905 MB        303 MB
  first scan of that table after ready    95 ms        600 ms

These runs show a reliable 2x to 5x reduction in hard downtime across
scenarios A–D. The exact multiple depends on how much I/O write-back
stock recovery is forced to do and also by completely bypassing the
massive end-of-recovery checkpoint, we shift the bottleneck entirely
away from disk writes down to raw scan CPU. This is a deliberate
architectural trade-off of total background work in exchange for
immediate availability. The deferred costs behave exactly as expected:
the first full scan of a hot table post-recovery is 1.5–7x slower due to
on-first-touch replay, and the background drain ultimately spends more
total time re-decoding WAL than stock recovery did. But the primary goal
of drastically shrinking the window where the database cannot accept
connections is achieved.

Two things I learned from measuring that I had wrong before.  With
full_page_writes on, stock crash recovery reads almost no data pages (the
first record for each page after the checkpoint carries the page), so its
critical path is CPU to apply + the write-back, not random reads.  And
the scan can be too fast for its own good: at -O2 it outran the kernel's
readahead window for 8 kB reads and spent 40 of 46 seconds waiting for
WAL, slower than stock recovery on the same files; a posix_fadvise
(WILLNEED) on each segment as it is opened fixed that, and the cold runs
above include it.

I intend to repeat the 10 and 50 GB points on EC2 with gp3 storage, where
the write-back and the evictions cost what they cost in production rather
than what a laptop's virtual disk feels like that minute.

Known limitations and also unknown :), which I would like to discuss:

1. The index is not bounded.  It is roughly 5-15% of the WAL volume and
   lives in DSM, which is /dev/shm, thinking to spill when hits a cap.
2. Also the fast crash recovery worker could be parallel, which makes
   replaying all the pending pages recovered , so the queries won't be slow.
3. Pending pages are read synchronously, one at a time, and look like
   buffer hits to the read stream, which shrinks its look-ahead, need
   to add AIO magic here, trying to figure out how.
4. A checkpoint requested during the window fails ("checkpoint request
   failed") rather than waits: CHECKPOINT, pg_backup_start() and
   CREATE/DROP DATABASE included.  The alternative is to have such a
   request wait for the worker in RequestCheckpoint(), since the caller
   was going to wait for the checkpoint anyway; I have that written, but
   kept the error in v1 so that we can decide here.  One visible
   consequence: with the fast_crash_recovery forced on, 018_wal_optimize can fail,
   because it issues CHECKPOINT right after a crash restart.

0001 is the feature
0002 adds a TAP test (src/test/recovery/t/060) and documentation.

check-world passes with the setting forced on through TEMP_CONFIG,
including the whole recovery suite, whose logs show the worker replaying
pages after every crash.  The one exception is 018_wal_optimize, which
can fail for the reason given in 4 above when the machine is loaded.

--
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/
"Hello, friend?" That's lame. Maybe I should give you a name. But that's a slippery slope.
You're only in my head. We have to remember that. It's actually happened. I'm talking to an imaginary person.

Re: [RFC PATCH v1] On-demand WAL replay: accept connections before crash recovery has applied the WAL

От:
Jakub Wartak <jakub.wartak@enterprisedb.com>
Дата:
On Sat, Oct 10, 2026 at 12:45 PM Srinath Reddy Sadipiralla
 wrote:

Hi Srinath, sorry for posting so late, but here it finally is:

> After a crash, the server cannot accept connections until all WAL written
> since the last checkpoint has been replayed and, for crash recovery, until
> the end-of-recovery checkpoint has written the result back to disk.  Both
> are proportional to the amount of WAL, so time-to-connect after a crash is
> bound by WAL volume.
>
> The attached patches let the startup process scan that WAL without
> applying the records that modify relation pages.  It replays everything
> else eagerly (transaction status, multixacts, smgr and database
> operations, ... anything without a block reference, which is cheap and has
> no later page read that could trigger it), and records, per page, the LSNs
> of the records that touch it, in a dshash table in dynamic shared memory.

It's big feature, probably even controversial and risky, up to the point
You haven't got any responses so far, so I'll play devil advocate to at least
provide some amount of feedback. I have loads of my own doubts, and I've tried
to think and experiment a bit with this concept (more on this later).

Main counterargument is that for folks wishing to have fast crash consistency
restart, it is better today to simply failover to another node rather than wait
for it. So it would only happen for single instances (without HA) and/or PITR.

> - The feature applies to crash recovery under the postmaster only.  Archive
>   recovery, standby mode and single-user mode log a message and replay WAL
>   as usual.

1. That's my big fear, it is not universal. Normally the standby is allowed
to open when consistent recovery state is reached, right? (backup_label.
XLOG_BACKUP_END or pg_control.minRecoveryPoint) and the hot standby got
WAL XLOG_RUNNING_XACTS? (it knows which transactions were in progress on
primary => so we can build MVCC snapshots). So we open with potential lag
still there normally and we allow reads, yet this patch doesn't work in this
conditions. It could take minutes for standby to open for reads (reach
consistent state) and in theory we could minimize that time too. It's not
implemented probably because it is hard/challening?

> Known limitations and also unknown :), which I would like to discuss:
[..]
> 2. Also the fast crash recovery worker could be parallel, which makes
>    replaying all the pending pages recovered , so the queries won't be slow.

2. Yes, fast crash recovery worker could be parallel, which make, but if I
think there's should be some debate at least on how the grand architecural
vision would like like for parallelism in the startup&recovery; there's was
least couple of patches floating: Koichi's parallel recovery, more recent
"WAL pipelined recovery" and now this). I cannot help, but maybe others will
do.

3. Speaking of lazily WAL scanning, if we are doing it (and have plenty of
code from You for this already, thanks :D), why just don't have some filter
to filter WAL records applied to just interesting for us relations? That could
be building block for 'recover single table' for restoring/recovering single
table/schema/DB in PITR scenarios? Today we need to have all of data restored
from let's say 50TB to just to see 1 table (after WAL recovery) from 1 day
ago, which is hardly scalable. So with your's LSNIndexer we could have:

  recovery_target_relation_filter = 'schemaoid.tableoid'
  recovery_target_db_filter = 'dboid'

(the idea is that one would simply restore few segments and not whole cluster,
then StartReadBuffersImpl() -> ReadAndReplayPendingBuffer() looks like almost
ready to do it, filter out anything not need, simply said ignore blocks not in
those two GUCs). This is kind of dragons den, because recovering just base/
/ is happy path, and restoring related-objects seems to be
harder (think of scenarios like FKs, catalog, custom extension's objects,
partitioned tables - e.g. if PITR and catalog has entries to other partitions
and I've just restored *some* what should happen)? *IF* that sounds
interesting then probably patch should be split into 3 sections (lsnindexer-
foundation infrastrcture, impl. of fast-crash, and impl. of
recovery_target_*_filters?). If this should be done, no idea, it's just that
there's additional usecase supporitng this approach/code.

===========================================================================

Probably without answers to the above design-like questions, it doesn't make
sense to fix the below findings, but just as it happened that I've played with
patch, I'm posing them (hopefully they are useful):

4. I've played with the patch and it indeed opened faster, which is cool to
   see for real.

5. As stated code needs to re-read all the WAL (if there's lots of IT , it's
   going to be a lot of IO, we are assuming expected 2x here), but detailed
   measurement and comparisiong of the same crashed cluster indicate that
   something odd is happening:

   fast_crash_recovery=off / startup process:
   while : ; do cat /proc/`pgrep -f "startup recovering"`/io; done
   rchar: 620503048
   wchar: 197158239
   syscr: 75748
   syscw: 24080
   read_bytes: 0
   write_bytes: 197566464
   cancelled_write_bytes: 0

   fast_crash_recovery=on // startup recovering (process "A")
   while : ; do cat /proc/`pgrep -f "startup recovering"`/io; done
   rchar: 620740616
   wchar: 9138
   syscr: 75777
   syscw: 10
   read_bytes: 0
   write_bytes: 8192
   cancelled_write_bytes: 0

   fast_crash_recovery=on // fast recovery worker (process "B")
   while : ; do cat /proc/`pgrep -f "fast recovery worker"`/io; done
   rchar: 1673109504
   wchar: 199418022
   syscr: 204237
   syscw: 24345
   read_bytes: 0
   write_bytes: 332218368
   cancelled_write_bytes: 0

   "Blind" Claude AI analysis of the above:
   Metric         OFF    ON (A + B) Change
   rchar         620.5 MB 2,293.9 MB 3.7×    // not2x?
   wchar         197.2 MB 199.4 MB ≈ same (+1.1%)
   syscr         75,748    280,014     3.7×    // not2x?
   syscw         24,080     24,355     ≈ same
   read_bytes     0        0         none
   write_bytes     197.6 MB 332.2 MB +68% (+134.7 MB)

   So the picture tells that writing has been done by process B (syscw), good.
   However, turning the feature causes way more reading (not just expected 2x,
   but 3.7x). Potentially it's eviction, but I haven't drilled more into this,
   anyway sample stack of fast recovery  pid doing writing looked like this:
    pwrite64(79, ""..., 8192, 0) = 8192
    > /usr/lib/x86_64-linux-gnu/libc.so.6(pwrite+0x17) [0xfa5d7]
    > /usr/pgsql20/bin/postgres(pg_pwritev+0x39) [0x5e7aab]
    > /usr/pgsql20/bin/postgres(FileWriteV+0x188) [0x5ea086]
    > /usr/pgsql20/bin/postgres(mdwritev+0x1c2) [0x627000]
    > /usr/pgsql20/bin/postgres(smgrwritev+0x81) [0x629e02]
    > /usr/pgsql20/bin/postgres(smgrwrite+0x3f) [0x5d59e4]
    > /usr/pgsql20/bin/postgres(FlushBuffer+0x17f) [0x5dc82a]
    > /usr/pgsql20/bin/postgres(GetVictimBuffer+0x13d) [0x5d9a76]
/////// Evictions
    > /usr/pgsql20/bin/postgres(BufferAlloc+0x12b) [0x5d94f8]
    > /usr/pgsql20/bin/postgres(PinBufferForBlock+0x68) [0x5d7d82]
    > /usr/pgsql20/bin/postgres(StartReadBuffersImpl+0x216) [0x5d85e0]
    > /usr/pgsql20/bin/postgres(StartReadBuffer+0x53) [0x5d88c6]
    > /usr/pgsql20/bin/postgres(ReadBuffer_common+0x2bb) [0x5d811f]
    > /usr/pgsql20/bin/postgres(ReadBufferWithoutRelcache+0x82) [0x5d76ab]
    > /usr/pgsql20/bin/postgres(FastRecoveryMain+0x280) [0x5374c2]
    > /usr/pgsql20/bin/postgres(FastRecoveryWorkerMain+0xc6) [0x53762e]
    > /usr/pgsql20/bin/postgres(postmaster_child_launch+0x160) [0x537a42]

6. XLogFileRead()
   +#if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
   +
   +               /*
   +                * Fast crash recovery decodes WAL faster than the
kernel grows its
   +                * readahead window for 8 kB reads, and then waits
at nearly every
   +                * window.  Ask for the whole segment at once; the
kernel reads it in
   +                * the background while we decode what has already arrived.
   +                */
   +               if (LSNIndexIsActive())
   +                       (void) posix_fadvise(fd, 0, 0, POSIX_FADV_WILLNEED);
   +#endif

   This looks like independent change, we could have it independently and
   it doesn't feel that connected to this patch alone. Trouble is potentially
   demonstrating the real benefit of such such alone.


7. With normal crash recovery, I get this (~1.5s checkpoint):
2026-11-19 09:46:13.915 CET [76368] LOG:  checkpoint starting:
end-of-recovery fast wait
2026-11-19 09:46:15.419 CET [76368] LOG:  checkpoint complete:
end-of-recovery fast wait: [..] total=1.506 s; [..]

but with vs fast_crash_recovery=on I get 33s?

2026-11-19 09:46:37.538 CET [76454] LOG:  fast crash recovery complete
2026-11-19 09:46:37.539 CET [76448] LOG:  checkpoint starting: force
2026-11-19 09:47:10.630 CET [76448] LOG:  checkpoint complete: force:
wrote 2067 buffers[..], total=33.092 s; [..]
2026-11-19 09:47:10.635 CET [76448] LOG:  checkpoint starting: wal

Shouldn't the checkpoint after fast crash recovery be also executed as fast as
possible to minimize the chances of subsequent crash forcing the thing to redo
all the work again? (so to save work, before next crash happen; imagine
constantly SIGSEGVing postgres).

8. The patch seems to be lacking bypassing of opening data relation segments
   in lazy scan?  If they are not needed we do we open them and ask for advises
   there? It might pollute causes VFS cache. Below pg_wal fd = 6, and normal
   segment = 921 && 922,  so it shows that we are scanning WAL and opening/
   fadvising a lot of normal segmetns, where it is too early for that:

[pid 373215] openat(AT_FDCWD, "base/5/16389.23334", O_RDWR|O_CLOEXEC) = 921
[pid 373215] fadvise64(921, 0, 8192, POSIX_FADV_WILLNEED) = 0
[pid 373215] pread64(6, "", 8192, 13328384) = 8192 (DELAYED)
[pid 373215] pread64(6, "", 8192, 13336576) = 8192 (DELAYED)
[pid 373215] fadvise64(921, 8192, 8192, POSIX_FADV_WILLNEED) = 0
[pid 373215] pread64(6,  "", 8192, 13344768) = 8192 (DELAYED)
[pid 373215] fadvise64(921, 16384, 8192, POSIX_FADV_WILLNEED) = 0
[pid 373215] pread64(6, "", 8192, 13352960) = 8192 (DELAYED)
[pid 373215] pread64(6, "", 8192, 13361152) = 8192 (DELAYED)
[pid 373215] fadvise64(921, 24576, 8192, POSIX_FADV_WILLNEED) = 0
[pid 373215] pread64(6, """, 8192, 13369344) = 8192 (DELAYED)
[pid 373215] pread64(6, "", 8192, 13377536) = 8192 (DELAYED)
[pid 373215] fadvise64(921, 32768, 8192, POSIX_FADV_WILLNEED) = 0
[pid 373215] pread64(6, "", 8192, 13385728) = 8192 (DELAYED)
[pid 373215] pread64(6, "", 8192, 13393920) = 8192 (DELAYED)
[pid 373215] fadvise64(921, 40960, 8192, POSIX_FADV_WILLNEED) = 0
[pid 373215] pread64(6, "", 8192, 13402112) = 8192 (DELAYED)
[pid 373215] openat(AT_FDCWD, "base/5/16389.23335", O_RDWR|O_CLOEXEC) = 922
[pid 373215] fadvise64(922, 0, 8192, POSIX_FADV_WILLNEED) = 0

sample stack from startup/recovery when this happens is showing
XLogPrefetcherNextBlock() as culprint:

fadvise64(974, 40960, 8192, POSIX_FADV_WILLNEED) = 0
 > /usr/lib/x86_64-linux-gnu/libc.so.6(posix_fadvise64+0xe) [0x11b7be]
 > /usr/pgsql20/bin/postgres(FilePrefetch+0x73) [0x5e9d20]
 > /usr/pgsql20/bin/postgres(mdprefetch+0x108) [0x6266dd]
 > /usr/pgsql20/bin/postgres(smgrprefetch+0x67) [0x629bc1]
 > /usr/pgsql20/bin/postgres(PrefetchSharedBuffer+0xc1) [0x5d72fd]
 > /usr/pgsql20/bin/postgres(XLogPrefetcherNextBlock+0x5cb) [0x1ff0c8] <- bad?
 > /usr/pgsql20/bin/postgres(lrq_prefetch+0x47) [0x1fe50f]
 > /usr/pgsql20/bin/postgres(lrq_complete_lsn+0xe8) [0x1fe6d8]
 > /usr/pgsql20/bin/postgres(XLogPrefetcherReadRecord+0x10a) [0x1ff75d]
 > /usr/pgsql20/bin/postgres(ReadRecord+0xb1) [0x2054fd]
 > /usr/pgsql20/bin/postgres(PerformWalRecovery+0x51e) [0x202d88]
 > /usr/pgsql20/bin/postgres(StartupXLOG+0xa29) [0x1f2000]
 > /usr/pgsql20/bin/postgres(StartupProcessMain+0x109) [0x53fb21]

So perhaps somehow disarm prefetcher during inital fast_crash_recovery scan?
(PerformWalRecovery?) There should be no openat, no pread64, no
fadvise64/posix_fadvise64 for stuff we dont need there.

9. XLogFileClose() has this:
    /*
     * WAL segment files will not be re-read in normal operation, so we advise
     * the OS to release any cached pages.  But do not do so if WAL archiving
     * or streaming is active, because archiver and walsender process could
     * use the cache to read the WAL segment.
     */
    #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
            if (!XLogIsNeeded() && (io_direct_flags & IO_DIRECT_WAL) !=0 && ...)
                    (void) posix_fadvise(openLogFile, 0, 0,
POSIX_FADV_DONTNEED);

    but here with fast_crash_recovery=on we actually *ARE* going to re-read it
    (fixing this may result in even faster recovery, if all WAL would cached
    in VFS cache)

10. How and when are the prepared transactions recovered? Because:

LOG:  redo done at 1/0CE26300 system usage: CPU: user: 0.94 s, system:
0.42 s, elapsed: 1.37 s
LOG:  fast crash recovery: deferred 1556253 records for 123968 pages
(46 MB of index), [..]
LOG:  recovering prepared transaction 690 of epoch 0 from shared memory
LOG:  recovering prepared transaction 694 of epoch 0 from shared memory
[..]
LOG:  recovering prepared transaction 822 of epoch 0 from shared memory
LOG:  database system is ready to accept connections
LOG:  fast recovery worker started
LOG:  fast recovery worker replaying 123968 pending pages
LOG:  fast crash recovery complete

question is, shouldn't it be replayed also from under the fast recovery
worker itself? (Transaction/PREPARE is reference-less, maybe just messsage is
wrong, btw: it got silenced rightfuly down to DEBUG2 recently with c11eb5de01)

-J.


FAQ