Re: Compression of bigger WAL records
Re: Compression of bigger WAL records
От:
Fujii Masao <masao.fujii@oss.nttdata.com>
Дата:
On 2025/01/22 3:24, Andrey M. Borodin wrote: > > >> On 12 Jan 2025, at 17:43, Andrey M. Borodin wrote: >> >> I attach a prototype patch. > > Here's v2, now it passes all the tests with wal_debug. I like the idea of WAL compression more. With the current approach, each backend needs to allocate memory twice the size of the total WAL record. Right? One area is for the gathered WAL record data (from rdt and registered_buffers), and the other is for storing the compressed data. Could this lead to potential memory usage concerns? Perhaps we should consider setting a limit on the maximum memory each backend can use for WAL compression? Regards, -- Fujii Masao Advanced Computing Technology Center Research and Development Headquarters NTT DATA CORPORATION
Re: Compression of bigger WAL records
От:
wenhui qiu <qiuwenhuifx@gmail.com>
Дата:
Hi Andery
I have a question ,If wal_compression_threshold is set to more than the block size of the wal log, then the FPI is not compressed, and if so, it might make sense to have a maximum value of this parameter that does not exceed the block size of the wal log?
Best regards
On Thu, Jan 30, 2025 at 9:26 PM Andrey Borodin <x4mmm@yandex-team.ru> wrote:
> On 23 Jan 2025, at 20:13, Japin Li <japinli@hotmail.com> wrote:
>
>
> I find this feature interesting;
Thank you for your interest in the patch!
> however, it cannot be applied to the current
> master (b35434b134b) due to commit 32a18cc0a73.
PFA a rebased version.
>
> I see the patch compresses the WAL record according to the wal_compression,
> IIRC the wal_compression is only used for FPI, right? Maybe we should update
> the description of this parameter.
Yes, I'll udpate documentation in future versions too.
> I see that the wal_compression_threshold defaults to 512. I wonder if you
> chose this value based on testing or randomly.
Voices in my head told me it's a good number.
> On 28 Jan 2025, at 22:10, Fujii Masao <masao.fujii@oss.nttdata.com> wrote:
>
> I like the idea of WAL compression more.
Thank you!
> With the current approach, each backend needs to allocate memory twice
> the size of the total WAL record. Right? One area is for the gathered
> WAL record data (from rdt and registered_buffers), and the other is for
> storing the compressed data.
Yes, exactly. And also a decompression buffer for each WAL reader.
> Could this lead to potential memory usage
> concerns? Perhaps we should consider setting a limit on the maximum
> memory each backend can use for WAL compression?
Yes, the limit makes sense.
Also, we can reduce memory consumption by employing a streaming compression. Currently, I'm working on a prototype of such technology, because it would allow wholesale WAL compression. The idea is to reuse compression context from previous records to better compress new records. This would allow efficient compression of even very small records. However, there is exactly 0 chance to get it done in a decent shape before feature freeze.
The chances of getting currently proposed approach to v18 seems slim either... I'm hesitating to register this patch on the CF. What do you think?
Best regards, Andrey Borodin.
Re: Compression of bigger WAL records
> On 31 Jan 2025, at 08:37, wenhui qiu wrote: > > Hi Andery > I have a question ,If wal_compression_threshold is set to more than the block size of the wal log, then the FPI is not compressed, and if so, it might make sense to have a maximum value of this parameter that does not exceed the block size of the wal log? Oops, looks like I missed your question. Sorry for so long delay. User might want to compress only megabyte+ records, there's nothing wrong with it. WAL record itself is capped by 1Gb (XLogRecordMaxSize), I do not see a reason to restrict wal_compression_threshold by lower value. PFA rebased version. Best regards, Andrey Borodin.
Re: Compression of bigger WAL records
> On 14 Jul 2025, at 23:22, Andrey Borodin wrote: > > PFA rebased version. Here's a rebased version. Also I fixed a problem of possible wrong memory context used for allocating compression buffer. Best regards, Andrey Borodin.
Re: Compression of bigger WAL records
От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Mon, Jan 12, 2026 at 2:54 AM Andrey Borodin wrote:
>
>
>
> > On 14 Jul 2025, at 23:22, Andrey Borodin wrote:
> >
> > PFA rebased version.
>
> Here's a rebased version. Also I fixed a problem of possible wrong memory context used for allocating compression buffer.
Thanks for updating the patch!
With the v5 patch, I see the following compiler warning:
xlog.c:726:1: warning: unused function 'XLogGetRecordTotalLen'
[-Wunused-function]
726 | XLogGetRecordTotalLen(XLogRecord *record)
| ^~~~~~~~~~~~~~~~~~~~~
This seems to happen because XLogGetRecordTotalLen() is only used under
WAL_DEBUG. If that's correct, its definition should probably also be guarded
by WAL_DEBUG to avoid the warning.
cfbot reported a regression test failure with v5. Could you please
look into that?
https://cirrus-ci.com/build/5635306839343104
When I ran pg_waldump on WAL generated with wal_compression=pglz and
wal_compression_threshold=32, I got this error:
pg_waldump: error: error in WAL record at 0/02183BE0: could not
decompress record at 0/2183D10
Isn't this a bug?
+ XLogEnsureCompressionBuffer(MaxSizeOfXLogRecordBlockHeader + BLCKSZ);
XLogEnsureCompressionBuffer() is now called every time XLogRegisterBuffer(),
XLogRegisterBlock(), XLogRegisterData(), and XLogRegisterBufData() are invoked.
Why is that necessary? Wouldn't it be sufficient to
call XLogEnsureCompressionBuffer() once, with the total length,
just before XLogCompressRdt(rdt)?
v5 removes the ability to compress only full-page images, which is the current
wal_compression behavior. That may be disappointing for users who rely on
the existing semantics. Would it make more sense to keep the current behavior
and add a new feature to compress entire WAL records whose size exceeds
the specified threshold?
Regards,
--
Fujii Masao
Re: Compression of bigger WAL records
От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
Hi Fujii! Thanks for the review, I'll address your feedback soon. > On 16 Jan 2026, at 20:44, Fujii Masao wrote: > > Would it make more sense to keep the current behavior > and add a new feature to compress entire WAL records whose size exceeds > the specified threshold? That's a very good idea! We don't need to replace current behavior, we can just complement it. I'll implement this idea! Best regards, Andrey Borodin.
Re: Compression of bigger WAL records
> On 16 Jan 2026, at 21:17, Andrey Borodin wrote: > > That's a very good idea! We don't need to replace current behavior, we can just complement it. > I'll implement this idea! Here's the implementation. Previously existing buffers are now combined into single allocation, which is GUC-controlled (you can add more memory). However, now this buffer is just enough to accommodate most of records... So, maybe we do not need a GUC at all, because keeping it minimal (same consumption as before the patch) is just enough. Now the patch essentially have no extra memory footprint, but allows to save 25% of WAL on index creation (in case of random data). User can force FPI-only compression by increasing wal_compression_threshold to 1GB. The decision chain is now a bit complicated: - assemble record without compression FPIs - try whole record compression - if compression enlarged record fallback to FPI compression I think the case can be simplified to "Try only one compression approach that is expected to work, if not - insert uncompressed". What do you think? Best regards, Andrey Borodin.
Re: Compression of bigger WAL records
От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello
+static void
+AllocCompressionBuffers(void)
+{
+ uint32 new_size = wal_compression_buffer;
This is called in the assign hook - and isn't that called before the
global variable is updated?
+ compressed_header->method = XLR_COMPRESS_LZ4;
+ compr_len = LZ4_compress_default((char *) &src_header[1], (char *)
&compressed_header[1],
+ orig_len, compressed_data_size);
compressed_header[1] has an offset of 32, but compressed_data_size
refers to the entire size, isn't there a possible buffer overrun here?
Same with ZSTD.
+/* Header prepended to a whole-record compressed WAL record */
+typedef struct XLogCompressionHeader
+{
+ XLogRecord record_header;
+ uint8 method; /* XLR_COMPRESS_* */
+ uint32 decompressed_length;
+} XLogCompressionHeader;
This has 3 bytes of uninitialized padding, is that okay? I remember
seeing a separate thread about possibly cleaning these up not long
ago.
+# Enable WAL compression for recovery tests.
+# lz4 is used here; 052_wal_compression.pl separately tests all methods.
+wal_compression = 'lz4'
Doesn't this test needs a check to require a build with compression flags?
+#wal_compression = lz4 # enables compression of
full-page writes;
But the default value is still off, isn't this example misleading?
+ total_len_decomp = -1; /* XLogCompressionHeader spans pages */
at multiple places, but this is an unsigned variable.
+ variable => 'wal_compression_buffer',
+ boot_val => '295972',
+ min => '295972',
Doesn't guc_params.dat support using macros instead of this hardcoded
magic number?
Re: Compression of bigger WAL records
От:
Japin Li <japinli@hotmail.com>
Дата:
Hi, Andrey On Mon, 09 Mar 2026 at 22:07, Andrey Borodin wrote: >> On 16 Jan 2026, at 21:17, Andrey Borodin wrote: >> >> That's a very good idea! We don't need to replace current behavior, we can just complement it. >> I'll implement this idea! > > Here's the implementation. Previously existing buffers are now combined > into single allocation, which is GUC-controlled (you can add more memory). > > However, now this buffer is just enough to accommodate most of records... > So, maybe we do not need a GUC at all, because keeping it minimal (same > consumption as before the patch) is just enough. > > Now the patch essentially have no extra memory footprint, but allows to > save 25% of WAL on index creation (in case of random data). > > User can force FPI-only compression by increasing wal_compression_threshold > to 1GB. > > The decision chain is now a bit complicated: > - assemble record without compression FPIs > - try whole record compression > - if compression enlarged record fallback to FPI compression > I think the case can be simplified to "Try only one compression approach that > is expected to work, if not - insert uncompressed". > > What do you think? > > Thanks for updating the patch. It seems a rebase is needed. $ git am ~/v6-0001-Add-whole-record-WAL-compression-alongside-FPI-co.patch Applying: Add whole-record WAL compression alongside FPI compression error: patch failed: src/backend/access/transam/xloginsert.c:115 error: src/backend/access/transam/xloginsert.c: patch does not apply Patch failed at 0001 Add whole-record WAL compression alongside FPI compression hint: Use 'git am --show-current-patch=diff' to see the failed patch When you have resolved this problem, run "git am --continue". If you prefer to skip this patch, run "git am --skip" instead. To restore the original branch and stop patching, run "git am --abort". > Best regards, Andrey Borodin. > > [2. text/x-diff; v6-0001-Add-whole-record-WAL-compression-alongside-FPI-co.patch]... -- Regards, Japin Li ChengDu WenWu Information Technology Co., Ltd.
Re: Compression of bigger WAL records
Hi hackers!
This is v7, and it is now three patches. The thread had grown into one
patch doing several things at once, so I split it, and the first of the
three is useful on its own.
Sorry for the long silence, and for leaving several review comments
unanswered since March. I have tried to answer all of them below.
---- 0001: reuse a zstd compression context ----
This one is independent of the rest of the thread, so I am putting it
first as low-hanging fruit.
XLogCompressBackupBlock() calls ZSTD_compress(), which creates and
destroys a ZSTD_CCtx on every call. That context is not small: at the
default level ZSTD_estimateCCtxSize() reports 1.3MB. So a backend
running with wal_compression = zstd pays that allocation once per
full-page image, and a record can carry up to XLR_MAX_BLOCK_ID + 1 of
them.
The patch creates the context on first use and keeps it for the life of
the backend, compressing with ZSTD_compressCCtx(). On a statement that
logs 48k full-page images this is about 12% faster.
Pros: small, one file, no format change, and the WAL it produces is
identical byte for byte.
Cons: a backend that used zstd once holds the 1.3MB until it exits. I
think that is the right trade, but it is a real change in footprint for
a backend that compresses once and never again.
---- 0002: whole-record compression alongside FPI compression ----
This is the feature this thread started with, with Fujii-san's
suggestion applied: it complements per-FPI compression instead of
replacing it.
When a record is larger than wal_compression_threshold, it is compressed
as a single unit instead of compressing each full-page image on its own.
That wins whenever the images in one record share content, which is
typical of B-tree index builds. On CREATE INDEX over 10M random floats,
WAL drops from 160MB to 132MB with lz4 and from 125MB to 97MB with zstd.
Only lz4 and zstd take part now. pglz refuses input it cann't shrink
significantly, which a record made of full-page images rarely clears, so
in the earlier versions it cost a flatten and a compression attempt and
saved nothing measurable. It still compresses full-page images exactly as
before.
Pros: it reaches a redundancy that per-FPI compression cannot see, and
records below the threshold are untouched. Every record still decodes
on its own, so nothing about how WAL is read changes. Setting the
threshold above the largest possible record restores today's behaviour.
Cons:
1. Memory. The per-block compressed_page arrays are replaced by two
buffers carved out in one piece, one staging the record and one
taking the compressor output. Each is 274300 bytes with BLCKSZ 8192
and zstd compiled in, against 273372 bytes for the old arrays at
their 33-block maximum. So a backend with compression enabled holds
about twice what it held before. The staging buffer reproduces the
old allocation; the output buffer is genuinely new. It cannot be
removed without compressing straight off the rdt chain, and the
compressed length has to be known before WAL space is reserved, so
the output has to be materialized somewhere. Perhaps, I can just
assume the buffer of a twice smaller size, or somthing like that...
2. A low threshold can make WAL bigger. Whole-record compression
displaces per-FPI compression for the records it takes, and adds 8
bytes of header to each. On a pgbench run, threshold 32 produced 720
bytes of WAL per transaction against 622 at the default 512.
---- 0003: compress records against earlier records (WIP) ----
This is the direction I mentioned in the first message of this thread,
and it is not in a good shape yet. Just a prototype, it womewhat works but
the design discussion is needed.
Half the WAL a pgbench run produces is out of reach for per-record
compression. On a 1.6GB sample the median record was 72 bytes, and the
0.8% of records over 512 bytes held 47.5% of the bytes. A 72-byte
record does not compress on its own. It compresses very well against
the records before it.
Offline, on that sample, compressing each record on its own gives 1.76x.
Keeping a compressor across records, flushed after every record so the
record is complete when it is inserted, gives 2.93x across 8 streams.
The flush is not optional: WAL cannot leave a record's bytes inside a
compressor, and the compressed length has to be known before the space
is reserved.
The patch adds wal_compression_streams, a pool of streams a backend
leases while it compresses and inserts, so records enter a stream in the
order a reader will meet them. Currently a backend taking a lease over restarts
the stream, because the compressor state lives in the other backend and
shared memory cannot hold a libzstd object. I think I can fix it in future
iterations.
Once a record depends on the ones before it, some records have to stay
out of the scheme. The rule is not a resource-manager list but a
property: anything that someone reads by LSN without replaying what
precedes it has to stay readable on its own. Recovery finds the
checkpoint record from pg_control, and twophase.c reads a PREPARE record
from a stored LSN, so those are excluded, and XLOG_SWITCH with them.
This applies only with streams on; in 0002 every record is independent
and nothing is excluded.
What works: crash recovery, the data, amcheck, and reading a whole WAL
segment, because streams restart at segment boundaries.
What does not: a reader starting at an arbitrary LSN inside a segment
cannot decode, because it has no stream context for the records before
its start point. pg_waldump --start and pg_walinspect both fail that
way, and pg_rewind and logical decoding restart points would too. That
has to be solved before this is worth reviewing. I would welcome
opinions on the shape of the solution: my current thinking is that the
format has to let a reader find the nearest preceding stream restart.
It also costs throughput. On pgbench the stream lock, which is held
across compression and insertion, cost about 12% tps on my machine. I
have not measured that on a machine large enough for the WAL insert path
to be contended, and Andres has pointed out elsewhere that it already is
there.
---- Testing ----
Everything below is on a 16-core Linux box, built with AddressSanitizer
and --enable-cassert.
The workload walks the start offset of a compressed record across a
whole WAL page, emits messages sized on both sides of the threshold and
of the internal buffer bound, writes high-entropy payloads so the
compressor gives up, and takes four checkpoint-and-update rounds so
records carry full-page images. It then crashes the server and checks
that recovery reproduces two checksums, that pg_waldump and
pg_get_wal_records_info() decode the range, and that bt_index_check()
passes. wal_consistency_checking = all compares every replayed page
against the image in the record.
0001 and 0002 pass that with zero sanitizer reports, with compression
off, with zstd at the default and at threshold 32, with lz4, with pglz,
and with consistency checking on.
I also built all four combinations of --with-lz4 and --with-zstd with
-Werror, after Kirill's report above.
Two bugs in my own reader code turned up on the way, both now fixed in
0002. When a compressed record's header straddled a WAL page, the
reader reserved a decode slot sized for the compressed length and then
decoded the larger record into it. And the slot was not reset when the
read restarted, so a later pass could hand out a slot already in the
decode queue. Neither reproduces at the default threshold, which is why
they survived so long. I could not build a TAP test that fails before
the fix and passes after, so I have not added one.
---- Answers ----
On 12 Jan 2025, Kirill Reshke wrote:
> initdb fails when configured with --without-zstd
Thank you, and sorry it took this long. Builds without the compression
libraries are handled now: the whole-record machinery is compiled out
when neither lz4 nor zstd is present, and the reader still recognizes
such a record and reports it properly rather than mis-decoding it. I
built all four combinations with -Werror.
On 23 Jan 2025, Japin Li wrote:
> I see the patch compresses the WAL record according to the
> wal_compression, IIRC the wal_compression is only used for FPI, right?
> Maybe we should update the description of this parameter.
You are right, and I still owe this. postgresql.conf.sample is updated
in 0002, but the GUC description and the documentation are not. I will
do that before this soon.
> I see that the wal_compression_threshold defaults to 512. I wonder if
> you chose this value based on testing or randomly.
I answered this with a joke at the time, which it deserved less than a
real answer. I have measured it since: within per-record compression
the threshold barely matters, because small records do not compress on
their own. Compressing every record instead of only those over 512
bytes changed a 1.6GB sample by less than one percent. What the
threshold really controls is how much per-FPI compression gets
displaced, and lowering it can make WAL bigger, as in point 2 above.
For an outside data point, the usual recommendation for gzip over HTTP
is not to bother below roughly 860 bytes [1], on the same argument:
below that the header and the CPU cost outweigh what you save. That is
a different domain and WAL records are not HTTP responses, but the order
of magnitude agrees with what I measured. So 512 is a reasonable
default, for a better reason than the one I gave. If anything this
suggests it should be a little higher rather than lower, and I would not
object to 1kB if someone prefers a round number.
On 28 Jan 2025, Fujii Masao wrote:
> With the current approach, each backend needs to allocate memory twice
> the size of the total WAL record. [...] Perhaps we should consider
> setting a limit on the maximum memory each backend can use for WAL
> compression?
I tried that as a GUC and then removed it. The buffers are now a fixed
size, equal to the largest record that can be built, which is the same
amount the per-block arrays occupied at their maximum. A GUC did not
earn its place: the minimum useful value is already the value you want,
and it brought an assign-hook ordering bug with it, which Zsolt found.
The honest summary is point 1 above: it is 2x, not 1x, and I do not see
how to avoid the second buffer.
On 16 Jan 2026, Fujii Masao wrote:
> With the v5 patch, I see the following compiler warning:
> xloginsert.c:726:1: warning: unused function
> 'XLogGetRecordTotalLen'
Fixed since v6; it is guarded by WAL_DEBUG. Note my own tree builds
with -DWAL_DEBUG, so cfbot is what actually proves it.
> cfbot reported a regression test failure with v5.
Should be gone. make check and the recovery suite pass, and the stress
matrix above passes under a sanitizer build.
> When I ran pg_waldump on WAL generated with wal_compression=pglz and
> wal_compression_threshold=32, I got this error:
> pg_waldump: error: error in WAL record at 0/02183BE0: could not
> decompress record at 0/2183D10
> Isn't this a bug?
I could not reproduce it, and it is now moot for pglz specifically,
since pglz no longer takes part in whole-record compression. 0002 runs
pg_waldump over compressed WAL for every method as part of its test, and
the stress runs above do the same. If you still have the recipe I would
like to try it against v7.
> XLogEnsureCompressionBuffer() is now called every time
> XLogRegisterBuffer() [...] Why is that necessary?
It is not, and it is gone since v6. The buffers are allocated once,
outside any critical section.
> v5 removes the ability to compress only full-page images [...] Would
> it make more sense to keep the current behavior and add a new feature
> to compress entire WAL records whose size exceeds the specified
> threshold?
That was the right call and it is what 0002 does. Thank you.
On 9 Mar 2026, Zsolt Parragi wrote:
Thank you for reading it that closely. Every one of these was real.
> +static void
> +AllocCompressionBuffers(void)
> +{
> + uint32 new_size = wal_compression_buffer;
>
> This is called in the assign hook - and isn't that called before the
> global variable is updated?
Yes. guc.c calls the assign hook and then assigns the variable, so the
hook saw the old value, and raising the GUC did not grow the buffers.
XLogCompressRdt() would then flatten a larger record into a smaller
buffer, which is a heap overflow in a non-assert build. The GUC is gone
now, and the remaining hook reads newval.
> compressed_header[1] has an offset of 32, but compressed_data_size
> refers to the entire size, isn't there a possible buffer overrun here?
> Same with ZSTD.
Correct. The destination now gets the space that is really left, after
the header.
> This has 3 bytes of uninitialized padding, is that okay?
It was not. The header is zeroed before it is filled, so the bytes that
reach disk are deterministic. I also reordered the fields, and
SizeOfXLogCompressedRecord is now plain sizeof(), which keeps it in
agreement with the pointer the payload is written to.
> Doesn't this test needs a check to require a build with compression
> flags?
Fixed by using pglz for the suite-wide config, since it is always
available. 052 covers lz4 and zstd separately and skips what a build
lacks.
> But the default value is still off, isn't this example misleading?
That was a leftover from my testing. postgresql.conf.sample says off
again.
> + total_len_decomp = -1; /* XLogCompressionHeader spans pages */
> at multiple places, but this is an unsigned variable.
Replaced with an explicit boolean. While fixing it I found that the
branch it belonged to was wrong in a worse way: it reserved a decode
slot sized for the compressed length and then decoded the decompressed
record into it.
> Doesn't guc_params.dat support using macros instead of this hardcoded
> magic number?
It does, but the GUC is gone so the number with it.
On 10 Mar 2026, Japin Li wrote:
> Thanks for updating the patch. It seems a rebase is needed.
Done, on top of master as of this week. Sorry for the wait.
Thank you!
Best regards, Andrey Borodin.
[0] https://postgr.es/m/4DC38068-976E-4A84-8EE6-4EFACBBD927A@yandex-team.ru
[1] https://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
Re: Compression of bigger WAL records
> On 26 Jul 2026, at 21:09, Andrey Borodin wrote:
>
> This is v7
Hi hackers!
This is v8. Still three patches. 0003 now answers the question I left
open in v7 - a reader can start at an arbitrary LSN. 0001 grew to
cover decompression as well, which turned out to be the bigger win, and
running the test suites with the feature actually turned on found a
number of bugs.
Numbers are from two machines, 4-core for 0002 and the compression side
of 0001, 16-core for 0003 and the redo figures, both built with -O2 and
without assertions, fsync off, shared_buffers 8GB. Each was repeated,
where a number moved between runs I say so.
---- 0001: reuse zstd contexts, both directions ----
Still the piece that is useful on its own, and it grew since v7: it now
keeps the decompression context too, which turns out to matter more.
XLogCompressBackupBlock() calls ZSTD_compress() and RestoreBlockImage()
calls ZSTD_decompress(). Both create and destroy a context per call. At
the default level ZSTD_estimateCCtxSize() reports 1.3MB for the
contex. So zstd pays an allocation per full-page image on the
way in, and one per image again on the way out. The patch creates each
on first use and keeps it, the compressor for the life of the backend,
the decompressor in XLogReaderState.
The reading side is where this shows, because one startup process
replays every image. Redoing 200MB of page images:
zstd, master 4.24s zstd, patched 2.33s
lz4, master 1.59s lz4, patched 1.59s
A sequential scan that sets hint bits on a freshly checkpointed table
with wal_log_hints on runs about 26% faster.
This also bears on the "WAL compression setting after PostgreSQL LZ4
default change" thread, where the order zstd -> lz4 -> pglz is proposed
for what "on" should mean. On master, replaying zstd-compressed images
costs 2.7x what lz4 costs, even though zstd wrote 38% less WAL; with the
context kept, that gap falls to 1.5x.
Cons: a backend that used zstd once holds the 1.3MB until it exits, and
a reader holds a decompression context, which is far smaller.
---- 0002: whole-record compression alongside FPI compression ----
Unchanged in design from v7, plus the documentation that was missing.
When a record is larger than wal_compression_threshold it is compressed
as a single unit rather than each full-page image separately, which wins
whenever the images in one record share content.
On CREATE INDEX over 10M random doubles, with the generator seeded so
the runs are comparable:
zstd 144.8MB -> 116.9MB (-19%)
lz4 189.5MB -> 161.0MB (-15%)
Pros: it reaches redundancy that per-FPI compression cannot see, records
below the threshold are untouched, and every record still decodes on its
own, so nothing about how WAL is read changes. Setting the threshold
above the largest possible record restores today's behaviour.
Cons, both unchanged from v7:
1. Memory. A backend with compression enabled holds two 274300-byte
buffers where it used to hold one array of about the same total size:
the staging buffer reproduces the old allocation, the output buffer
is new. The compressed length has to be known before WAL space is
reserved, so the output has to be materialized somewhere.
2. A low threshold can make WAL bigger, because whole-record compression
displaces per-FPI compression for the records it takes and adds
header to each.
---- 0003: compress records against earlier records (WIP) ----
Still WIP, but no longer blocked on the reader problem.
The motivation is unchanged: half the WAL a pgbench run produces is out
of reach for per-record compression, because the median record is far
too small to compress on its own but compresses well against the records
before it.
What is new in v8 is how a reader starts in the middle of WAL.
Every stream starts over at fixed 4MB boundaries. The writer enforces
that rather than hoping for it: a record that would continue a stream
past the next boundary is refused its reserved position and built again
against a stream that starts over. The check is one comparison against
CurrBytePos under the spinlock that reservation already holds; the
boundary is converted to a byte position outside the lock. It fires
about once per stream per 4MB, and I could not measure its cost.
A reader that wants to start at some LSN then rewinds to the boundary
below it and reads forward, which rebuilds the decompressors, and stops
short of the record it was asked for: feeding a record to its
decompressor twice would leave it in a state its successors were not
compressed against. That is XLogBeginReadStreamed(), and pg_waldump,
pg_walinspect, logical decoding, walsummarizer and pg_rewind all use it.
A record whose stream has not been seen to start over refuses to
decompress rather than decoding whatever the bytes happen to mean.
Why a fixed distance and not the WAL segment: how far a reader rewinds
should not change when a cluster is initialised with a different segment
size, and 64MB segments are not unusual. 4MB divides both 16MB and 64MB
segments, so a boundary is also always a page start. Compression is
insensitive to the value - pgbench emits the same WAL per transaction
to within 2% anywhere between 1MB and 64MB - so it is chosen for the
readers.
Numbers below are from a 16-core machine, pgbench scale 100, fsync off
so that this measures the feature and not the disk. WAL bytes per
transaction and throughput, with the stream count matched to the client
count:
clients streams off streams = clients
1 1720 / 2456 1086 / 2340 -37% WAL, -5% tps
8 701 / 18432 530 / 17326 -24% WAL, -6% tps
32 544 / 43729 433 / 44111 -20% WAL, no cost
64 542 / 46173 448 / 39499 -17% WAL, -12% tps
The 32- and 64-client rows answer the question I could not answer in v7:
the stream lease, which is held across compression and insertion, does
not show up as contention when the insert path is already busy. At 32
clients with 32 streams there is no measurable cost at all.
What does show up is that the stream count has to track concurrency.
Eight streams buy 4% at 32 clients and nothing at 64:
64 clients, streams 0 / 8 / 64 -> 542 / 534 / 448 bytes per txn
Building the third patch with wal_compression_streams = 0 reproduces the
second patch's numbers, so the cost is in using the feature, not in
carrying it.
Two other shapes, WAL volume only:
wide UPDATE of 500k rows 223.9MB -> 154.6MB (-31%)
COPY of 3M rows 65.4MB -> 68.6MB (+5%)
The COPY case is the honest counterexample: those records are large and
already compress well on their own, so the stream adds header and buys
nothing. I do not think that argues against the feature, but it does
argue that turning it on should stay a choice.
Memory, peak RSS with 64 clients writing and then a full pg_waldump over
what they wrote:
streams backend peak pg_waldump peak
0 146.6 MB 3.4 MB
8 150.5 MB 9.0 MB
64 150.5 MB 51.5 MB
The writing side costs about 4MB per backend and does not grow with the
stream count, because a backend keeps one compressor rather than one per
stream. The reading side costs about 0.75MB per stream, and every
reader pays it: the startup process, a walsender doing logical decoding,
pg_waldump.
Costs, as I see them:
1. Throughput, when streams are pushed as high as the client count: 12%
at 64 clients on 16 cores. At and below one stream per core I could
not measure a cost.
2. Memory. 0.75MB per stream for every reader, as above.
3. WAL retention. A replication slot has to keep the WAL back to the
reset boundary below what it needs itself, so up to 4MB more.
The same rewind costs reading, not just retention: a reader that
starts in the middle re-reads up to 4MB to rebuild the decompressors,
and it does so whether or not the WAL it is about to read holds any
streams at all. For readers that start once that is nothing; for
walsummarizer, which starts afresh per summary file, it is up to 4MB
per 16MB summarized. Making the rewind happen only when a record
actually turns out to need it is the obvious answer and I have not
got it working yet.
4. Records that someone reads by LSN without replaying what precedes
them have to stay out of the scheme: the checkpoint records including
XLOG_CHECKPOINT_REDO, XLOG_END_OF_RECOVERY, XLOG_SWITCH and PREPARE.
I could not measure the fsync=on case usefully. The disk I have caps at
82MB/s and repeats of one configuration differed by a factor of two, so
I have no throughput claim there; WAL volume did reproduce, 15-25%
lower with streams, in line with the numbers above.
What I would still like opinions on: whether refusing a reserved
position is an acceptable thing for an insertion path to do, and how to
resolve the tension the numbers above show: the ratio wants roughly one
stream per writing backend, while each stream costs every reader
0.75MB.
wal_compression_streams currently caps at 64, which is already generous
for a reader and far short of the backend count on a busy server.
WDYT?
Best regards, Andrey Borodin.
Re: Compression of bigger WAL records
On Fri, Aug 14, 2026 at 08:30:03PM +0300, Andrey Borodin wrote: > Rebased, v9 is attached. Three of those conflicts were worth more than > a mechanical fixup. I don't really have a ground-breaking opinion about v9-0002 and v9-0003 (sorry!), but I do think that v9-0001 has a lot of value in terms of reusing the [de]compression context. Particularly for WAL replay where we have WAL mostly made of FPIs, this could be a huge deal in terms of performance. Your numbers regarding wal_log_hints are also appealing. So let's get this part done. Now, the patch needs a few adjustments from what I can see. Not that many adjustments, and they should be easy enough to fix. > That commit is also why 0001 matters more than it did. With "on" now > reaching for zstd first, every installation that turns compression on > without naming an algorithm gets the codec that allocates a context per > full-page image, in both directions. v9-0001 should be split into two parts: one for the WAL insert path, and a second one for the xlogreader bits and WAL replay. Both are independently useful on their own. The replay part is much more interesting to me, though, with the startup process replaying everything, so I'd suggest to focus on this part first. The code paths touched are independent, so the order does not really matter, fine. :D +#ifdef USE_ZSTD +/* + * Compression context reused across all block images compressed by this + * backend. zstd keeps its match tables and window in here, roughly 1.3MB at + * the default level, and allocates them on first use. Creating a context per + * call would repeat that allocation for every full-page image. + * + * It is deliberately not freed when wal_compression changes: a backend that + * compressed once is likely to do it again, and the context is only reachable + * from here. + */ +static ZSTD_CCtx *zstd_cctx = NULL; +#endif I suspect that we could cut most of the comment here without losing in readability. + zstd_cctx = ZSTD_createCCtx(); [...] + record->fpi_dctx = ZSTD_createDCtx(); Postgres has a bad history of losing track of memory that's been allocated in a context different than a palloc(), especially when it comes from external libraries, and I don't think we should do in each backend an allocation that's under the control of zstd, or we should at least have some safeguards to clean up that correctly. We have a bunch of facilities in place to make that safer by design, like resowners or memory context callback. Based on how long-lived these context are going to be, the xloginsert.c bit will be living with the process, so we could just leave ZSTD_createDCtx as is. However, XLogReaderState.fpi_dctx is not OK. You should be safe with having a reset memory context callback, linked to the memory context where the XLogReaderState has been allocated. This has to be backend-only. + /* + * Kept across calls so that decompressing a full page image does not + * create and destroy a decompression context every time. Void because + * this header is included where zstd.h is not. + */ + void *fpi_dctx; I think that this is an incorrect design, as it could encourage reusing fpi_dctx across more compression methods than just zstd. Let's just hide that within a USE_ZSTD block with a proper pointer type. Note that wal_compression is user-settable, so one could mix different compression methods on a record-basis. Perhaps your idea of using a void* is better at the end, but please at least mark it with a "zstd" naming and hide it behind a fpi_dctx. - if (ZSTD_isError(len)) - len = -1; /* failure */ + if (zstd_cctx == NULL) + zstd_cctx = ZSTD_createCCtx(); + + if (zstd_cctx == NULL) + len = -1; /* out of memory; store the i This is incorrect. Compression failures are fail-safe, but an allocation failure (OOM) on the context should be a *hard* failure. The replay part makes the good choice, so I'm puzzled as of why you have chosen a safe failure mode here. I can see some APIs available in zstd for more dynamic allocations, like ZSTD_createDCtx_advanced() or some "static" versions that can be given a pre-allocated area, but these are guarded by ZSTDLIB_STATIC_API, aka we cannot use that with a dynamically-linked zstd library. Sad. -- Michael
Re: Compression of bigger WAL records
Hi Michael! Thanks for looking into this! Attached v10 contains only the context-reuse changes, split into replay (0001) and WAL insertion (0002). The reader now owns a ZSTD_DCtx pointer under USE_ZSTD. Backend builds register a reset callback in the reader's memory context, and XLogReaderFree() unregisters it before freeing the context. I also shortened the compression-side comment. We could also avoid this cleanup bookkeeping with a static context, as in 0002. For now we only decompress independent images in one call, with no history to preserve between records. On 6 Oct 2026, at 03:34 UTC, Michael Paquier wrote: > The replay part makes the good choice, so I'm puzzled as of why you > have chosen a safe failure mode here. My reasoning was that the writer can still store an uncompressed image, whereas replay cannot restore a compressed image without the context. I changed this as you suggested, but I still think falling back to an uncompressed image is preferable. We are in a critical section. wal_compression can change during a session, so preparing the workspace outside critical sections is not straightforward. This is also the hardest and most contentious part of the whole-record and streaming compression patches. I'm trying to reuse the FPI compression buffers, but still need twice as much buffer space as before. I haven't found a better approach. Your thoughts on the allocation strategy would be very helpful, even without reviewing those patches. Thank you! Best regards, Andrey Borodin.
Re: Compression of bigger WAL records
On Tue, Oct 06, 2026 at 06:09:38PM +0500, Andrey Borodin wrote: > The reader now owns a ZSTD_DCtx pointer under USE_ZSTD. Backend builds > register a reset callback in the reader's memory context, and > XLogReaderFree() unregisters it before freeing the context. I also > shortened the compression-side comment. The declaration of zstd.h is actually quite invasive. Another possibility would be a forward declaration, like: typedef struct ZSTD_DCtx_s ZSTD_DCtx; That gives type enforcement, but perhaps you had the right idea in v9 where we used a void* pointer. I'd still keep that behind a USE_ZSTD, though, with a zstd-ish naming. I have also been benchmarking the replay path a bit with something like the following based on pgbench_accounts, that gives a fixed number of compressible pages, then run series of VACUUM FULL to generate WAL mostly made of full page records: CREATE TABLE t (aid int, bid int, abalance int, filler char(84)) WITH (autovacuum_enabled = off); INSERT INTO t SELECT i, i / 100000 + 1, 0, '' FROM generate_series(1, 610000) i; VACUUM t; CHECKPOINT; -- series 10k pages (see via pg_waldump -b). VACUUM FULL t; On replay (no fsync, -O2, no asserts, data on tmpfs), I am getting depending on two different hosts a gain of 1.5% and 3.7% in replay time (100 VACUUM FULLs, so 1M pages), which is not as much as you have reported, still that's above noise. For 50 lines of extra code, I'll take that. I would be interested in any scripts you may have, and attempt to reproduce the numbers you have posted. I'll also try some more runs on a third host (much better CPU and disk that I have around, locally, not in the cloud). > We could also avoid this cleanup bookkeeping with a static context, as > in 0002. For now we only decompress independent images in one call, with > no history to preserve between records. With xlogreader.c/h being a pluggable facility for frontend and backend, storing a static state is not really cool IMO. > My reasoning was that the writer can still store an uncompressed image, > whereas replay cannot restore a compressed image without the context. > I changed this as you suggested, but I still think falling back to an > uncompressed image is preferable. We are in a critical section. > > wal_compression can change during a session, so preparing the workspace > outside critical sections is not straightforward. This is also the > hardest and most contentious part of the whole-record and streaming > compression patches. I'm trying to reuse the FPI compression buffers, > but still need twice as much buffer space as before. I haven't found a > better approach. Your thoughts on the allocation strategy would be very > helpful, even without reviewing those patches. Hmm. OK, perhaps just storing it uncompressed is better if the context allocation fails, that's unlikely, still perhaps your alternative is just better than a plain crash. Please let me ponder on this part a bit more. I am attaching a slighly-edited v4 for the time being, which is fine to me code-wise. I am still planning to do a bit more benchmarking with replay times, but my first impression is that the numbers seem good. So, any thoughts or comments? -- Michael
Re: Compression of bigger WAL records
Hi Michael! On 7 Oct 2026, at 08:46 UTC, Michael Paquier wrote: > I would be interested in any scripts you may have, and attempt to > reproduce the numbers you have posted. Attached is a cleaned-up version of the replay script. It creates six million rows with repeat(md5(g::text), 5), checkpoints, and scans the table to log hint-bit FPIs with wal_log_hints=on. Then it crashes the server and measures the "redo done" elapsed time, excluding the end-of-recovery checkpoint. The original runs used -O2, no assertions, fsync=off and shared_buffers=8GB. There's synchronous insert before the immediate shutdown to ensure the scan's WAL is flushed. I found the original logs: 4.34 and 4.14 seconds without the patch and 2.32 and 2.33 with it. lz4 was just an unchanged control: 1.59 seconds in all four runs. The 200MB figure was compressed WAL, not raw page images. I have not remeasured these numbers on v10. Tomas also tested context reuse in the wal_compression default thread [0]: recovery went from 158 to 147 seconds, versus 145 with lz4. ZSTD_createDCtx_internal disappeared from the profile, where it had accounted for about 9% of sampled CPU time. A void pointer under USE_ZSTD is fine with me, and I agree with keeping the context in the reader. Thank you! Best regards, Andrey Borodin. [0] https://www.postgresql.org/message-id/18d632e6-6fa9-42fc-9dda-bad166374aa5@vondra.me
Re: Compression of bigger WAL records
On Wed, Oct 07, 2026 at 09:42:42PM +0500, Andrey Borodin wrote: > I found the original logs: 4.34 and 4.14 seconds without the patch and > 2.32 and 2.33 with it. lz4 was just an unchanged control: 1.59 seconds in > all four runs. The 200MB figure was compressed WAL, not raw page images. > I have not remeasured these numbers on v10. Thanks. I don't expect a difference as on replay we use a single xlogreader, meaning one callback across the board. Averaging 4 runs across multiple environments, I get: - 1.76s for HEAD vs 1.72s for the patch on one machine, 6M rows (EC2 on Debian with libzstd at 1.5.7), or ~2.3%. - 2.52s for HEAD vs 2.44s for the patch on a second machine, 6M rows (laptop, Fedora 44 with libzstd again at 1.5.7) or ~3.2%. - 2.62s for HEAD vs 2.57s for the patch on a third machine, 12M rows (bigger box, Fedora 44, 1.5.7) or ~1.9%. So these numbers are matching my first impressions, and I am compiling with a -O2, no asserts, etc. I have repeated the same test with your v8, in case I was missing something, and my numbers with v8 still match with v10. > Tomas also tested context reuse in the wal_compression default thread > [0]: recovery went from 158 to 147 seconds, versus 145 with lz4. > ZSTD_createDCtx_internal disappeared from the profile, where it had > accounted for about 9% of sampled CPU time. I think that this just points out to the fact that my benchmarking skills deeply suck compared to Tomas's, but I'm still able to see wins anyway in all the places where I am comparing HEAD vs the patch. Applied the recovery part. -- Michael
Re: Compression of bigger WAL records
Hi Michael! On 8 Oct 2026, at 02:04 UTC, Michael Paquier wrote: > Applied the recovery part. Thank you for reviewing, benchmarking and committing it! Interesting difference in our setups is libzstd: my has 1.5.5, while your three machines use 1.5.7. I have not checked yet whether that explains the larger gain here. Attached is v11 with the three remaining patches, rebased on master: 0001 reuses the compression context on WAL insertion. I restored the fallback to an uncompressed image if context allocation fails, rather than risking a PANIC in a critical section. 0002 compresses whole records, allowing lz4 and zstd to share matches across full-page images. It now reuses the committed reader context too. The decompression buffer follows the reader's lifetime, and the reader checks that decompression produces the declared length. 0003 keeps zstd history across records to reach small records that do not compress well on their own. It is still WIP and off by default. Reader memory use and the cost of rewinding to a reset boundary remain the main trade-offs. The decompressors now have context-reset cleanup. The allocation question from my previous mail is still open: 0002 needs two buffers in place of the old per-image workspace. I have not found a way to avoid the extra buffer without complicating the insertion path. Thank you! Best regards, Andrey Borodin.
Re: Compression of bigger WAL records
On Thu, Oct 08, 2026 at 08:53:17AM +0500, Andrey Borodin wrote: > 0001 reuses the compression context on WAL insertion. I restored the > fallback to an uncompressed image if context allocation fails, rather > than risking a PANIC in a critical section. Thanks. Will look at this one next, even if I don't think that I will have much to say. I was wondering about some micro-benchmarking to reduce the amount of noise to zero, even if that would just be testing an equivalent of native zstd... -- Michael
Re: Compression of bigger WAL records
От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
On 8 Oct 2026, at 04:06 UTC, Michael Paquier wrote: > I was wondering about some micro-benchmarking to > reduce the amount of noise to zero Yes, and for the replay results there is one specific thing to isolate: with DYNAMIC_BMI2, ZSTD_initDCtx_internal() does CPU feature detection via CPUID for every new context, in both 1.5.5 and 1.5.7 [0]. Context reuse avoids that as well as palloc/pfree. My benchmark host is a KVM guest, so I wonder whether the cost of that check contributes to the difference. This is still only a hypothesis. My benchmark hosts are unavailable today due to data center maintenance. When they are back, I can measure context creation and library versions. Best regards, Andrey Borodin. [0] https://github.com/facebook/zstd/blob/v1.5.7/lib/decompress/zstd_decompress.c#L252-L275
Re: Compression of bigger WAL records
От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
+/* Compress the assembled record; NULL if that did not pay off */ +static XLogRecData * +XLogCompressRdt(XLogRecData *rdt) That doesn't seem to be the case, it only returns NULL on compression error, incompressible records can get slightly larger with compression? Waldump statistics show decompressed totals, is that expected? Shouldn't we somehow be able to see compressed statistics, maybe ratios? While running I can also see numbers like the following with pg_stat_wal wal_bytes 10 677 687 wal_fpi_bytes 90 204 188 Which seems wrong, as wal_fpi_bytes should be always smaller than wal_bytes?
Re: Compression of bigger WAL records
On Thu, Oct 08, 2026 at 11:20:35AM +0500, Andrey Borodin wrote: > This is still only a hypothesis. My benchmark hosts are unavailable today > due to data center maintenance. When they are back, I can measure context > creation and library versions. Thanks. I have been playing with some of my cases and quickly measured a 6% improvement of my VACUUM FULL workload from upthread, and a lot less CPU getting used. In short, applied the WAL insert part. -- Michael
Re: Compression of bigger WAL records
Hi Michael, Zsolt! On 14 Oct 2026, Michael Paquier wrote: > In short, applied the WAL insert part. Thank you! Attached is v12: whole-record compression (0001), a separate pg_walinspect update (0002), and WIP streams (0003). Context reuse removes per-image setup cost. These patches target redundancy between images in a record and between successive records. Zsolt, you are right about incompressible records. 0001 now falls back unless compression saves space including its header. Streams in 0003 still allow individual records to grow to preserve history for later records. Following Nikolay Samokhvalov's off-list review [0], FPI-only settings no longer allocate the large whole-record workspaces. Those are prepared outside critical sections only for settings that can use them. A writer also keeps one stream compressor across lease changes, resetting it when acquiring a different slot. My earlier one-compressor-per-writer description was not true of v11. On the statistics question raised by both Zsolt and Nikolay, pg_waldump and pg_walinspect now expose physical sizes separately from decoded sizes. I kept wal_fpi_bytes as image bytes before whole-record compression and documented that it can exceed physical wal_bytes. There is no exact way to split a jointly compressed payload into image and non-image bytes. 0003 is still WIP: reader memory and the cost of rewinding to a stream reset boundary remain open trade-offs. Best regards, Andrey Borodin. [0] https://github.com/NikolayS/postgres/issues/99#issuecomment-6068279914
Re: Compression of bigger WAL records
От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
- decoded = XLogReadRecordAlloc(state,
- total_len,
- false /* allow_oversized */ );
+ if (have_decomp_len)
+ decoded = XLogReadRecordAlloc(state,
+ total_len_decomp,
+ false /* allow_oversized */ );
+
Won't this result in a performance regression with the additional
blocks when the header crosses multiple pages?
+/* Read length of a record, accounting for possible compression */
+static uint32
+XLogGetRecordTotalLen(XLogRecord *record)
+{
+ if (record->xl_info & XLR_COMPRESSED)
Shouldn't this flag be unset after decompression? Or alternatively
some existing code needs fixing, for example replorigin_identity
doesn't do any masking (but above it replorigin_desc does, so that by
itself seems somewhat inconsistent)
And: it seems like that the patchset tries to compress incompressible
FPI records twice (first record, then whole page, failing both times)?
Re: Compression of bigger WAL records
Hi Zsolt! On 26 Oct 2026, Zsolt Parragi wrote: > Won't this result in a performance regression with the additional > blocks when the header crosses multiple pages? v12 stops nonblocking read-ahead at a split header even with free decode space. In v13 it assembles the record and retries allocation from the decode ring. If the ring is full, it yields without advancing NextRecPtr. > Shouldn't this flag be unset after decompression? Agreed. With streams enabled, replication origin SET and DROP records are reported as UNKNOWN. v13 clears XLR_COMPRESSED after decompression. The new test checks both record names and that compression was used. pg_waldump still displays physical lengths when they differ from decoded lengths. > And: it seems like that the patchset tries to compress incompressible > FPI records twice (first record, then whole page, failing both times)? I removed the second codec pass in 0001. Thank you! Best regards, Andrey Borodin.
Re: Compression of bigger WAL records
От:
Tomas Vondra <tomas@vondra.me>
Дата:
On 11/8/26 08:49, Andrey Borodin wrote: > Hi Zsolt! > > On 26 Oct 2026, Zsolt Parragi wrote: >> Won't this result in a performance regression with the additional >> blocks when the header crosses multiple pages? > > v12 stops nonblocking read-ahead at a split header even with free decode > space. In v13 it assembles the record and retries allocation from the > decode ring. If the ring is full, it yields without advancing > NextRecPtr. > >> Shouldn't this flag be unset after decompression? > > Agreed. With streams enabled, replication origin SET and DROP records > are reported as UNKNOWN. v13 clears XLR_COMPRESSED after decompression. > The new test checks both record names and that compression was used. > pg_waldump still displays physical lengths when they differ from decoded > lengths. > > >> And: it seems like that the patchset tries to compress incompressible >> FPI records twice (first record, then whole page, failing both times)? > > I removed the second codec pass in 0001. > > Thank you! > > > Best regards, Andrey Borodin. Hi, The patches need a rebase (just minor bitrot). I've only quickly skimmed the patches, but I do have a couple questions: 1) Are there any motivating benchmarks, quantifying the benefits on "average" and "best-case" workloads / datasets. Is the point a better compression ratio, lower CPU usage, or something else? What benefits should we expect for cases plausible in real world? 2) wal_compression_threshold - I kinda dislike this GUC name, because it implies it's about "wal compression" in general, and completely hides that it's about whole-record compression. 3) The docs say this in a couple places: Total amount of WAL full page images in bytes, after per-image compression but before whole-record compression. This can exceed wal_bytes when whole records are compressed: their compressed payload cannot be split into image and non-image portions. I really don't understand the point of this. I mean, what does that tell me? It's not the "raw" size of WAL, because it's already compressed, but it's also not really the "compressed" size, because we're going to try the whole-record compression. How is this useful? I'm puzzled. 4) In another place, the docs say this: Lowering this value does not simply compress more. A record taken by whole-record compression no longer has its page images compressed individually. The compressed record, including its header, is used only if smaller than the uncompressed record. Otherwise the record is written uncompressed, without retrying per-image compression. The result is not compared with per-image compression. A lower threshold can therefore produce more WAL than per-image compression. Setting it above the size of the largest possible WAL record disables whole-record compression entirely, leaving the page-image compression that performed before this setting existed. That seems rather vague. Like, how would I know how to pick a good value? What are good values? What are the min/max values? FWIW I don't think we should be adding infinite number of knobs - if the 512B default is good, then lets use that, and maybe have a #define to override that, same as we have TOAST_TUPLE_THRESHOLD. regards -- Tomas Vondra