Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
От:
Gustavo William <gustavowilliam0805@gmail.com>
Дата:
Вложения:
Hi Jakub,
Thanks for reviewing it. I'm resending the chain of patches here, with 0005 already merged + your suggestions applied.
Here is a summary of what I've fixed:
> I've forgotten to support incremental mode (which means that I ended up issuing posix_fadvise SEQUENTIAL even in incremental mode
1. Fixed. Only issue posix_fadvise SEQUENTIAL for full backups and only issue posix_fadvise WILLNEED for incremental backups.
> there's bug that when m_io_c = 0 you still issue posix_fadvise()s from 2nd callsite (no way to turn it off) and also with e.g. m_io_c = 1 we seem to issue an additional one.
2. Fixed this by only calling prefetch_next_incremental_run when m_io_c > 1. Also moved the call to happen after read_file_data_into_buffer instead of before. Both changes together make the prefetching logic a little more honest regarding I/O queue depth, i.e:
- When m_io_c = 0 or m_io_c = 1: no prefetching at all, queue depth is constantly1 (the synchronous block read).
- When m_io_c > 1 (e.g. 2): prefetch 2 initially > read 1 + prefetch 1 > read 1 + prefetch 1... on average, there will always be 2 I/O simultaneously (assuming fadvise calls are honored).
> I'm not sure f that merging of adjacent blocks shouldn't be also capped up a io_combine_limit GUC
3. Agree that capping is good there. Though I think maintenance_io_concurrency can be reused for this purpose instead? I think a new GUC for this might be too specific. I currently have it implemented using m_io_c. Let me know your thoughts on this if you think otherwise.
> I would rename pf_index to just prefetch_idx, so it would easier to read.
4. Agreed. Fixed.
Thanks,
Gustavo Oliveira
Thanks for reviewing it. I'm resending the chain of patches here, with 0005 already merged + your suggestions applied.
Here is a summary of what I've fixed:
> I've forgotten to support incremental mode (which means that I ended up issuing posix_fadvise SEQUENTIAL even in incremental mode
1. Fixed. Only issue posix_fadvise SEQUENTIAL for full backups and only issue posix_fadvise WILLNEED for incremental backups.
> there's bug that when m_io_c = 0 you still issue posix_fadvise()s from 2nd callsite (no way to turn it off) and also with e.g. m_io_c = 1 we seem to issue an additional one.
2. Fixed this by only calling prefetch_next_incremental_run when m_io_c > 1. Also moved the call to happen after read_file_data_into_buffer instead of before. Both changes together make the prefetching logic a little more honest regarding I/O queue depth, i.e:
- When m_io_c = 0 or m_io_c = 1: no prefetching at all, queue depth is constantly1 (the synchronous block read).
- When m_io_c > 1 (e.g. 2): prefetch 2 initially > read 1 + prefetch 1 > read 1 + prefetch 1... on average, there will always be 2 I/O simultaneously (assuming fadvise calls are honored).
> I'm not sure f that merging of adjacent blocks shouldn't be also capped up a io_combine_limit GUC
3. Agree that capping is good there. Though I think maintenance_io_concurrency can be reused for this purpose instead? I think a new GUC for this might be too specific. I currently have it implemented using m_io_c. Let me know your thoughts on this if you think otherwise.
> I would rename pf_index to just prefetch_idx, so it would easier to read.
4. Agreed. Fixed.
Thanks,
Gustavo Oliveira
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
От:
Jakub Wartak <jakub.wartak@enterprisedb.com>
Дата:
On Tue, Sep 22, 2026 at 9:40 PM Gustavo William
wrote:
>
> Hi Jakub,
>
> Thanks for reviewing it. I'm resending the chain of patches here, with 0005 already merged + your suggestions applied.
[..]
Hi Gustavo,
TLDR; I've verified ~9.4x improvement with 0005-incremental-backup just for
the read path on the NVMe (by avoiding stalled pread()). Good job :)
Testing method:
initdb # summarize_wal=on , maintenance_io_concurrency=2, ...
pgbench -i -s 500 --fillfactor=100 # ~7.5GB base/
pg_basebackup -D /tmp/full -c fast -v
pgbench -N -c 8 -j 8 -t 10000 postgres # -N=updates
psql -c "CHECKPOINT" postgres
sudo /usr/local/bin/drop_fs_cache.sh
time pg_basebackup -i /tmp/full/backup_manifest --target=server-blackhole \
-Xnone -c fast --no-sync --no-verify-checksums
Avg of 3 runs (drop_caches + time pg_basebackup -i)
Without 0005: 7.53s
With 0005: 0.80s (note it's just reading due to blackhole, so no writes!)
I don't have access to SATA drive, but I suspect it would be way better
there.
I was kind of sceptical of the result at first, but explanation of the
phehomena seems to be like this: basebackup_incremnetal.c has
GetFileBackupMethod()->qsort() so it sorts the blocks to be read. Without 0005
patch, preads() of increasing block numbers (offsets) all cause hit page cache
misses, and apparently - at least here on kernel 6.17.x, but earlier for sure
too - this seem to kick off the readahead (because kernel's readahead seems to
be implemented to only kick in by by page-cache misses , it won't even start
if there are hits, kind of makes sense), so pure preads() tend to overread a
lot (like reading N-times more data from a a 1GB segment than we need).
I think the kernel's assumption is that reading sequentially is cheaper than
reading one by one, but depending on density of changes we often - at least
in this cenario, that is in incremetanl basebackup mode - we read much less
than the kernel reads with readahead (simply said: it overreads a lot!).
So using fadvise(FADV_WILLNEED) here caused kind of disarms such aggressive
readahead completley (as it results in 100% hit to pagecaches, so readahead is
not even activated), and this causes way faster incremental times, so fast
that I'm had to actually reserach why and how it happens :o
Issues with the patch
- it seems maintenance_io_concurrency=1 disables prefetch? (it's not queue
depth, it's more of how many to prefetch, so "1" means IMHO pread() +
one posix_fadvise() or am I wrong?)
- pgindent might be needed.
-J.
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
От:
Heikki Linnakangas <hlinnaka@iki.fi>
Дата:
I started to look at these, starting from this patch: > 0004 increases SINK_BUFFER_LENGTH from its current 32 kB. Profiling the > server side shows a huge number of small pread() calls coming from > basebackup_read_file(), which is surprising given that elsewhere in the tree > (backend/storage/buffer/README) we already mention that a 256 kB ring for seq. > scans scans is used because it fits comfortably in L2 cache. On my laptop, > with no SSL, no checksum generation or verification, a hot filesystem cache, > and a client blackhole to eliminate client I/O, a 10 GB backup over loopback > runs at: > 3.1 GB/s with the 32 kB buffer, > 5.1 GB/s at 128 kB, > 5.5 GB/s at 256 kB, > 6.0 GB/s at 1 MB > (those are average of five runs). Cool > The win comes from letting pread() > swallow much larger chunks of each segment in one go: per-core L2 caches are > 1-2 MB even on laptops these days, syscalls have become more expensive since > the Spectre/Meltdown mitigations, and the kernel's default readahead is > already in the 128-512 kB range, so there's little reason to trickle the data > through 32 kB at a time. While we're at it, we should probably allocate the buffer with palloc_aligned(PG_IO_ALIGN_SIZE); a pread() into an aligned buffer should be a little faster. I wonder about this in read_file_data_into_buffer(): > cnt = basebackup_read_file(fd, sink->bbs_buffer, > Min(sink->bbs_buffer_length, length), > offset, readfilename, true); > > /* Can't verify checksums if read length is not a multiple of BLCKSZ. */ > if (!verify_checksum || (cnt % BLCKSZ) != 0) > return cnt; It doesn't seem right to assume that the count must be a multiple of BLCKSZ, especially if we use a larger buffer. Should we do something about that? - Heikki
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
От:
Jakub Wartak <jakub.wartak@enterprisedb.com>
Дата:
Вложения:
On Mon, Oct 5, 2026 at 6:24 PM Heikki Linnakangas wrote:
> I started to look at these, starting from this patch:
Hi Heikki, thanks for taking a look !
> > 0004 increases SINK_BUFFER_LENGTH from its current 32 kB. Profiling the
> > server side shows a huge number of small pread() calls coming from
> > basebackup_read_file(), which is surprising given that elsewhere in the tree
> > (backend/storage/buffer/README) we already mention that a 256 kB ring for seq.
> > scans scans is used because it fits comfortably in L2 cache. On my laptop,
> > with no SSL, no checksum generation or verification, a hot filesystem cache,
> > and a client blackhole to eliminate client I/O, a 10 GB backup over loopback
> > runs at:
> > 3.1 GB/s with the 32 kB buffer,
> > 5.1 GB/s at 128 kB,
> > 5.5 GB/s at 256 kB,
> > 6.0 GB/s at 1 MB
> > (those are average of five runs).
>
> Cool
>
> > The win comes from letting pread()
> > swallow much larger chunks of each segment in one go: per-core L2 caches are
> > 1-2 MB even on laptops these days, syscalls have become more expensive since
> > the Spectre/Meltdown mitigations, and the kernel's default readahead is
> > already in the 128-512 kB range, so there's little reason to trickle the data
> > through 32 kB at a time.
>
> While we're at it, we should probably allocate the buffer with
> palloc_aligned(PG_IO_ALIGN_SIZE); a pread() into an aligned buffer
> should be a little faster.
I've attached patchset with 0004 modified that has this adjustement, but I
haven't quantified the gain for this alone though.
BTW: I've added discussion link and other tags, fixed some minor types in to all
commitmsgs too.
> I wonder about this in read_file_data_into_buffer():
>
> > cnt = basebackup_read_file(fd, sink->bbs_buffer,
> > Min(sink->bbs_buffer_length, length),
> > offset, readfilename, true);
> >
> > /* Can't verify checksums if read length is not a multiple of BLCKSZ. */
> > if (!verify_checksum || (cnt % BLCKSZ) != 0)
> > return cnt;
>
> It doesn't seem right to assume that the count must be a multiple of
> BLCKSZ, especially if we use a larger buffer. Should we do something
> about that?
Your question has opened a whole can of worms on my side :(, but isn't this
code saying two things at once?
- it's only for calculating checksums only for BLCKSZ-sized blocks of
relations (I could imagine some user-placed file, or ENOSPC failure)
- we expect pread/pwrite() atomicity between two concurrent backends (one
backend doing pwrite()/fallocate() extends or truncation while the 2nd
is doing basebackup?)
bbsink_begin_backup(buffer_length=SINK_BUFFER_LENGTH) will set sink->
bbs_buffer_length to that SINK.. value and even there verify too:
Assert((sink->bbs_buffer_length % BLCKSZ) == 0);
sendFile() has the same (+ there's more occurences of this)
/*
* Checksums are verified in multiples of BLCKSZ, so the buffer length
* should be a multiple of the block size as well.
*/
Assert((sink->bbs_buffer_length % BLCKSZ) == 0);
further more sendFile() has this too above the "if (cnt < BLCKSZ)"
/*
* If we get a partial read, that must mean that the relation is
* being truncated. Ultimately, it should be truncated to a
* multiple of BLCKSZ, since this path should only be reached for
* relation files, but we might transiently observe an
* intermediate value.
*
* It should be fine to treat this just as if the entire block had
* been truncated away - i.e. fill this and all later blocks with
* zeroes. WAL replay will fix things up.
*/
and below that, there is ereport() that says just checksums couldn't be
verified. I mean in 0004 we are just growing and so it assumes we shouldn't
get any problems with this code. It looks like it is written while expecting
proper pread()/pwrite() atomicity when extending for up to 32kb, or am I
missing something?
On 6.17.x and 6.14.x x86_64 ext4 I've got no issues with such atomicity for
buffered preads while __appending__ stuff (using pwrite() to extend) and pread()
got correct stuff or premature EOF - that was for both 8kB and 256kB. Of
course I'm able to get torn-pages (only on 6.17.x - sic!) while doing buffered
OVERWRITES (so yea, 8kb split into 4kB + old 4KB -- checksum wouldn't match]).
Anyway as this topic touches the lack of pread()/pwrite() atomicity, but:
a) for torn-pages we are already protected there (see nearby comment for
reread_cnt , so we re-read)
b) for truncation too we are protected too
c) and it seems there is no issue for extending/appending
I've done some extensive pgbench read-write tests with pg_basebackup back then
and that such stuff didn't happen, perhaps buildfarm would tell more(?) My
only worry is that there could be some silent kernel change (in the past)
that would allow too see incompletle data by pread() for pwrite(), but if
that is not happening on 8kB/32kB (which is already over page-size), why
would that be happening for higher values?
BTW: previous such discussions [1][2][3][4] all seem to point that lack of
similar atomicity guaranteees or seem to be kernel bugs or some bizzare platform
(see e.g. "pwrite/pread is non-atomic" in [2]) or at least deficit in fs
(while XFS being always safer [5]).
Still, even if if we just read miss some stale data due to pread() woes (and
skip checksums there) the data should be recoverable from WAL.
-J.
[1] - https://www.postgresql.org/message-id/20220116071210.GA735692%40rfd.leadboat.com
[2] - https://www.postgresql.org/message-id/20220116210241.GC756210%40rfd.leadboat.com
[3] - https://www.postgresql.org/message-id/CA%2BhUKGJ98%3DMOjDCnMAC5gSpkzrrey%3DO%2BaEQJ1OY03C%3DcVtiwkA%40mail.gmail.com
[4] - https://www.postgresql.org/message-id/CA%2BhUKG%2B19bZKidSiWmMsDmgUVe%3D_rr0m57LfR%2BnAbWprVDd_cw%40mail.gmail.com
[5] - https://www.postgresql.org/message-id/CA%2BhUKGJsT8G_YyjUzMZaJTWyua6PbwC3TAUMv_kDS0F0vzr2Pw%40mail.gmail.com
- after "As for ext4, we've detected and debugged clues.."
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
От:
Heikki Linnakangas <hlinnaka@iki.fi>
Дата:
On 06/10/2026 16:10, Jakub Wartak wrote: > further more sendFile() has this too above the "if (cnt < BLCKSZ)" > /* > * If we get a partial read, that must mean that the relation is > * being truncated. Ultimately, it should be truncated to a > * multiple of BLCKSZ, since this path should only be reached for > * relation files, but we might transiently observe an > * intermediate value. > * > * It should be fine to treat this just as if the entire block had > * been truncated away - i.e. fill this and all later blocks with > * zeroes. WAL replay will fix things up. > */ > > and below that, there is ereport() that says just checksums couldn't be > verified. I mean in 0004 we are just growing and so it assumes we shouldn't > get any problems with this code. It looks like it is written while expecting > proper pread()/pwrite() atomicity when extending for up to 32kb, or am I > missing something? I think that comment is wrong. A short read is possible for other reasons than a truncated file, e.g. if the read is interrupted by a signal. In the past, we've made that same assumption that you never get a short read on a BLCKSZ-sized read in other places too, but it was always questionable. Thomas Munro fixed it for smgrread() in commit 4908c58720. I think we should now fix that in read_file_data_into_buffer(), too. Make it retry, so that it never returns fewer bytes than requested except for EOF. With a larger buffer, a short read becomes more likely. - Heikki
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
On Tue, Oct 6, 2026 at 5:42 PM Heikki Linnakangas wrote: > I think that comment is wrong. A short read is possible for other > reasons than a truncated file, e.g. if the read is interrupted by a > signal. In the past, we've made that same assumption that you never get > a short read on a BLCKSZ-sized read in other places too, but it was > always questionable. Thomas Munro fixed it for smgrread() in commit > 4908c58720. > > I think we should now fix that in read_file_data_into_buffer(), too. > Make it retry, so that it never returns fewer bytes than requested > except for EOF. With a larger buffer, a short read becomes more likely. OK, I see, thanks, so I've tried this in the attached 0004. 0001..0004 without asserts, still give ~1.67x on hot DB fully in VFS cache: pg_basebackup -c fast -v -h 127.0.0.1 --target=client-blackhole -Xnone \ -c fast --no-sync --no-verify-checksums --manifest-checksums=NONE \ 2>&1 | grep MB/s (client-blackhole still transfers to CLI, so it's receieving just ignoring write path at all) 256kb (as within 0004): pg_basebackup: base backup completed (avg 5503.2 MB/s) pg_basebackup: base backup completed (avg 5331.5 MB/s) pg_basebackup: base backup completed (avg 5205.6 MB/s) 32kB: pg_basebackup: base backup completed (avg 3110.2 MB/s) pg_basebackup: base backup completed (avg 3307.3 MB/s) pg_basebackup: base backup completed (avg 3191.2 MB/s) I've tried a couple of other integrity tests too for this new retry code: 1. high concurrency pgbench with loop of parallel pg_basebackup + pg_verifybackup for couple of minutes (to see if that backing up files being appended works OK). It went OK. 2. I've tried failure injection on 3rd invocation of pread of certain file: strace -ff -p $POSTMASTERPID -P $PGDATA/base/1/1255 \ -e trace=pread64 -k -e inject=pread64:error=EINTR:when=3 and in first version of my patch I've got: WARNING: aborting backup due to backend exiting before pg_backup_stop .. ERROR: could not read file "./base/1/1255": Interrupted system call strace got it exactly there: pread64(14, ..., 262144, 524288) = -1 EINTR (Interrupted system call) (INJECTED) > /usr/lib/x86_64-linux-gnu/libc.so.6(pread64+0x17) [0xfa577] > .../bin/postgres(basebackup_read_file+0x61) [0x23b9a1] > .../bin/postgres(read_file_data_into_buffer+0x4d) [0x23bcfd] so right, today even master seems to be vulnerable to this I think. Anyway, I've added to 0004 the EINTR guard (FileReadV() had goto for this) and I have retested this using the EINTR injection for way more pgdata files at specifc blocks and then checked if the resulting DB was fine: rm -rf /tmp/full1 # ~10GB DB pg_basebackup -c fast -v -h 127.0.0.1 -D /tmp/full1 -c fast # strace on some relations with "when=1..2+1" has reported INJECTED # messages (causing restart of the syscall in code) pg_verifybackup /tmp/full1 and got "backup successfully verified" 3. With SIMULATE_SHORT_READ it also works OK. -J.
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
От:
Heikki Linnakangas <hlinnaka@iki.fi>
Дата:
On 07/10/2026 12:55, Jakub Wartak wrote: > On Tue, Oct 6, 2026 at 5:42 PM Heikki Linnakangas wrote: > >> I think that comment is wrong. A short read is possible for other >> reasons than a truncated file, e.g. if the read is interrupted by a >> signal. In the past, we've made that same assumption that you never get >> a short read on a BLCKSZ-sized read in other places too, but it was >> always questionable. Thomas Munro fixed it for smgrread() in commit >> 4908c58720. >> >> I think we should now fix that in read_file_data_into_buffer(), too. >> Make it retry, so that it never returns fewer bytes than requested >> except for EOF. With a larger buffer, a short read becomes more likely. > > OK, I see, thanks, so I've tried this in the attached 0004. Ok, looks good as far as it goes. But looking at basebackup_read_file(), I think there's a race condition with partial_read_ok == false. This could happen: 0. read_file_data_into_buffer() observes a checksum failure thanks to a torn write, and retries reading a single BLCKSZ block. 1. basebackup_read_file() is called with partial_read_ok == false, nbytes=BLCKSZ. 2. It reads the first 4096 bytes of the block. (e.g. because of SIMULATE_SHORT_READ, or EINTR) 3. The file is truncated 4. basebackup_read_file() makes another pg_pread() call to read the rest of the block. It returns 0, because the file was truncated 5. basebackup_read_file() throws a partial read error: "could not read file \"%s\": read %zu of %zu". If the truncation happened earlier, before the first read, or later, after the whole block has been read, you don't get the error. - Heikki
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
От:
Gustavo William <gustavowilliam0805@gmail.com>
Дата:
Вложения:
Hi,
Apologies for the delay.
TL;DR:
- The speedup from 0005 depends a lot on how much the incremental backup has changed
since the last one: ~9.8x at 14% delta, ~3.7x at 33%, ~1.2x at 57%. That explains the
difference between Jakub's 9.4x speedup and the ~1.5x I first saw.
- Most of the gain comes from avoiding the kernel's own readahead on scattered blocks
(it was doing more than double the I/O needed), not from concurrency.
- Merging adjacent blocks matters. Without it, 0005 is slower than master on backups
with a high delta.
- maintenance_io_concurrency (m_io_c) beyond 2 only helps a little, and only when
there are many adjacent blocks. m_io_c = 1 is still worse though.
- Code changes in this version: prefetch is enabled again for m_io_c = 1, the merge
limit is now io_combine_limit, there is a new limit on how far ahead we prefetch,
and the prefetch state moved into a new IncrPrefetch struct.
> I've verified ~9.4x improvement with 0005-incremental-backup
I was confused by the big difference between our results, since I had initially seen
only ~1.5x. After replicating your tests I found the reason: the speedup varies a lot
depending on how much delta your incremental backup has.
I followed the same method you described:
initdb # summarize_wal=on, maintenance_io_concurrency=2, ...
pgbench -i -s 500 --fillfactor=100 -d dbname=test # ~7.5GB
pg_basebackup -D /pg-test/full -c fast
# ~14% of data change
psql test -c "CHECKPOINT"
./measure pg_basebackup --incremental /pg-test/full/backup_manifest --wal-method none --target server-blackhole --checkpoint fast
# "measure" is a simple script that runs the command 3 times, dropping caches in between
That gives an incremental backup of ~1.1G (~14% delta). To increase the delta I then ran
pgbench + checkpoint a few more times between backups. Results (in seconds):
delta change without 0005 with 0005 speedup
------------- ------------ --------- -------
~14% (~1.1G) 42.48 4.31 ~9.8x
~33% (~2.5G) 27.56 7.49 ~3.7x
~57% (~4.3G) 15.60 13.13 ~1.2x
So the higher the delta, the smaller the gain from 0005. I think this ties back to the
kernel behavior you observed.
Reading scattered blocks the way pg_basebackup does today seems to confuse the kernel.
After a single block read, the kernel may readahead the following blocks, expecting a
sequential pattern. With scattered delta blocks that never happens, so the prefetched
data is wasted. I actually checked this on /proc/<pid>/io during a backup of ~14% delta:
Without 0005
```
rchar: 1139995913 # bytes requested by the process (1.1GB)
syscr: 138285
read_bytes: 2557988864 # bytes actually read from storage (2.5GB)
```
With 0005
```
rchar: 1139966637 # bytes requested by the process (1.1GB)
syscr: 138279
read_bytes: 1143574528 # bytes actually read from storage (1.1GB)
```
So, without 0005 the kernel does more than double the I/O we need. 0005 helps with
concurrency, but its major improvement is avoiding this misguided readahead.
This explains the results above. With 14% delta from pgbench, most blocks are
scattered, so 0005 avoids all that double I/O and gets a huge speedup. At 57% the delta
blocks are much more adjacent, so the kernel's own readahead gets a good part of its
guesses right and 0005 has less to improve on.
A few other questions I tried to answer in this round:
1. Does increasing maintenance_io_concurrency make a big difference?
Not really. There's some gain up to a point, but it's small. This also reinforces that
most of the gain of 0005 comes from avoiding the kernel's double I/O, not from
concurrency itself. Below are some results of backup with 14% delta (in seconds):
with m_io_c = 2: 4.45
with m_io_c = 16: 4.14
with m_io_c = 32: 4.07
with m_io_c = 64: 4.18
This made me wonder if we should stop making the prefetch window tied to m_io_c and
instead just use a small fixed number like 2. But a higher m_io_c does give a
modest gain on backups with a higher delta (more adjacent blocks). With ~57% delta:
with m_io_c = 2: 13.13
with m_io_c = 16: 10.28
2. Does maintenance_io_concurrency = 1 give any gain?
Yes, but less than 2. With ~14% delta (scattered blocks), in seconds:
with m_io_c = 2: 4.31
with m_io_c = 1: 6.94
3. Is merging adjacent blocks really helping?
At some point I considered dropping the merge-of-adjacent-blocks piece, so I decided
to measure it on a 57% delta backup with m_io_c = 16 (results in seconds):
without 0005: 15.60
0005 with merge: 10.28
0005 without merge: 20.41
It helps a lot. Without it, 0005 makes incremental backups with a high delta
slower than not having 0005 at all (15.60 above).
My environment:
AWS EC2 c3.8xlarge; EBS vol 22000 IOPS, 1500MB/s max throughput;
Apologies for the delay.
TL;DR:
- The speedup from 0005 depends a lot on how much the incremental backup has changed
since the last one: ~9.8x at 14% delta, ~3.7x at 33%, ~1.2x at 57%. That explains the
difference between Jakub's 9.4x speedup and the ~1.5x I first saw.
- Most of the gain comes from avoiding the kernel's own readahead on scattered blocks
(it was doing more than double the I/O needed), not from concurrency.
- Merging adjacent blocks matters. Without it, 0005 is slower than master on backups
with a high delta.
- maintenance_io_concurrency (m_io_c) beyond 2 only helps a little, and only when
there are many adjacent blocks. m_io_c = 1 is still worse though.
- Code changes in this version: prefetch is enabled again for m_io_c = 1, the merge
limit is now io_combine_limit, there is a new limit on how far ahead we prefetch,
and the prefetch state moved into a new IncrPrefetch struct.
> I've verified ~9.4x improvement with 0005-incremental-backup
I was confused by the big difference between our results, since I had initially seen
only ~1.5x. After replicating your tests I found the reason: the speedup varies a lot
depending on how much delta your incremental backup has.
I followed the same method you described:
initdb # summarize_wal=on, maintenance_io_concurrency=2, ...
pgbench -i -s 500 --fillfactor=100 -d dbname=test # ~7.5GB
pg_basebackup -D /pg-test/full -c fast
# ~14% of data change
psql test -c "CHECKPOINT"
./measure pg_basebackup --incremental /pg-test/full/backup_manifest --wal-method none --target server-blackhole --checkpoint fast
# "measure" is a simple script that runs the command 3 times, dropping caches in between
That gives an incremental backup of ~1.1G (~14% delta). To increase the delta I then ran
pgbench + checkpoint a few more times between backups. Results (in seconds):
delta change without 0005 with 0005 speedup
------------- ------------ --------- -------
~14% (~1.1G) 42.48 4.31 ~9.8x
~33% (~2.5G) 27.56 7.49 ~3.7x
~57% (~4.3G) 15.60 13.13 ~1.2x
So the higher the delta, the smaller the gain from 0005. I think this ties back to the
kernel behavior you observed.
Reading scattered blocks the way pg_basebackup does today seems to confuse the kernel.
After a single block read, the kernel may readahead the following blocks, expecting a
sequential pattern. With scattered delta blocks that never happens, so the prefetched
data is wasted. I actually checked this on /proc/<pid>/io during a backup of ~14% delta:
Without 0005
```
rchar: 1139995913 # bytes requested by the process (1.1GB)
syscr: 138285
read_bytes: 2557988864 # bytes actually read from storage (2.5GB)
```
With 0005
```
rchar: 1139966637 # bytes requested by the process (1.1GB)
syscr: 138279
read_bytes: 1143574528 # bytes actually read from storage (1.1GB)
```
So, without 0005 the kernel does more than double the I/O we need. 0005 helps with
concurrency, but its major improvement is avoiding this misguided readahead.
This explains the results above. With 14% delta from pgbench, most blocks are
scattered, so 0005 avoids all that double I/O and gets a huge speedup. At 57% the delta
blocks are much more adjacent, so the kernel's own readahead gets a good part of its
guesses right and 0005 has less to improve on.
A few other questions I tried to answer in this round:
1. Does increasing maintenance_io_concurrency make a big difference?
Not really. There's some gain up to a point, but it's small. This also reinforces that
most of the gain of 0005 comes from avoiding the kernel's double I/O, not from
concurrency itself. Below are some results of backup with 14% delta (in seconds):
with m_io_c = 2: 4.45
with m_io_c = 16: 4.14
with m_io_c = 32: 4.07
with m_io_c = 64: 4.18
This made me wonder if we should stop making the prefetch window tied to m_io_c and
instead just use a small fixed number like 2. But a higher m_io_c does give a
modest gain on backups with a higher delta (more adjacent blocks). With ~57% delta:
with m_io_c = 2: 13.13
with m_io_c = 16: 10.28
2. Does maintenance_io_concurrency = 1 give any gain?
Yes, but less than 2. With ~14% delta (scattered blocks), in seconds:
with m_io_c = 2: 4.31
with m_io_c = 1: 6.94
3. Is merging adjacent blocks really helping?
At some point I considered dropping the merge-of-adjacent-blocks piece, so I decided
to measure it on a 57% delta backup with m_io_c = 16 (results in seconds):
without 0005: 15.60
0005 with merge: 10.28
0005 without merge: 20.41
It helps a lot. Without it, 0005 makes incremental backups with a high delta
slower than not having 0005 at all (15.60 above).
My environment:
AWS EC2 c3.8xlarge; EBS vol 22000 IOPS, 1500MB/s max throughput;
RHEL 9.8; Kernel 5.14.0-687.41.1.el9_8.x86_64
Now regarding the code changes of this last iteration:
1. > it seems maintenance_io_concurrency=1 disables prefetch?
Yes, I had disabled it, thinking it wouldn't help. After the tests above I enabled
it again.
2. We had previously agreed on a limit for how many blocks can be merged into a single
fadvise. I was using maintenance_io_concurrency for that, but I thought
io_combine_limit might be a better fit according to its description. Do you think
that makes sense?
3. The previous version had no limit on how far ahead, in blocks, we could prefetch.
Each iteration runs one prefetch_next_incremental_run(), which can cover many
blocks when they're adjacent. With lots of adjacent blocks we could get far ahead of
the block being read, filling the page cache with pages that won't be needed any
time soon and might even be evicted before they are read.
Based on that, I added a distance limit, in blocks, of
maintenance_io_concurrency * io_combine_limit. When there are many adjacent blocks,
that keeps us at most maintenance_io_concurrency fadvise calls ahead of the current
block.
4. I added a new struct named IncrPrefetch to the code to hold some parameters of the
prefetch mechanism. I thought sendFile() was getting a lot of new variables and
becoming harder to read. I hope that makes sense.
BTW thank you very much for helping with the reviews, I appreciate it.
Regards,
Gustavo Oliveira
Now regarding the code changes of this last iteration:
1. > it seems maintenance_io_concurrency=1 disables prefetch?
Yes, I had disabled it, thinking it wouldn't help. After the tests above I enabled
it again.
2. We had previously agreed on a limit for how many blocks can be merged into a single
fadvise. I was using maintenance_io_concurrency for that, but I thought
io_combine_limit might be a better fit according to its description. Do you think
that makes sense?
3. The previous version had no limit on how far ahead, in blocks, we could prefetch.
Each iteration runs one prefetch_next_incremental_run(), which can cover many
blocks when they're adjacent. With lots of adjacent blocks we could get far ahead of
the block being read, filling the page cache with pages that won't be needed any
time soon and might even be evicted before they are read.
Based on that, I added a distance limit, in blocks, of
maintenance_io_concurrency * io_combine_limit. When there are many adjacent blocks,
that keeps us at most maintenance_io_concurrency fadvise calls ahead of the current
block.
4. I added a new struct named IncrPrefetch to the code to hold some parameters of the
prefetch mechanism. I thought sendFile() was getting a lot of new variables and
becoming harder to read. I hope that makes sense.
BTW thank you very much for helping with the reviews, I appreciate it.
Regards,
Gustavo Oliveira
Em qui., 15 de out. de 2026 às 09:08, Heikki Linnakangas <hlinnaka@iki.fi> escreveu:
On 07/10/2026 12:55, Jakub Wartak wrote:
> On Tue, Oct 6, 2026 at 5:42 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
>
>> I think that comment is wrong. A short read is possible for other
>> reasons than a truncated file, e.g. if the read is interrupted by a
>> signal. In the past, we've made that same assumption that you never get
>> a short read on a BLCKSZ-sized read in other places too, but it was
>> always questionable. Thomas Munro fixed it for smgrread() in commit
>> 4908c58720.
>>
>> I think we should now fix that in read_file_data_into_buffer(), too.
>> Make it retry, so that it never returns fewer bytes than requested
>> except for EOF. With a larger buffer, a short read becomes more likely.
>
> OK, I see, thanks, so I've tried this in the attached 0004.
Ok, looks good as far as it goes. But looking at basebackup_read_file(),
I think there's a race condition with partial_read_ok == false. This
could happen:
0. read_file_data_into_buffer() observes a checksum failure thanks to a
torn write, and retries reading a single BLCKSZ block.
1. basebackup_read_file() is called with partial_read_ok == false,
nbytes=BLCKSZ.
2. It reads the first 4096 bytes of the block. (e.g. because of
SIMULATE_SHORT_READ, or EINTR)
3. The file is truncated
4. basebackup_read_file() makes another pg_pread() call to read the rest
of the block. It returns 0, because the file was truncated
5. basebackup_read_file() throws a partial read error: "could not read
file \"%s\": read %zu of %zu".
If the truncation happened earlier, before the first read, or later,
after the whole block has been read, you don't get the error.
- Heikki
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
On Thu, Oct 15, 2026 at 2:09 PM Heikki Linnakangas wrote:
>
> On 07/10/2026 12:55, Jakub Wartak wrote:
> > On Tue, Oct 6, 2026 at 5:42 PM Heikki Linnakangas wrote:
> >
> >> I think that comment is wrong. A short read is possible for other
> >> reasons than a truncated file, e.g. if the read is interrupted by a
> >> signal. In the past, we've made that same assumption that you never get
> >> a short read on a BLCKSZ-sized read in other places too, but it was
> >> always questionable. Thomas Munro fixed it for smgrread() in commit
> >> 4908c58720.
> >>
> >> I think we should now fix that in read_file_data_into_buffer(), too.
> >> Make it retry, so that it never returns fewer bytes than requested
> >> except for EOF. With a larger buffer, a short read becomes more likely.
> >
> > OK, I see, thanks, so I've tried this in the attached 0004.
>
> Ok, looks good as far as it goes. But looking at basebackup_read_file(),
> I think there's a race condition with partial_read_ok == false. This
> could happen:
>
> 0. read_file_data_into_buffer() observes a checksum failure thanks to a
> torn write, and retries reading a single BLCKSZ block.
> 1. basebackup_read_file() is called with partial_read_ok == false,
> nbytes=BLCKSZ.
> 2. It reads the first 4096 bytes of the block. (e.g. because of
> SIMULATE_SHORT_READ, or EINTR)
> 3. The file is truncated
> 4. basebackup_read_file() makes another pg_pread() call to read the rest
> of the block. It returns 0, because the file was truncated
> 5. basebackup_read_file() throws a partial read error: "could not read
> file \"%s\": read %zu of %zu".
>
> If the truncation happened earlier, before the first read, or later,
> after the whole block has been read, you don't get the error.
Hi Heikki,
So the 0001 is the previous one, and and 0002 is about fixing that
SIMULATE_SHORT_READ/EINTR situation above (separate just to ease the review).
I suspect we should never assume that basebackup_read_file() with
partial_read_ok==false is fine, so it was my starting point, so:
- reread_cnt = basebackup_read_file(..., partial_read_ok=false)
- if (reread_cnt == 0)
+ reread_cnt = basebackup_read_file(..., partial_read_ok=true)
+ if (reread_cnt != BLCKSZ)
and that was it's only user, so it's gone now.
But there's more and it deserves some explanation: when running above
WIP-fix to that reread race condition and simulating EINTR/short reads
and backing up things things in parallel all the time and having this
setup:
1. #define SIMULATE_SHORT_READ
2. INSERT INTO t SELECT generate_series(1, 10000); \watch 0.0001
3. TRUNCATE t; \watch 0.0001 -- it kept on rotating relfilenode a lot
4. optional: strace in parallel (even more EINTR and stuff)
5. while : ; do rm -rf /tmp/full1 && install/bin/pg_basebackup -c fast \
-h 127.0.0.1 -D /tmp/full1 && install/bin/pg_verifybackup /tmp/full1; \
done
I've started receving haywire stuff like:
WARNING: could not verify checksum in file "./base/5/157555", block 32:
read buffer size 167936 and page size 8192 differ
DETAIL: bytes_done=262144 filestat.st_size=3629056 fstat_rc=0 fstat_size=0
Please notice the 2nd fstat report size of 0 (truncation) vs 3629056, so I
had to fix that further, so that's why I landed with is_relfile and inside
read_file_data_into_buffer() there's now:
if (is_relfile && cnt < requested && (cnt % BLCKSZ) != 0)
hopefully comment explains the rationale.
The errdetail() is still there and I would like to keep it , but maybe
some better form or shape or maybe better leave it as separate DEBUG1
to still being able to troubleshoot this code (it's hard).
A thorough review would be highly advisable, as this is like walking on thin
ice and a lot of smart people complained about this code in the past.
-J.
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
On 29/10/2026 16:16, Jakub Wartak wrote: > On Thu, Oct 15, 2026 at 2:09 PM Heikki Linnakangas wrote: >> Ok, looks good as far as it goes. But looking at basebackup_read_file(), >> I think there's a race condition with partial_read_ok == false. This >> could happen: >> >> 0. read_file_data_into_buffer() observes a checksum failure thanks to a >> torn write, and retries reading a single BLCKSZ block. >> 1. basebackup_read_file() is called with partial_read_ok == false, >> nbytes=BLCKSZ. >> 2. It reads the first 4096 bytes of the block. (e.g. because of >> SIMULATE_SHORT_READ, or EINTR) >> 3. The file is truncated >> 4. basebackup_read_file() makes another pg_pread() call to read the rest >> of the block. It returns 0, because the file was truncated >> 5. basebackup_read_file() throws a partial read error: "could not read >> file \"%s\": read %zu of %zu". >> >> If the truncation happened earlier, before the first read, or later, >> after the whole block has been read, you don't get the error. > > Hi Heikki, > > So the 0001 is the previous one, and and 0002 is about fixing that > SIMULATE_SHORT_READ/EINTR situation above (separate just to ease the review). > I suspect we should never assume that basebackup_read_file() with > partial_read_ok==false is fine, so it was my starting point, so: > - reread_cnt = basebackup_read_file(..., partial_read_ok=false) > - if (reread_cnt == 0) > + reread_cnt = basebackup_read_file(..., partial_read_ok=true) > + if (reread_cnt != BLCKSZ) > and that was it's only user, so it's gone now. > > But there's more and it deserves some explanation: when running above > WIP-fix to that reread race condition and simulating EINTR/short reads > and backing up things things in parallel all the time and having this > setup: > > 1. #define SIMULATE_SHORT_READ > 2. INSERT INTO t SELECT generate_series(1, 10000); \watch 0.0001 > 3. TRUNCATE t; \watch 0.0001 -- it kept on rotating relfilenode a lot > 4. optional: strace in parallel (even more EINTR and stuff) > 5. while : ; do rm -rf /tmp/full1 && install/bin/pg_basebackup -c fast \ > -h 127.0.0.1 -D /tmp/full1 && install/bin/pg_verifybackup /tmp/full1; \ > done > > I've started receving haywire stuff like: > WARNING: could not verify checksum in file "./base/5/157555", block 32: > read buffer size 167936 and page size 8192 differ > DETAIL: bytes_done=262144 filestat.st_size=3629056 fstat_rc=0 fstat_size=0 > > Please notice the 2nd fstat report size of 0 (truncation) vs 3629056, so I > had to fix that further, so that's why I landed with is_relfile and inside > read_file_data_into_buffer() there's now: > if (is_relfile && cnt < requested && (cnt % BLCKSZ) != 0) > hopefully comment explains the rationale. > > The errdetail() is still there and I would like to keep it , but maybe > some better form or shape or maybe better leave it as separate DEBUG1 > to still being able to troubleshoot this code (it's hard). > > A thorough review would be highly advisable, as this is like walking on thin > ice and a lot of smart people complained about this code in the past. These functions are really complex, they work quite differently for relation files and others. The responsibility for verifying the checksums is supposedly in read_file_data_into_buffer() -- but the caller still needs to worry about page boundaries and short reads and warn about checksum failure on short read. That's not new with your patches, but it's getting worse. I think this all becomes more clear if we separate the code to handle relation files and other files. See attached. The first patch splits sendFile() into two: sendRelFile() for relation files, and sendFile() for all other files. That duplicates some code, but makes it more readable IMHO. sendFile() can call basebackup_read_file() directly, and read_[rel]file_data_into_buffer() is only be used for relation files, which makes the 'is_relfile' argument unnecessary. The second patch changes read_relfile_data_into_buffer() to always work with full BLCKSZ blocks. That moves the handling of partial reads fully inside read_relfile_data_into_buffer(), making the caller simpler. These two patches are on top of your two patches, because I developed them that way, but it would probably make sense to squash them a little. - Heikki
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
От:
Jakub Wartak <jakub.wartak@enterprisedb.com>
Дата:
Вложения:
On Wed, Nov 4, 2026 at 11:45 PM Heikki Linnakangas wrote:
>
> On 29/10/2026 16:16, Jakub Wartak wrote:
> > On Thu, Oct 15, 2026 at 2:09 PM Heikki Linnakangas wrote:
> >> Ok, looks good as far as it goes. But looking at basebackup_read_file(),
> >> I think there's a race condition with partial_read_ok == false. This
> >> could happen:
> >>
> >> 0. read_file_data_into_buffer() observes a checksum failure thanks to a
> >> torn write, and retries reading a single BLCKSZ block.
> >> 1. basebackup_read_file() is called with partial_read_ok == false,
> >> nbytes=BLCKSZ.
> >> 2. It reads the first 4096 bytes of the block. (e.g. because of
> >> SIMULATE_SHORT_READ, or EINTR)
> >> 3. The file is truncated
> >> 4. basebackup_read_file() makes another pg_pread() call to read the rest
> >> of the block. It returns 0, because the file was truncated
> >> 5. basebackup_read_file() throws a partial read error: "could not read
> >> file \"%s\": read %zu of %zu".
> >>
> >> If the truncation happened earlier, before the first read, or later,
> >> after the whole block has been read, you don't get the error.
> >
> > Hi Heikki,
> >
> > So the 0001 is the previous one, and and 0002 is about fixing that
> > SIMULATE_SHORT_READ/EINTR situation above (separate just to ease the review).
> > I suspect we should never assume that basebackup_read_file() with
> > partial_read_ok==false is fine, so it was my starting point, so:
> > - reread_cnt = basebackup_read_file(..., partial_read_ok=false)
> > - if (reread_cnt == 0)
> > + reread_cnt = basebackup_read_file(..., partial_read_ok=true)
> > + if (reread_cnt != BLCKSZ)
> > and that was it's only user, so it's gone now.
> >
> > But there's more and it deserves some explanation: when running above
> > WIP-fix to that reread race condition and simulating EINTR/short reads
> > and backing up things things in parallel all the time and having this
> > setup:
> >
> > 1. #define SIMULATE_SHORT_READ
> > 2. INSERT INTO t SELECT generate_series(1, 10000); \watch 0.0001
> > 3. TRUNCATE t; \watch 0.0001 -- it kept on rotating relfilenode a lot
> > 4. optional: strace in parallel (even more EINTR and stuff)
> > 5. while : ; do rm -rf /tmp/full1 && install/bin/pg_basebackup -c fast \
> > -h 127.0.0.1 -D /tmp/full1 && install/bin/pg_verifybackup /tmp/full1; \
> > done
> >
> > I've started receving haywire stuff like:
> > WARNING: could not verify checksum in file "./base/5/157555", block 32:
> > read buffer size 167936 and page size 8192 differ
> > DETAIL: bytes_done=262144 filestat.st_size=3629056 fstat_rc=0 fstat_size=0
> >
> > Please notice the 2nd fstat report size of 0 (truncation) vs 3629056, so I
> > had to fix that further, so that's why I landed with is_relfile and inside
> > read_file_data_into_buffer() there's now:
> > if (is_relfile && cnt < requested && (cnt % BLCKSZ) != 0)
> > hopefully comment explains the rationale.
> >
> > The errdetail() is still there and I would like to keep it , but maybe
> > some better form or shape or maybe better leave it as separate DEBUG1
> > to still being able to troubleshoot this code (it's hard).
> >
> > A thorough review would be highly advisable, as this is like walking on thin
> > ice and a lot of smart people complained about this code in the past.
>
> These functions are really complex, they work quite differently for
> relation files and others. The responsibility for verifying the
> checksums is supposedly in read_file_data_into_buffer() -- but the
> caller still needs to worry about page boundaries and short reads and
> warn about checksum failure on short read. That's not new with your
> patches, but it's getting worse.
>
> I think this all becomes more clear if we separate the code to handle
> relation files and other files. See attached. The first patch splits
> sendFile() into two: sendRelFile() for relation files, and sendFile()
> for all other files. That duplicates some code, but makes it more
> readable IMHO. sendFile() can call basebackup_read_file() directly, and
> read_[rel]file_data_into_buffer() is only be used for relation files,
> which makes the 'is_relfile' argument unnecessary.
>
> The second patch changes read_relfile_data_into_buffer() to always work
> with full BLCKSZ blocks. That moves the handling of partial reads fully
> inside read_relfile_data_into_buffer(), making the caller simpler.
>
> These two patches are on top of your two patches, because I developed
> them that way, but it would probably make sense to squash them a little.
Hi Heikki,
Wow, thanks, I was afraid to even touch all of that, but yes it makes it
easier to follow. I've stressed it and I've got two test failures [1] due to
that 0003 ("split sendFile() and sendRelFile()"):
- pg_verifybackup/008_untar, ERROR: could not read file "./junk": Bad address
- pg_verifybackup/010_client_untar , could not read COPY data + crash +
"could not opendir"
In both cases it was due to 640kB "junk" non-relation file being read into
256kB buffer and then blowing up with e.g. with EFAULT due pread().
Then I've tried to break the basebackup in parallel with traffic for quite
some time, but I couldn't :) That was with pgbench -s 100 (~2.2GB relation,
so 2 segments), parallel concurrent loops of VACUUMS/TRUNCATE,
-DSIMULATE_SHORT_READ, and the end hash of table was gathered. Then real
restores worked, hash of the table matched and amcheck did not complain.
I cannot think of anything else.
As for code itself:
- one comment was not updated
- I've noticed we got rid of ereport("could not verify checksum in file")
and started to wonder if that's a good thing. Even with the retries one
of the cases is gone now (transistent reads), but I suspect there could
be sick situations where relfilesize % BLCKSZ != 0 (something odd
happened; try echo "123" >> 16384.100, just static file/fs corrupted). It
looks like earlier we would ship that garbage and with this we seem to be
just shiping zeros instead. I'm not after those zeros or data (WAL should
fix that), but the fact that there is such file in such state in first
place (pg_basebackup is also used as healthy DB verification kinda of thing,
it's often the only thing people use to verify readability of their DB
along with checksums-crosscheck). IMHO we should raise more attention to
such scenarios, if for some reason on some fs/platform it is possible to
end up with such traiing bytes I would sleep safer if user got WARNING,
so I've added another patch for Your's consideration.
Other than that, the CI seem to be happy about this v0005 implementation
(GHA does not have capactiy for MacOS runs for the 2nd day in row).
I'm thinking of squashing all of this into one bigger thing (it's kinda
pointless to have commit just for changing the #define SINK_BUFFER_SIZE?)
or do You want to have it refactor first and then just adjust #define?
-J.
[1] - meson test -C build -q --print-errorlogs --suite setup \
--suite postgresql:pg_basebackup \
--suite postgresql:pg_verifybackup \
--suite postgresql:pg_combinebackup
[2] - https://github.com/jakubwartakEDB/postgres-public-ci/actions/runs/42016809106
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
От:
Jakub Wartak <jakub.wartak@enterprisedb.com>
Дата:
Вложения:
On Tue, Oct 20, 2026 at 3:44 AM Gustavo William wrote: > > Hi, > > Apologies for the delay. > Hi Gustavo, same from my side, apologies, finally I've got to this after the PgConfEU. The 0005 didn't want to apply cleanly due to 51d7bf5edcaf4. I've fixed it now. > TL;DR: > > - The speedup from 0005 depends a lot on how much the incremental backup has changed > since the last one: ~9.8x at 14% delta, ~3.7x at 33%, ~1.2x at 57%. That explains the > difference between Jakub's 9.4x speedup and the ~1.5x I first saw. > - Most of the gain comes from avoiding the kernel's own readahead on scattered blocks > (it was doing more than double the I/O needed), not from concurrency. > - Merging adjacent blocks matters. Without it, 0005 is slower than master on backups > with a high delta. > - maintenance_io_concurrency (m_io_c) beyond 2 only helps a little, and only when > there are many adjacent blocks. m_io_c = 1 is still worse though. > - Code changes in this version: prefetch is enabled again for m_io_c = 1, the merge > limit is now io_combine_limit, there is a new limit on how far ahead we prefetch, > and the prefetch state moved into a new IncrPrefetch struct. > > > I've verified ~9.4x improvement with 0005-incremental-backup > > I was confused by the big difference between our results, since I had initially seen > only ~1.5x. After replicating your tests I found the reason: the speedup varies a lot > depending on how much delta your incremental backup has. > > I followed the same method you described: [..] > > delta change without 0005 with 0005 speedup > ------------- ------------ --------- ------- > ~14% (~1.1G) 42.48 4.31 ~9.8x > ~33% (~2.5G) 27.56 7.49 ~3.7x > ~57% (~4.3G) 15.60 13.13 ~1.2x > > So the higher the delta, the smaller the gain from 0005. I think this ties back to the > kernel behavior you observed. True, I suspect that on production dbs, the delta is going to be rather small most of the time. > Reading scattered blocks the way pg_basebackup does today seems to confuse the kernel. > After a single block read, the kernel may readahead the following blocks, expecting a > sequential pattern. With scattered delta blocks that never happens, so the prefetched > data is wasted. I actually checked this on /proc//io during a backup of ~14% delta: > > Without 0005 > ``` > rchar: 1139995913 # bytes requested by the process (1.1GB) > syscr: 138285 > read_bytes: 2557988864 # bytes actually read from storage (2.5GB) > ``` > > With 0005 > ``` > rchar: 1139966637 # bytes requested by the process (1.1GB) > syscr: 138279 > read_bytes: 1143574528 # bytes actually read from storage (1.1GB) > ``` > > So, without 0005 the kernel does more than double the I/O we need. 0005 helps with > concurrency, but its major improvement is avoiding this misguided readahead. Thanks for doing those measurements - apparently we did not concentrate that much on performance as we should, back when incrementental backups were introduced (PG17). > This explains the results above. With 14% delta from pgbench, most blocks are > scattered, so 0005 avoids all that double I/O and gets a huge speedup. At 57% the delta > blocks are much more adjacent, so the kernel's own readahead gets a good part of its > guesses right and 0005 has less to improve on. > > A few other questions I tried to answer in this round: > > 1. Does increasing maintenance_io_concurrency make a big difference? > > Not really. There's some gain up to a point, but it's small. This also reinforces that > most of the gain of 0005 comes from avoiding the kernel's double I/O, not from > concurrency itself. Below are some results of backup with 14% delta (in seconds): > > with m_io_c = 2: 4.45 > with m_io_c = 16: 4.14 > with m_io_c = 32: 4.07 > with m_io_c = 64: 4.18 > > This made me wonder if we should stop making the prefetch window tied to m_io_c and > instead just use a small fixed number like 2. But a higher m_io_c does give a > modest gain on backups with a higher delta (more adjacent blocks). With ~57% delta: > > with m_io_c = 2: 13.13 > with m_io_c = 16: 10.28 > Let's just tie with m_io_c for simplicity. If it does not hurt, so we can leave as that. > 3. Is merging adjacent blocks really helping? > > At some point I considered dropping the merge-of-adjacent-blocks piece, so I decided > to measure it on a 57% delta backup with m_io_c = 16 (results in seconds): > > without 0005: 15.60 > 0005 with merge: 10.28 > 0005 without merge: 20.41 > > It helps a lot. Without it, 0005 makes incremental backups with a high delta > slower than not having 0005 at all (15.60 above). > Cool. > > Now regarding the code changes of this last iteration: > > 2. We had previously agreed on a limit for how many blocks can be merged into a single > fadvise. I was using maintenance_io_concurrency for that, but I thought > io_combine_limit might be a better fit according to its description. Do you think > that makes sense? Yes, sounds good. > 3. The previous version had no limit on how far ahead, in blocks, we could prefetch. > Each iteration runs one prefetch_next_incremental_run(), which can cover many > blocks when they're adjacent. With lots of adjacent blocks we could get far ahead of > the block being read, filling the page cache with pages that won't be needed any > time soon and might even be evicted before they are read. > > Based on that, I added a distance limit, in blocks, of > maintenance_io_concurrency * io_combine_limit. When there are many adjacent blocks, > that keeps us at most maintenance_io_concurrency fadvise calls ahead of the current > block. Sounds good too (unless anybody else complains of course). I've checked syscalls using strace for fadvise64 vs pread64 and we seem to be good from fadvise64 case. We could do way better for pread() for the incremental case -- to merge adjacent indvidiual 8kB pread request into bigger ones/multuple ones by using preadV(), but that's way of outside this fadvise-patch, and it possibly would be smarter to use readstreaming API for that in far future (I haven't investigated that). > 4. I added a new struct named IncrPrefetch to the code to hold some parameters of the > prefetch mechanism. I thought sendFile() was getting a lot of new variables and > becoming harder to read. I hope that makes sense. Sure! Due to number of changes I'm attaching full current patchset changes include: - your's new v0005 incremental (now 0006 temporarily) that was fixed due to that 51d7bf5edcaf4 - fixes to re-reading & handling interruptions due to larger SINK_BUFF_SIZE (0004, 0005) from paralllel subthread (as requested by Heikki) - WIP-refactor of the sendFile and sendRelfile(); this prefetching patch wouldn't apply later on, so I've rebased it further so now SINK_BUFF_SIZE and related patches by Heikki are prerequsite for our fadvise patch) -J.
Re: enhancing pg_basebackup speeds up to ~23Gbps (small fixes + io_uring/Direct I/O)
От:
Markos Fountoulakis <markos@planetscale.com>
Дата:
On 2026-11-05 13:45 +0200, Jakub Wartak wrote:
> On Wed, Nov 4, 2026 at 11:45 PM Heikki Linnakangas wrote:
>>
>> On 29/10/2026 16:16, Jakub Wartak wrote:
>>> On Thu, Oct 15, 2026 at 2:09 PM Heikki Linnakangas wrote:
>>>> Ok, looks good as far as it goes. But looking at basebackup_read_file(),
>>>> I think there's a race condition with partial_read_ok == false. This
>>>> could happen:
>>>>
>>>> 0. read_file_data_into_buffer() observes a checksum failure thanks to a
>>>> torn write, and retries reading a single BLCKSZ block.
>>>> 1. basebackup_read_file() is called with partial_read_ok == false,
>>>> nbytes=BLCKSZ.
>>>> 2. It reads the first 4096 bytes of the block. (e.g. because of
>>>> SIMULATE_SHORT_READ, or EINTR)
>>>> 3. The file is truncated
>>>> 4. basebackup_read_file() makes another pg_pread() call to read the rest
>>>> of the block. It returns 0, because the file was truncated
>>>> 5. basebackup_read_file() throws a partial read error: "could not read
>>>> file \"%s\": read %zu of %zu".
>>>>
>>>> If the truncation happened earlier, before the first read, or later,
>>>> after the whole block has been read, you don't get the error.
>>>
>>> Hi Heikki,
>>>
>>> So the 0001 is the previous one, and and 0002 is about fixing that
>>> SIMULATE_SHORT_READ/EINTR situation above (separate just to ease the review).
>>> I suspect we should never assume that basebackup_read_file() with
>>> partial_read_ok==false is fine, so it was my starting point, so:
>>> - reread_cnt = basebackup_read_file(..., partial_read_ok=false)
>>> - if (reread_cnt == 0)
>>> + reread_cnt = basebackup_read_file(..., partial_read_ok=true)
>>> + if (reread_cnt != BLCKSZ)
>>> and that was it's only user, so it's gone now.
>>>
>>> But there's more and it deserves some explanation: when running above
>>> WIP-fix to that reread race condition and simulating EINTR/short reads
>>> and backing up things things in parallel all the time and having this
>>> setup:
>>>
>>> 1. #define SIMULATE_SHORT_READ
>>> 2. INSERT INTO t SELECT generate_series(1, 10000); \watch 0.0001
>>> 3. TRUNCATE t; \watch 0.0001 -- it kept on rotating relfilenode a lot
>>> 4. optional: strace in parallel (even more EINTR and stuff)
>>> 5. while : ; do rm -rf /tmp/full1 && install/bin/pg_basebackup -c fast \
>>> -h 127.0.0.1 -D /tmp/full1 && install/bin/pg_verifybackup /tmp/full1; \
>>> done
>>>
>>> I've started receving haywire stuff like:
>>> WARNING: could not verify checksum in file "./base/5/157555", block 32:
>>> read buffer size 167936 and page size 8192 differ
>>> DETAIL: bytes_done=262144 filestat.st_size=3629056 fstat_rc=0 fstat_size=0
>>>
>>> Please notice the 2nd fstat report size of 0 (truncation) vs 3629056, so I
>>> had to fix that further, so that's why I landed with is_relfile and inside
>>> read_file_data_into_buffer() there's now:
>>> if (is_relfile && cnt < requested && (cnt % BLCKSZ) != 0)
>>> hopefully comment explains the rationale.
>>>
>>> The errdetail() is still there and I would like to keep it , but maybe
>>> some better form or shape or maybe better leave it as separate DEBUG1
>>> to still being able to troubleshoot this code (it's hard).
>>>
>>> A thorough review would be highly advisable, as this is like walking on thin
>>> ice and a lot of smart people complained about this code in the past.
>>
>> These functions are really complex, they work quite differently for
>> relation files and others. The responsibility for verifying the
>> checksums is supposedly in read_file_data_into_buffer() -- but the
>> caller still needs to worry about page boundaries and short reads and
>> warn about checksum failure on short read. That's not new with your
>> patches, but it's getting worse.
>>
>> I think this all becomes more clear if we separate the code to handle
>> relation files and other files. See attached. The first patch splits
>> sendFile() into two: sendRelFile() for relation files, and sendFile()
>> for all other files. That duplicates some code, but makes it more
>> readable IMHO. sendFile() can call basebackup_read_file() directly, and
>> read_[rel]file_data_into_buffer() is only be used for relation files,
>> which makes the 'is_relfile' argument unnecessary.
>>
>> The second patch changes read_relfile_data_into_buffer() to always work
>> with full BLCKSZ blocks. That moves the handling of partial reads fully
>> inside read_relfile_data_into_buffer(), making the caller simpler.
>>
>> These two patches are on top of your two patches, because I developed
>> them that way, but it would probably make sense to squash them a little.
>
> Hi Heikki,
>
> Wow, thanks, I was afraid to even touch all of that, but yes it makes it
> easier to follow. I've stressed it and I've got two test failures [1] due to
> that 0003 ("split sendFile() and sendRelFile()"):
> - pg_verifybackup/008_untar, ERROR: could not read file "./junk": Bad address
> - pg_verifybackup/010_client_untar , could not read COPY data + crash +
> "could not opendir"
>
> In both cases it was due to 640kB "junk" non-relation file being read into
> 256kB buffer and then blowing up with e.g. with EFAULT due pread().
>
> Then I've tried to break the basebackup in parallel with traffic for quite
> some time, but I couldn't :) That was with pgbench -s 100 (~2.2GB relation,
> so 2 segments), parallel concurrent loops of VACUUMS/TRUNCATE,
> -DSIMULATE_SHORT_READ, and the end hash of table was gathered. Then real
> restores worked, hash of the table matched and amcheck did not complain.
> I cannot think of anything else.
>
> As for code itself:
> - one comment was not updated
> - I've noticed we got rid of ereport("could not verify checksum in file")
> and started to wonder if that's a good thing. Even with the retries one
> of the cases is gone now (transistent reads), but I suspect there could
> be sick situations where relfilesize % BLCKSZ != 0 (something odd
> happened; try echo "123" >> 16384.100, just static file/fs corrupted). It
> looks like earlier we would ship that garbage and with this we seem to be
> just shiping zeros instead. I'm not after those zeros or data (WAL should
> fix that), but the fact that there is such file in such state in first
> place (pg_basebackup is also used as healthy DB verification kinda of thing,
> it's often the only thing people use to verify readability of their DB
> along with checksums-crosscheck). IMHO we should raise more attention to
> such scenarios, if for some reason on some fs/platform it is possible to
> end up with such traiing bytes I would sleep safer if user got WARNING,
> so I've added another patch for Your's consideration.
>
> Other than that, the CI seem to be happy about this v0005 implementation
> (GHA does not have capactiy for MacOS runs for the 2nd day in row).
>
> I'm thinking of squashing all of this into one bigger thing (it's kinda
> pointless to have commit just for changing the #define SINK_BUFFER_SIZE?)
> or do You want to have it refactor first and then just adjust #define?
>
> -J.
>
> [1] - meson test -C build -q --print-errorlogs --suite setup \
> --suite postgresql:pg_basebackup \
> --suite postgresql:pg_verifybackup \
> --suite postgresql:pg_combinebackup
>
> [2] - https://github.com/jakubwartakEDB/postgres-public-ci/actions/runs/42016809106
Hi Jakub,
I reviewed the patch-set a bit, my biggest issue is with the use of fallocate():
- In general fallocate() has proven to be a bit problematic depending on the filesystem implementation of it (e.g. [1]), i.e. performance may regress on a network filesystem or a CoW one.
- Moreover, erroring out with FATAL for ENOSPC seems problematic to me:
- I think it is simpler in general to let the write() fail with ENOSPC (instead of fallocate()), which also should fail at a later time which may be desirable
- which is especially true in the case of overextending DIO_PREALLOC_CHUNK and potentially failing with ENOSPC when less real space is required
To conclude I am in favour of removing fallocate() altogether from this work, otherwise at least remove all the ENOSPC checks and maybe let it fail at the write() syscall stage instead.
[1] - https://www.postgresql.org/message-id/flat/E1voE6M-001P1f-18%40gemulon.postgresql.org
--
Markos Fountoulakis
PlanetScale
--
Markos Fountoulakis
PlanetScale