Use WALReadFromBuffers in more places
Use WALReadFromBuffers in more places
Hi, Commit 91f2cae7a4e that introduced WALReadFromBuffers only used it for physical walsenders. It can also be used in more places benefitting logical walsenders, backends running pg_walinspect and logical decoding functions if the WAL is available in WAL buffers. I'm attaching a 0001 patch for this. While at it, I've also added a test module in 0002 patch to demonstrate 2 things: 1) how the caller can ensure the requested WAL is fully copied to WAL buffers using WaitXLogInsertionsToFinish before reading from WAL buffers. 2) how one can implement an xlogreader page_read callback to read unflushed/not-yet-flushed WAL directly from WAL buffers. FWIW, a separate test module to explicitly test the new function is suggested here - https://www.postgresql.org/message-id/CAFiTN-sE7CJn-ZFj%2B-0Wv6TNytv_fp4n%2BeCszspxJ3mt77t5ig%40mail.gmail.com. Please have a look at the attached patches. I will register this for the next commit fest. -- Bharath Rupireddy PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Use WALReadFromBuffers in more places
От:
Jingtang Zhang <mrdrivingduck@gmail.com>
Дата:
Hi, Bharath. I've been testing this. It's cool. Is there any way we could
monitor the hit rate about directly reading from WAL buffers by exporting
to some views?
---
Regards, Jingtang
Re: Use WALReadFromBuffers in more places
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
On Wed, May 8, 2024 at 9:51 AM Jingtang Zhang wrote: > > Hi, Bharath. I've been testing this. It's cool. Is there any way we could > monitor the hit rate about directly reading from WAL buffers by exporting > to some views? Thanks for looking into this. I used purpose-built patches for verifying the WAL buffers hit ratio, please check USE-ON-HEAD-Collect-WAL-read-from-file-stats.txt and USE-ON-PATCH-Collect-WAL-read-from-buffers-and-file-stats.txt at https://www.postgresql.org/message-id/CALj2ACU9cfAcfVsGwUqXMace_7rfSBJ7%2BhXVJfVV1jnspTDGHQ%40mail.gmail.com. In the long run, it's better to extend what's proposed in the thread https://www.postgresql.org/message-id/CALj2ACU_f5_c8F%2BxyNR4HURjG%3DJziiz07wCpQc%3DAqAJUFh7%2B8w%40mail.gmail.com. I haven't had a chance to dive deep into that thread yet, but a quick glance over v8 patch tells me that it hasn't yet implemented the idea of collecting WAL read stats for both walsenders and the backends reading WAL. If that's done, we can extend it for WAL read from WAL buffers. -- Bharath Rupireddy PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Use WALReadFromBuffers in more places
От:
Nitin Jadhav <nitinjadhavpostgres@gmail.com>
Дата:
Hi Bharath, I spent some time examining the patch. Here are my observations from the review. - I believe there’s no need for an extra variable ‘nbytes’ in this context. We can repurpose the ‘count’ variable for the same function. If necessary, we might think about renaming ‘count’ to ‘nbytes’. - The operations performed by logical_read_xlog_page() and read_local_xlog_page_guts() are identical. It might be beneficial to create a shared function to minimize code repetition. Best Regards, Nitin Jadhav Azure Database for PostgreSQL Microsoft On Mon, May 13, 2024 at 12:17 PM Bharath Rupireddy wrote: > > On Wed, May 8, 2024 at 9:51 AM Jingtang Zhang wrote: > > > > Hi, Bharath. I've been testing this. It's cool. Is there any way we could > > monitor the hit rate about directly reading from WAL buffers by exporting > > to some views? > > Thanks for looking into this. I used purpose-built patches for > verifying the WAL buffers hit ratio, please check > USE-ON-HEAD-Collect-WAL-read-from-file-stats.txt and > USE-ON-PATCH-Collect-WAL-read-from-buffers-and-file-stats.txt at > https://www.postgresql.org/message-id/CALj2ACU9cfAcfVsGwUqXMace_7rfSBJ7%2BhXVJfVV1jnspTDGHQ%40mail.gmail.com. > In the long run, it's better to extend what's proposed in the thread > https://www.postgresql.org/message-id/CALj2ACU_f5_c8F%2BxyNR4HURjG%3DJziiz07wCpQc%3DAqAJUFh7%2B8w%40mail.gmail.com. > I haven't had a chance to dive deep into that thread yet, but a quick > glance over v8 patch tells me that it hasn't yet implemented the idea > of collecting WAL read stats for both walsenders and the backends > reading WAL. If that's done, we can extend it for WAL read from WAL > buffers. > > -- > Bharath Rupireddy > PostgreSQL Contributors Team > RDS Open Source Databases > Amazon Web Services: https://aws.amazon.com > >
Re: Use WALReadFromBuffers in more places
Hi,
On Sat, Jun 8, 2024 at 5:24 PM Nitin Jadhav <nitinjadhavpostgres@gmail.com> wrote:
>
> I spent some time examining the patch. Here are my observations from the review.
Thanks.
> - I believe there’s no need for an extra variable ‘nbytes’ in this
> context. We can repurpose the ‘count’ variable for the same function.
> If necessary, we might think about renaming ‘count’ to ‘nbytes’.
'count' variable can't be altered once determined as the page_read callbacks need to return the total number of bytes read. However, I ended up removing 'nbytes' like in the attached v2 patch.
> - The operations performed by logical_read_xlog_page() and
> read_local_xlog_page_guts() are identical. It might be beneficial to
> create a shared function to minimize code repetition.
IMO, creating another function to just wrap two other functions doesn't seem good to me.
I attached v2 patches for further review. No changes in 0002 patch.
--
Bharath Rupireddy
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
On Sat, Jun 8, 2024 at 5:24 PM Nitin Jadhav <nitinjadhavpostgres@gmail.com> wrote:
>
> I spent some time examining the patch. Here are my observations from the review.
Thanks.
> - I believe there’s no need for an extra variable ‘nbytes’ in this
> context. We can repurpose the ‘count’ variable for the same function.
> If necessary, we might think about renaming ‘count’ to ‘nbytes’.
'count' variable can't be altered once determined as the page_read callbacks need to return the total number of bytes read. However, I ended up removing 'nbytes' like in the attached v2 patch.
> - The operations performed by logical_read_xlog_page() and
> read_local_xlog_page_guts() are identical. It might be beneficial to
> create a shared function to minimize code repetition.
IMO, creating another function to just wrap two other functions doesn't seem good to me.
I attached v2 patches for further review. No changes in 0002 patch.
--
Bharath Rupireddy
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
Re: Use WALReadFromBuffers in more places
От:
Jingtang Zhang <mrdrivingduck@gmail.com>
Дата:
Hi all.
I've been back to this patch for a while recently. I witness that if a WAL
writer works fast, the already flushed WAL buffers will be zeroed out and
re-initialized for future use by AdvanceXLInsertBuffer in
XLogBackgroundFlush, so that WALReadFromBuffers will miss even though the
space of WAL buffer is enough. It is much more unfriendly for logical
walsenders than physical walsenders, because logical ones consume WAL
slower than physical ones due to the extra decoding phase. Seems that the aim
of AdvanceXLInsertBuffer in WAL writer contradicts with our reading from
WAL buffer. Any thoughts?
Re: Use WALReadFromBuffers in more places
Hi, On Tue, Oct 15, 2024 at 1:22 AM Jingtang Zhang wrote: > > I've been back to this patch for a while recently. I witness that if a WAL > writer works fast, the already flushed WAL buffers will be zeroed out and > re-initialized for future use by AdvanceXLInsertBuffer in > XLogBackgroundFlush, so that WALReadFromBuffers will miss even though the > space of WAL buffer is enough. It is much more unfriendly for logical > walsenders than physical walsenders, because logical ones consume WAL > slower than physical ones due to the extra decoding phase. Seems that the aim > of AdvanceXLInsertBuffer in WAL writer contradicts with our reading from > WAL buffer. Any thoughts? Thanks for looking at this. Yes, the WAL writers can zero out flushed buffers before WALReadFromBuffers gets to them. However, WALReadFromBuffers was intentionally designed as an opportunistic optimization - it's a "try this first, quickly" approach before falling back to reading from WAL files. The no-locks design ensures it never gets in the way of backends generating WAL, which is critical for overall system performance. I rebased and attached the v3 patch. I discarded the test extension patch that demonstrated WALReadFromBuffers' behavior (i.e., waiting for WAL to be fully copied to WAL buffers with WaitXLogInsertionsToFinish), as I believe the comment at the top of WALReadFromBuffers is sufficient documentation. I can reintroduce the test extension if there's interest. Thoughts? -- Bharath Rupireddy PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Use WALReadFromBuffers in more places
От:
Rahila Syed <rahilasyed90@gmail.com>
Дата:
Hi Bharath,
Hi,
Commit 91f2cae7a4e that introduced WALReadFromBuffers only used it for
physical walsenders. It can also be used in more places benefitting
logical walsenders, backends running pg_walinspect and logical
decoding functions if the WAL is available in WAL buffers. I'm
attaching a 0001 patch for this.
Thank you for working on this. It seems like a useful optimization. Do you have any information
on how much this improves the performance of the new callers of WALReadFromBuffers?
on how much this improves the performance of the new callers of WALReadFromBuffers?
Regarding the v3 version of the patch, do you also intend to include other callers of WALRead,
such as walsummarizer.c and pg_waldump.c?
In WALReadFromBuffers, the buffer scan currently stops when it encounters a buffer that
doesn't have the needed WAL page. However, it's possible to continue scanning past the
missing page and find other relevant pages further along. By keeping track of which pages
are missing, we could read only those specific pages from files, instead of reading everything
after the first missing page. I am wondering if this was taken into account during the design
of the function.
Thank you,
missing page and find other relevant pages further along. By keeping track of which pages
are missing, we could read only those specific pages from files, instead of reading everything
after the first missing page. I am wondering if this was taken into account during the design
of the function.
Thank you,
Rahila Syed
Re: Use WALReadFromBuffers in more places
От:
Jingtang Zhang <mrdrivingduck@gmail.com>
Дата:
Hi~ > Thanks for looking at this. Yes, the WAL writers can zero out flushed > buffers before WALReadFromBuffers gets to them. However, > WALReadFromBuffers was intentionally designed as an opportunistic > optimization - it's a "try this first, quickly" approach before > falling back to reading from WAL files. The no-locks design ensures it > never gets in the way of backends generating WAL, which is critical > for overall system performance. Yes, it is actually an interesting thing, beyond current topic. Since we are using buffered I/O, even though we cannot read from WAL buffer due to the opportunistic AdvanceXLInsertBuffer by WAL writer, later WALRead may still find the page inside OS page cache, with high probability, because the page has just been written out. So WALRead will be fast, too. But if we are moving forward to direct I/O some day in the future, the cost of WALReadFromBuffers and WALRead might be obvious. Maybe the opportunistic WAL buffer initialization could keep a small ratio of old pages inside WAL buffer so these pages can still be hit by WALReadFromBuffers. > I rebased and attached the v3 patch. The v3 patch LGTM. — Regards, Jingtang Alibaba Cloud
Re: Use WALReadFromBuffers in more places
От:
Jeff Davis <pgsql@j-davis.com>
Дата:
On Sat, 2025-09-13 at 22:04 -0700, Bharath Rupireddy wrote: > Thanks for looking at this. Yes, the WAL writers can zero out flushed > buffers before WALReadFromBuffers gets to them. However, > WALReadFromBuffers was intentionally designed as an opportunistic > optimization - it's a "try this first, quickly" approach before > falling back to reading from WAL files. IIRC, one motivation (perhaps the primary motivation?) was to make it possible to read buffers before they are flushed. It was always possible to read already-flushed buffers. The benefit of reading unflushed buffers is that we can replicate the WAL sooner (though it can't be replayed until the primary flushes it). Is that right? Regards, Jeff Davis
Re: Use WALReadFromBuffers in more places
От:
Rahila Syed <rahilasyed90@gmail.com>
Дата:
Hi,
On Mon, Sep 22, 2025 at 8:56 PM Jeff Davis <pgsql@j-davis.com> wrote:
On Sat, 2025-09-13 at 22:04 -0700, Bharath Rupireddy wrote:
> Thanks for looking at this. Yes, the WAL writers can zero out flushed
> buffers before WALReadFromBuffers gets to them. However,
> WALReadFromBuffers was intentionally designed as an opportunistic
> optimization - it's a "try this first, quickly" approach before
> falling back to reading from WAL files.
IIRC, one motivation (perhaps the primary motivation?) was to make it
possible to read buffers before they are flushed. It was always
possible to read already-flushed buffers.
The benefit of reading unflushed buffers is that we can replicate the
WAL sooner (though it can't be replayed until the primary flushes it).
Is that right?
I'm not certain about the primary motivation, but as it stands, WALReadFromBuffers only reads WAL records present in buffers up to the flush pointer. This is because XLogSendPhysical currently sends records only up to the flush pointer, not beyond.
I am currently testing a patch developed by Melih Mutlu that implements the functionality you described, sending unflushed buffers during physical replication. After some tuning, the patch has shown a 5 percent improvement in TPS for synchronous replication with remote_write. I am working on further improving the patch before sharing it on the hackers mailing list.
Thank you,
Rahila Syed
Re: Use WALReadFromBuffers in more places
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Mon, Sep 22, 2025 at 8:26 AM Jeff Davis wrote: > > On Sat, 2025-09-13 at 22:04 -0700, Bharath Rupireddy wrote: > > Thanks for looking at this. Yes, the WAL writers can zero out flushed > > buffers before WALReadFromBuffers gets to them. However, > > WALReadFromBuffers was intentionally designed as an opportunistic > > optimization - it's a "try this first, quickly" approach before > > falling back to reading from WAL files. > > IIRC, one motivation (perhaps the primary motivation?) was to make it > possible to read buffers before they are flushed. It was always > possible to read already-flushed buffers. > > The benefit of reading unflushed buffers is that we can replicate the > WAL sooner (though it can't be replayed until the primary flushes it). > Is that right? Right. Reading unflushed WAL buffers for replication was one of the motivations. But, in general, WALReadFromBuffers has more benefits since it lets WAL buffers act as a cache for reads, avoiding the need to re-read WAL from disk for (both physical and logical) replication. For example, it makes the use of direct I/O for WAL more realistic and can provide significant performance benefits [1]. [1] https://www.postgresql.org/message-id/20230114203403.4zpg72fw2qb34awf%40awork3.anarazel.de -- Bharath Rupireddy PostgreSQL Contributors Team RDS Open Source Databases Amazon Web Services: https://aws.amazon.com
Re: Use WALReadFromBuffers in more places
От:
Jeff Davis <pgsql@j-davis.com>
Дата:
On Wed, 2025-09-24 at 07:26 -0700, Bharath Rupireddy wrote: > Right. Reading unflushed WAL buffers for replication was one of the > motivations. But, in general, WALReadFromBuffers has more benefits > since it lets WAL buffers act as a cache for reads, avoiding the need > to re-read WAL from disk for (both physical and logical) replication. > For example, it makes the use of direct I/O for WAL more realistic > and > can provide significant performance benefits [1]. Is it possible to do a POC that shows the potential benefit, or are we still too far away? Regards, Jeff Davis
Re: Use WALReadFromBuffers in more places
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi,
On Wed, Sep 24, 2025 at 11:27 AM Jeff Davis <pgsql@j-davis.com> wrote:
>
> On Wed, 2025-09-24 at 07:26 -0700, Bharath Rupireddy wrote:
> > Right. Reading unflushed WAL buffers for replication was one of the
> > motivations. But, in general, WALReadFromBuffers has more benefits
> > since it lets WAL buffers act as a cache for reads, avoiding the need
> > to re-read WAL from disk for (both physical and logical) replication.
> > For example, it makes the use of direct I/O for WAL more realistic
> > and
> > can provide significant performance benefits [1].
>
> Is it possible to do a POC that shows the potential benefit, or are we
> still too far away?
Thanks for looking into this. I did performance analysis with WAL directo I/O to see how reading from WAL buffers affects walsenders: https://www.postgresql.org/message-id/CALj2ACV6rS%2B7iZx5%2BoAvyXJaN4AG-djAQeM1mrM%3DYSDkVrUs7g%40mail.gmail.com. Following is from that thread. Please let me know if you have any specific cases in mind. I'm happy to run the same test for logical replication.
It helps WAL DIO; since there's no OS
page cache, using WAL buffers as read cache helps a lot. It is clearly
evident from my experiment with WAL DIO patch [1], see the results [2]
and attached graph. As expected, WAL DIO brings down the TPS, whereas
WAL buffers read i.e. this patch brings it up.
[2] Test case is an insert pgbench workload.
clients HEAD | WAL DIO | WAL DIO & WAL BUFFERS READ | WAL BUFFERS READ
1 1404 1070 1424 1375
2 1487 796 1454 1517
4 3064 1743 3011 3019
8 6114 3556 6026 5954
16 11560 7051 12216 12132
32 23181 13079 23449 23561
64 43607 26983 43997 45636
128 80723 45169 81515 81911
256 110925 90185 107332 114046
512 119354 109817 110287 117506
768 112435 105795 106853 111605
1024 107554 105541 105942 109370
2048 88552 79024 80699 90555
4096 61323 54814 58704 61743
--
Bharath Rupireddy
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
On Wed, Sep 24, 2025 at 11:27 AM Jeff Davis <pgsql@j-davis.com> wrote:
>
> On Wed, 2025-09-24 at 07:26 -0700, Bharath Rupireddy wrote:
> > Right. Reading unflushed WAL buffers for replication was one of the
> > motivations. But, in general, WALReadFromBuffers has more benefits
> > since it lets WAL buffers act as a cache for reads, avoiding the need
> > to re-read WAL from disk for (both physical and logical) replication.
> > For example, it makes the use of direct I/O for WAL more realistic
> > and
> > can provide significant performance benefits [1].
>
> Is it possible to do a POC that shows the potential benefit, or are we
> still too far away?
Thanks for looking into this. I did performance analysis with WAL directo I/O to see how reading from WAL buffers affects walsenders: https://www.postgresql.org/message-id/CALj2ACV6rS%2B7iZx5%2BoAvyXJaN4AG-djAQeM1mrM%3DYSDkVrUs7g%40mail.gmail.com. Following is from that thread. Please let me know if you have any specific cases in mind. I'm happy to run the same test for logical replication.
It helps WAL DIO; since there's no OS
page cache, using WAL buffers as read cache helps a lot. It is clearly
evident from my experiment with WAL DIO patch [1], see the results [2]
and attached graph. As expected, WAL DIO brings down the TPS, whereas
WAL buffers read i.e. this patch brings it up.
[2] Test case is an insert pgbench workload.
clients HEAD | WAL DIO | WAL DIO & WAL BUFFERS READ | WAL BUFFERS READ
1 1404 1070 1424 1375
2 1487 796 1454 1517
4 3064 1743 3011 3019
8 6114 3556 6026 5954
16 11560 7051 12216 12132
32 23181 13079 23449 23561
64 43607 26983 43997 45636
128 80723 45169 81515 81911
256 110925 90185 107332 114046
512 119354 109817 110287 117506
768 112435 105795 106853 111605
1024 107554 105541 105942 109370
2048 88552 79024 80699 90555
4096 61323 54814 58704 61743
--
Bharath Rupireddy
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
Re: Use WALReadFromBuffers in more places
On Wed, Sep 24, 2025 at 12:32 PM Bharath Rupireddy wrote: > > > On Wed, 2025-09-24 at 07:26 -0700, Bharath Rupireddy wrote: > > > Right. Reading unflushed WAL buffers for replication was one of the > > > motivations. But, in general, WALReadFromBuffers has more benefits > > > since it lets WAL buffers act as a cache for reads, avoiding the need > > > to re-read WAL from disk for (both physical and logical) replication. > > > For example, it makes the use of direct I/O for WAL more realistic > > > and > > > can provide significant performance benefits [1]. > > Thanks for looking into this. I did performance analysis with WAL directo I/O to see how reading from WAL buffers affects walsenders: https://www.postgresql.org/message-id/CALj2ACV6rS%2B7iZx5%2BoAvyXJaN4AG-djAQeM1mrM%3DYSDkVrUs7g%40mail.gmail.com. Following is from that thread. Please let me know if you have any specific cases in mind. I'm happy to run the same test for logical replication. > > It helps WAL DIO; since there's no OS > page cache, using WAL buffers as read cache helps a lot. It is clearly > evident from my experiment with WAL DIO patch [1], see the results [2] > and attached graph. As expected, WAL DIO brings down the TPS, whereas > WAL buffers read i.e. this patch brings it up. > > [2] Test case is an insert pgbench workload. > clients HEAD | WAL DIO | WAL DIO & WAL BUFFERS READ | WAL BUFFERS READ > 1 1404 1070 1424 1375 > 2 1487 796 1454 1517 > 4 3064 1743 3011 3019 > 8 6114 3556 6026 5954 > 16 11560 7051 12216 12132 > 32 23181 13079 23449 23561 > 64 43607 26983 43997 45636 > 128 80723 45169 81515 81911 > 256 110925 90185 107332 114046 > 512 119354 109817 110287 117506 > 768 112435 105795 106853 111605 > 1024 107554 105541 105942 109370 > 2048 88552 79024 80699 90555 > 4096 61323 54814 58704 61743 Thank you all for reviewing this. Please find the attached rebased patch for further review. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Use WALReadFromBuffers in more places
On Mon, Aug 17, 2026 at 04:30:00PM -0700, Bharath Rupireddy wrote: > Test setup: two Amazon EC2 r7i.4xlarge instances (16 vCPU, 128 GB RAM) > in the same AZ, one publisher and one subscriber, pg_wal on a > dedicated gp3 disk. Publisher runs an insert-only pgbench workload (16 > clients) into a two-column table (bigint, text), each insert writing > 400 bytes, no indexes. Subscriber tails closely (lag in KB) so the WAL > the walsender reads is still in the 2 GB wal_buffers. wal_buffers=2GB, > debug_io_direct='wal'. > > Metrics: TPS is publisher pgbench insert throughput. Walsender read MB > is read_bytes from pg_stat_io for the walsender (bytes read through > WALRead()). WAL-disk reads and WAL-disk writes are peak throughput > from iostat on the pg_wal disk. Replication lag is > pg_stat_replication, sampled every 5 seconds, taken as the max over > the run. Worth noting something in the patch: read_local_xlog_page_guts() is touched, being called in read_local_xlog_page(). read_local_xlog_page() is used in much more contexts than just the logical paths and pg_walinspect you are referring to at the top of this thread. Repack workers, 2PC code, WAL summarizer have also references to it in their XL_ROUTINE(). This uses pgbench for the WAL inserts. For the logical path, at least, could a workload based on logical WAL messages generated by pg_logical_emit_message() be a fancier (aka less noisy) workload to use to compare the modes of debug_io_direct for the scope of this patch? I have to admit that I would be a bit stressed with changing the three code paths for logical_read_xlog_page(), XLogSendPhysical() and read_local_xlog_page_guts() all at once.. Checking things separately seems like a more safer approach, because less risky in terms of potential reverts of one part of the other if the buildfarm detects that something is wrong, particularly on slower machines where race condition patterns show up more easily. My 2c. -- Michael
Re: Use WALReadFromBuffers in more places
Hi,
On Wed, Sep 2, 2026 at 9:08 PM Michael Paquier wrote:
>
> On Mon, Aug 17, 2026 at 04:30:00PM -0700, Bharath Rupireddy wrote:
> > Test setup: two Amazon EC2 r7i.4xlarge instances (16 vCPU, 128 GB RAM)
> > in the same AZ, one publisher and one subscriber, pg_wal on a
> > dedicated gp3 disk. Publisher runs an insert-only pgbench workload (16
> > clients) into a two-column table (bigint, text), each insert writing
> > 400 bytes, no indexes. Subscriber tails closely (lag in KB) so the WAL
> > the walsender reads is still in the 2 GB wal_buffers. wal_buffers=2GB,
> > debug_io_direct='wal'.
> >
> > Metrics: TPS is publisher pgbench insert throughput. Walsender read MB
> > is read_bytes from pg_stat_io for the walsender (bytes read through
> > WALRead()). WAL-disk reads and WAL-disk writes are peak throughput
> > from iostat on the pg_wal disk. Replication lag is
> > pg_stat_replication, sampled every 5 seconds, taken as the max over
> > the run.
>
> Worth noting something in the patch: read_local_xlog_page_guts() is
> touched, being called in read_local_xlog_page().
> read_local_xlog_page() is used in much more contexts than just the
> logical paths and pg_walinspect you are referring to at the top of
> this thread. Repack workers, 2PC code, WAL summarizer have also
> references to it in their XL_ROUTINE().
Yes, repack and 2PC are covered by the 0002 patch. But I haven't yet
used it for the WAL summarizer. Would it be okay if I do some testing
with the WAL summarizer and propose it as a follow-up patch?
> This uses pgbench for the WAL inserts. For the logical path, at
> least, could a workload based on logical WAL messages generated by
> pg_logical_emit_message() be a fancier (aka less noisy) workload to
> use to compare the modes of debug_io_direct for the scope of this
> patch?
Thanks for the suggestion. Done. I used pg_logical_emit_message() to
emit the WAL plus pg_recvlogical to let a walsender read it, and here
are the results [1].
With WAL direct IO on, the patch reduces the walsender's WAL reads
from 1.0 GB to 1.6 MB per run, removing 14.5 MB/s of physical disk
reads and improving publisher throughput by about 17% (6,393 to 7,489
TPS). The throughput gain comes from eliminating the WAL read IO on
disk, so WAL writes no longer compete with WAL reads for disk IO. With
WAL direct IO off, the same reads are eliminated at the syscall level
with no throughput change, so it never regresses.
# build WAL direct IO TPS WAL generated MB walsender
read MB WAL-disk reads WAL-disk writes replication lag
1 HEAD on 6,393 511 1,055
14.5 MB/s 9.0 MB/s 0 KB
2 PATCHED on 7,489 598 1.6
0.01 MB/s 10.6 MB/s 0 KB
3 HEAD off 7,347 587 1,229
0 10.4 MB/s 0 KB
4 PATCHED off 7,352 587 1.8
0 10.4 MB/s 0 KB
> I have to admit that I would be a bit stressed with changing the three
> code paths for logical_read_xlog_page(), XLogSendPhysical() and
> read_local_xlog_page_guts() all at once.. Checking things separately
> seems like a more safer approach, because less risky in terms of
> potential reverts of one part of the other if the buildfarm detects
> that something is wrong, particularly on slower machines where race
> condition patterns show up more easily. My 2c.
The physical walsender change was supposed to be purely mechanical,
but upon thinking more, I would rather not touch that part. Also, the
way I had it, it had a bug where it ignored the retry part. Sorry
about that.
I split the patches into two. 0001 is for logical walsender, 0002 is
for local WAL reads. 0003 adds a TAP test using an injection point for
the segment boundary issue handled in both patches (I don't intend to
get this committed unless anyone thinks otherwise). A read fully
satisfied from WAL buffers can leave the segment file open on the
wrong segment. This is handled by closing the open segment after such
a read so the next file read reopens the correct one.
PS: There is an opportunity to deduplicate with a wrapper function on
the code that 0001 and 0002 add for WALReadFromBuffers()+WALRead(). I
chose not to add that wrapper, just because we cannot reuse it in the
physical walsenders, defeating the purpose of deduplication. I am open
to thoughts on this.
Please find the attached v6 patches.
[1]
# GUCs
shared_buffers = 8GB
max_wal_size = 64GB
synchronous_commit = on
wal_buffers = 16MB
# Session 1
psql -c "SELECT pg_create_logical_replication_slot('bench','test_decoding');"
printf "SELECT pg_logical_emit_message(true, 'bench', repeat('x',
350));\n" > emit.sql
pgbench -n -f emit.sql -c 16 -j 16 -T 180 postgres
pg_recvlogical -p 5432 -d postgres --slot bench --start -f /dev/null &
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Use WALReadFromBuffers in more places
Hi,
On Thu, Sep 3, 2026 at 10:41 PM Michael Paquier wrote:
>
> + }
> + else if (state->seg.ws_file >= 0)
> + {
> + /*
> + * A read fully satisfied from WAL buffers skips WALRead(), which is
> + * where ws_file is closed and reopened as the reader crosses
> + * segments. So a buffer-only read never notices the segment change.
> + * ws_file stays open on the old segment while ReadPageInternal()
> + * advances ws_segno. For example, when the first page of segment 2
> + * comes from buffers, ws_segno becomes 2 but ws_file is still open on
> + * segment 1. A later read of segment 2 that falls back to the file
> + * reuses the stale descriptor, since WALRead() decides whether to
> + * reopen from ws_segno (already 2) rather than the open file. It
> + * reads segment 1 and returns the wrong segment's WAL, seen during
> + * decoding as an "unexpected pageaddr" error. Close the segment after
> + * a buffer-only read so the next file read reopens the correct one.
> + */
> + state->routine.segment_close(state);
> + }
>
> Cannot that become wasteful for the logical path when reading pages
> from the same segment repeatedly causing opening and closing of the
> same file? That sounds relevant to me if we are still attempting
> to read from the same segment, depending on wal_buffers whose default
> is at 4MB. Something like an extra check based on XLByteInSeg() may
> be adapted, using the targetPagePtr, where we could close the segment
> only if we target a page not on the same segment?
>
> The same argument applies to both v6-0001 and v6-0002, both
> unconditionally closing a segment after completing a read from buffer
> or even not completing a read from buffers and completing the read
> with an extra WALRead().
Ah, yes, that is not acceptable. Nice catch! Fixed it by closing the
old segment only when the first WAL page of the new segment is fully
read from buffers.
> + Assert(rbytes == count);
>
> This assert feels redundant due to the other checks done above.
> Applies to patches 0001 and 0002.
Removed.
Please find the attached v7 patches.
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Use WALReadFromBuffers in more places
От:
Kirill Reshke <reshkekirill@gmail.com>
Дата:
On Tue, 8 Sept 2026 at 01:57, Bharath Rupireddy
wrote:
>
> Hi,
>
> On Thu, Sep 3, 2026 at 10:41 PM Michael Paquier wrote:
> >
> > + }
> > + else if (state->seg.ws_file >= 0)
> > + {
> > + /*
> > + * A read fully satisfied from WAL buffers skips WALRead(), which is
> > + * where ws_file is closed and reopened as the reader crosses
> > + * segments. So a buffer-only read never notices the segment change.
> > + * ws_file stays open on the old segment while ReadPageInternal()
> > + * advances ws_segno. For example, when the first page of segment 2
> > + * comes from buffers, ws_segno becomes 2 but ws_file is still open on
> > + * segment 1. A later read of segment 2 that falls back to the file
> > + * reuses the stale descriptor, since WALRead() decides whether to
> > + * reopen from ws_segno (already 2) rather than the open file. It
> > + * reads segment 1 and returns the wrong segment's WAL, seen during
> > + * decoding as an "unexpected pageaddr" error. Close the segment after
> > + * a buffer-only read so the next file read reopens the correct one.
> > + */
> > + state->routine.segment_close(state);
> > + }
> >
> > Cannot that become wasteful for the logical path when reading pages
> > from the same segment repeatedly causing opening and closing of the
> > same file? That sounds relevant to me if we are still attempting
> > to read from the same segment, depending on wal_buffers whose default
> > is at 4MB. Something like an extra check based on XLByteInSeg() may
> > be adapted, using the targetPagePtr, where we could close the segment
> > only if we target a page not on the same segment?
> >
> > The same argument applies to both v6-0001 and v6-0002, both
> > unconditionally closing a segment after completing a read from buffer
> > or even not completing a read from buffers and completing the read
> > with an extra WALRead().
>
> Ah, yes, that is not acceptable. Nice catch! Fixed it by closing the
> old segment only when the first WAL page of the new segment is fully
> read from buffers.
>
> > + Assert(rbytes == count);
> >
> > This assert feels redundant due to the other checks done above.
> > Applies to patches 0001 and 0002.
>
> Removed.
>
> Please find the attached v7 patches.
>
> --
> Bharath Rupireddy
> Amazon Web Services: https://aws.amazon.com
Hi!
I noticed this patch did a small benchmarking on v6/v7,
primary-standby on single vm. Seems like XLByteInSeg is really needful
here, but I didn't find any v6 perf regression in close() syscall
spam. I can share my bench scripts if needed.
reads/bytes in benches measured using pg_stat_io
## Results: catch-up subscriber
```
Build TPS walsender reads walsender read_bytes read_time
───────────────────────────────────────────────
HEAD + DIO 49,942 49,751 407 MB 1.66 ms
Patched v7 + DIO 46,469 124 818 KB 0 ms
───────────────────────────────────────────────
Delta —
-99.8% —
```
The patch virtually eliminates walsender file reads (407 MB -> 818 KB).
## Results: lagging subscriber
```
Build TPS walsender reads walsender read_bytes
────────────────────────────────────────
HEAD + DIO 47,802 127,119 1,041 MB
Patched v7 + DIO 48,956 71,118 583 MB
────────────────────────────────────────
Delta — -44%
```
With a lagging subscriber, the patch reduces file reads by 44% and
improves TPS (probably noise).
Code itself looks fine to me, don't see any major issues.
In 0001 this comment looks unnecessarily big for me:
> + /*
> + * A read fully satisfied from WAL buffers skips WALRead(), which is
> + * where ws_file is closed and reopened as the reader crosses
> + * segments. So a buffer-only read never notices the segment change.
> + * ws_file stays open on the old segment while ReadPageInternal()
> + * advances ws_segno. For example, when the first page of segment 2
> + * comes from buffers, ws_segno becomes 2 but ws_file is still open on
> + * segment 1. A later read of segment 2 that falls back to the file
> + * reuses the stale descriptor, since WALRead() decides whether to
> + * reopen from ws_segno (already 2) rather than the open file. It
> + * reads segment 1 and returns the wrong segment's WAL, seen during
> + * decoding as an "unexpected pageaddr" error. Close the segment when
> + * the page just read from buffers is not in the open segment, so the
> + * next file read reopens the correct one. Reads staying within the
> + * open segment leave it alone, because ws_segno does not change.
> + */
Isn't this just a very detailed way to say "close WAL segment that you
ought to close?". I think 0002 comment
+ /*
+ * Close the segment when a read fully satisfied from WAL buffers is
+ * not in the open segment, so the next file read reopens the correct
+ * one. See logical_read_xlog_page() for why this is needed.
+ */
Is ok.
v7 is neutral for buffered io (no regression/only 1-2% noise) and
saves a lot of IO for direct IO.
Also here [1] & [2], you (and Andres) suggest sending WAL before it has been
locally written out and flushed to improve synchronous replication
performance. I have actually made a simple PoC on this recently ([3]
code and benchmarks used), and it didn't show some improvement (even
with standby applying all wal from received primary, beyond flush ptr.
~6-7% improvement at low WAL volume, parity at high volume). So, can
you share a thread with this work or start one?
Small summary for results
[1] https://www.postgresql.org/message-id/CALj2ACVzJPJMLi%2BuhU8Hvw6sYiTOVy-vetkZ4QTQ%3DTOE8dygkA%40mail.gmail.com
[2] https://www.postgresql.org/message-id/20230125211540.zylu74dj2uuh3k7w%40awork3.anarazel.de
[3] https://github.com/pg-sharding/cpg/pull/107/commits
[4] https://github.com/pg-sharding/cpg/tree/wal_flush/bench/walrcvflusher/scripts
--
Best regards,
Kirill Reshke
Re: Use WALReadFromBuffers in more places
On Mon, Sep 14, 2026 at 01:07:00PM -0700, Bharath Rupireddy wrote: > I noticed a CF bot failure in 001_rep_changes.pl because the logical > walsender was reading all the WAL from WAL buffers, so the disk read > path was never hit. This caused the TAP test that expects at least one > disk read to time out. This reminds me of a missing piece in the > WALReadFromBuffers() journey, that is, reporting how often WAL is read > from WAL buffers. So far the physical walsender TAP test hasn't > complained, but in the 0001 patch I added support to report WAL buffer > hits using the existing IOOP_HIT operation and adjusted the physical > walsender test accordingly. Note that I couldn't add byte-level hit > tracking in 0001, which I plan to do separately. The added hit counter > for WAL is enough to know how often reads come from WAL buffers and > will fix the CF bot failure. Hmm. Okay but.. > Another idea to resolve this is to just count reads from WAL buffers > into the existing reads and read_bytes, the same way WALRead() does, > and be done with it. This is simpler, though one can't distinguish or > know how often WAL buffers are hit and reading from WAL files is > avoided. One argument in favor of this approach is to just treat WAL > buffer hits like OS page cache hits, and since we don't count those in > pg_stat_io, that is okay. But I prefer using the hits operation unless > anyone thinks otherwise. + /* + * Report the read as a hit on the WAL buffers, so that it can be + * distinguished from a read from a file. A read that finds only part of + * the requested WAL here is also reported by the file read that the + * caller then does, for the rest of it. + */ + if (nread > 0) + pgstat_count_io_op(IOOBJECT_WAL, IOCONTEXT_NORMAL, IOOP_HIT, 1, 0); + + return nread; ... It looks to me that you do not have the right idea with v9-0001, where you decide to count the number of *times* we call WALReadFromBuffers(). It would be more correct to me to count the number of hits as of the *number of pages* we are able to read while attempting to retrieve "count" bytes worth of WAL in a single call of WALReadFromBuffers(). If some data has been evicted, we may read less data, but the number of pages hit still seems like the most relevant part. With that, it is possible to do an educated estimation of how many data worth XLOG_BLCKSZ has been found. It does not have to be 100% precise, just good enough to know the balance between buffer reads and physical reads. If we read for example 1GB worth of data in one call of WALReadFromBuffers() it would be confusing to count that as 1 hit, that should be (1024^3 / XLOG_BLCKSZ) hits. Let's use a counter that is incremented while scanning the pages through the while loop, then increment pg_stat_io once at the end of WALReadFromBuffers() if (nread > 0). I am not really convinced that there is a need to have the number of bytes if we know the number of hits. Even with MAX_SEND_SIZE worth *only* 16 pages, sending very less than 8kB of data is IMO very unlikely these days on systems where we care about the IO activity. The number of bytes would become useful if we send for example a bunch of small-ish messages in the WAL sender. > 0002 through 0004 are unchanged, except that the logical walsender > test in 0002 now waits for the sum of reads and hits, since a read > from the WAL buffers is reported as a hit and not as a read. In terms of 0002, 0003 and 0005, anybody who does a serious review of this patch set will need to run benchmarks to confirm your points. If you could post a script, that would be useful IMO. The difficulty of this patch is not its implementation, it's the testing. I am not convinced that 0004 offers much value if integrated, still it seems nice to have to stress the CI. -- Michael
Re: Use WALReadFromBuffers in more places
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Вложения:
Hi,
On Thu, Oct 8, 2026 at 10:37 PM Michael Paquier wrote:
>
> It would be more correct to me to count the
> number of hits as of the *number of pages* we are able to read while
> attempting to retrieve "count" bytes worth of WAL in a single call of
> WALReadFromBuffers().
>
> If we read for example 1GB worth of data in
> one call of WALReadFromBuffers() it would be confusing to count that
> as 1 hit, that should be (1024^3 / XLOG_BLCKSZ) hits. Let's use a
> counter that is incremented while scanning the pages through the while
> loop, then increment pg_stat_io once at the end of
> WALReadFromBuffers() if (nread > 0).
Done that way.
> In terms of 0002, 0003 and 0005, anybody who does a serious review of
> this patch set will need to run benchmarks to confirm your points. If
> you could post a script, that would be useful IMO. The difficulty of
> this patch is not its implementation, it's the testing.
Sorry for not sharing them earlier. I attached the test scripts I used
for my benchmarking. I also did a new run and shared the results [1].
> I am not convinced that 0004 offers much value if integrated, still it
> seems nice to have to stress the CI.
Agreed. I dropped this patch, since we now know the fix and it works,
and v9 has it for the records.
I also did some correctness testing. I disabled the WAL writer's
opportunistic WAL buffer page initialization and forced the WAL
buffers to 2GB in the code (patch attached for this), so that most of
the WAL is available in the WAL buffers for readers, and ran make
check-world. I don't see any issues except the one TAP test failure
that happens on HEAD as well as with the patches, since it strictly
depends on the WAL buffers size.
Please find the attached v10 patches. I reworded the comments a bit
and rewrote the commit messages.
[1]
With WAL direct IO on, HEAD vs PATCHED, file reads reduced by 99.9%,
53.4% and 64.1%, and WAL disk read IO reduced by 99.9%, 98.9% and
27.8%, for the logical walsender, local WAL reads and WAL summarizer
resp. With WAL direct IO off, file reads reduced by 99.9%, 65.5% and
65.0%.
Test setup: Amazon EC2 r7i.4xlarge instance (16 vCPU, 128 GB RAM),
pg_wal on a dedicated gp3 volume. shared_buffers=8GB,
wal_buffers=16MB, max_wal_size=64GB, synchronous_commit=on. 350 byte
logical messages using pgbench with 16 clients for 180 seconds, while
the reader reads that WAL back. Each is an average of 5 runs.
0002 logical walsender:
# build WAL direct IO TPS WAL generated MB walsender read MB
file reads buffer hits WAL-disk reads WAL-disk writes replication
lag
1 HEAD on 6393 511 1056
204243 0 13.4 MB/s 9.5 MB/s 9.3 KB
2 PATCHED on 7394 591 1.5
198 240183 0.02 MB/s 10.9 MB/s 4.6 KB
3 HEAD off 7368 589 1231
239521 0 0 MB/s 10.8 MB/s 4.6 KB
4 PATCHED off 7321 585 1.8
229 237596 0 MB/s 10.8 MB/s 4.1 KB
0003 local WAL reads:
# build WAL direct IO TPS scans/s WAL generated MB reader read
MB file reads buffer hits WAL-disk reads WAL-disk writes reader
lag
1 HEAD on 6695 313 544 1476
214098 0 10.1 MB/s 9.9 MB/s 22.1 KB
2 PATCHED on 7494 493 612 779
99759 192916 0.11 MB/s 11.1 MB/s 14.9 KB
3 HEAD off 7412 491 606 1878
292188 0 0 MB/s 11.0 MB/s 14.9 KB
4 PATCHED off 7450 493 609 787
100790 193393 0 MB/s 11.0 MB/s 14.9 KB
0004 WAL summarizer:
# build WAL direct IO TPS WAL generated MB summarizer file read
MB file reads buffer hits WAL-disk reads WAL-disk writes
1 HEAD on 7366 578 582
74887 0 10.0 MB/s 12.4 MB/s
2 PATCHED on 7394 580 210
26913 48264 7.2 MB/s 10.8 MB/s
3 HEAD off 7313 574 578
74383 0 0 MB/s 10.6 MB/s
4 PATCHED off 7300 573 204
26057 48792 0 MB/s 10.6 MB/s
--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com
Re: Use WALReadFromBuffers in more places
On Mon, Oct 12, 2026 at 05:01:08PM -0700, Bharath Rupireddy wrote: > Done that way. Thanks. Applied v10-0001 after tweaking a bit the docs, to close the monitoring gap with the tracking of WAL buffer bits. -- Michael
Re: Use WALReadFromBuffers in more places
Hi, On Thu, Oct 15, 2026 at 4:10 PM Michael Paquier wrote: > > Thanks. Applied v10-0001 after tweaking a bit the docs, to close the > monitoring gap with the tracking of WAL buffer bits. Thanks. Please find attached the remaining patches, renumbered to keep CI happy. No code changes, changed only the patch numbers, so kept them as v10. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
RE: Use WALReadFromBuffers in more places
От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Hi, Recently I came up with the similar idea and finally found the thread, started to learn... I found your performance looks very nice. IIUC, the performance can be decreased if the wal_buffer is not enough large and walsenders always miss the cache, right? Can we confirm when it can happen? Regarding the code, state->seg.ws_tli cannot be updated if logical_read_xlog_page() bypasses the actual WAL read. It seems to break the callback rule determined in xlogheader.h: ``` * The callback shall set ->seg.ws_tli to the TLI of the file the page was * read from. */ XLogPageReadCB page_read; ``` Best regards, Hayato Kuroda FUJITSU LIMITED
Re: Use WALReadFromBuffers in more places
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi, On Tue, Oct 27, 2026 at 4:40 AM Hayato Kuroda (Fujitsu) wrote: > > I found your performance looks very nice. Thanks for taking a look at it. > IIUC, the performance can be decreased > if the wal_buffer is not enough large and walsenders always miss the cache, right? > Can we confirm when it can happen? It depends on a couple of things. When there are not enough WAL buffers. When the consumers are lagging beyond the WAL being generated i.e. insertion point. When the WAL writer's opportunistic page initialization kicks in to zero-out the most WAL pages from the buffers. > Regarding the code, state->seg.ws_tli cannot be updated if logical_read_xlog_page() > bypasses the actual WAL read. It seems to break the callback rule determined > in xlogheader.h: > > ``` > * The callback shall set ->seg.ws_tli to the TLI of the file the page was > * read from. > */ > XLogPageReadCB page_read; > ``` Yes, you are right. When the WAL is fully read from the buffers, ws_tli stays 0. For the existing physical walsender the first read always happens from a WAL file, as we attempt to read from the buffers with ws_tli 0. I can't think of any correctness issue, but it affects error reporting for file removal and validation checks. When reading from the buffers, the validation checks rarely fail, because the WAL pages are initialized atomically for next use. I would like to fix this by setting seg.ws_tli when we skip reading from the file. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com
Re: Use WALReadFromBuffers in more places
Hi, On Wed, Nov 4, 2026 at 1:09 PM Bharath Rupireddy wrote: > > > Regarding the code, state->seg.ws_tli cannot be updated if logical_read_xlog_page() > > bypasses the actual WAL read. It seems to break the callback rule determined > > in xlogheader.h: > > Yes, you are right. When the WAL is fully read from the buffers, > ws_tli stays 0. For the existing physical walsender the first read > always happens from a WAL file, as we attempt to read from the buffers > with ws_tli 0. I can't think of any correctness issue, but it affects > error reporting for file removal and validation checks. When reading > from the buffers, the validation checks rarely fail, because the WAL > pages are initialized atomically for next use. > > I would like to fix this by setting seg.ws_tli when we skip reading > from the file. Please find the attached v11 patches with the above change. -- Bharath Rupireddy Amazon Web Services: https://aws.amazon.com