Keep TIDBitmap pagetable memory across bitmap scans

Started by Greg Burd16 days ago9 messageshackers
Jump to latest
#1Greg Burd
greg@burd.me

On Fri, Oct 16, 2026, John Naylor wrote:

On Wed, Oct 14, 2026, David Geier wrote:

This is because today, a major cost of large BitmapIndexScans is
repeatedly growing the simplehash.h-based hash table backing TIDBitmap
from initially 128 elements to its final size.

How much of a major cost?

Hi John, David,

I'm ping'ing you two because this came up while reviewing the radix tree
thread you've been working on [1]/messages/by-id/6a55187b-8b27-41a8-bef1-ef7259dccf8d@gmail.com, it got me thinking. So I dove in and
measured it. I was going to post into your thread but because there is
a prototype patch that resulted from my investigation, I thought I'd
start a new thread.

A bitmap heap scan over many pages spends much of its time in the
kernel when many backends run it at once. The TIDBitmap pagetable is a
simplehash that starts at 256 slots and doubles until it fits. For a
bitmap of about 17k heap pages that is seven grows, from a 12 kB array
up to a 1.5 MB one, about 2.9 MB of zeroed allocations per query. Each
array goes to malloc, and with glibc's default settings the heap grows
with brk for each step and is trimmed back to the kernel at ExecutorEnd.
The next query faults the same pages in again, about 730 page faults per
query.

With many backends doing this at once, the faults and the trims contend
in the kernel. On a 96-thread host at 96 clients, 27% of all cycles are
in native_queued_spin_lock_slowpath under folio_lruvec_lock_irqsave (all
backends in one memory cgroup), and a third of the CPU is system time.

David, I think you saw the same growth cost and measured presizing the
table: 3,034 page faults down to 0, and a bitmap index scan from 193 to
139 ms [2]/messages/by-id/6193bdf3-218e-4cbc-b369-d964c52af4e0@gmail.com. Presizing from the planner's estimate only helps where the
estimate is right, though. For "ga @> ARRAY[a, b]" on an int4[] GIN
index the estimate here is 4 rows against 17k, so the table grows from
256 slots as before. And under the two most common libc implementations
for Linux (musl, glibc) with a low mmap threshold, every array over 128
kB is mapped and unmapped each time. In a prototype I tried presizing
to the right size, but that took musl only from 768 to 424 faults per
query.

The attached prototype patches try a different approach, they keep and
reuse the allocated memory instead.

0001 adds src/test/modules/test_tidbitmap. It builds up to 32 bitmaps
at once from synthetic block numbers, checks each one's contents by
iterating it, and raises errors while they are being built. The SQL
part compares BitmapAnd, BitmapOr, GIN prefix matches, rescans, an open
cursor, an error, a cancel, work_mem changes and a parallel bitmap heap
scan against a plan with no bitmap. It passes without 0002.

0002 keeps the pagetable array and the sorted page list of up to two
large private bitmaps per backend, in a memory context named "TIDBitmap
cache". A bitmap whose table reaches 2048 slots takes a free entry and
switches to the entry's array in one step. Bitmaps that find no free
entry work as before, and so do small bitmaps and shared ones. The
arrays are allocated in the cache context, and a reset callback on the
bitmap's own context gives the entry back, so an error that skips
tbm_free() neither frees them nor leaves a dangling owner.

Two entries is the smallest number that covers BitmapAnd, which holds
the result and one input at a time; with one entry, the second bitmap
still faulted. The threshold is 2048 slots because simplehash grows a
large table from inside the insert when its probe chains get long, so
the cache has to be taken before the next grow can happen, and a
2048-slot array (96 kB) is the largest that stays under the 128 kB mmap
threshold.

Benchmark numbers:

c7i.metal-24xl (Xeon 8488C, 48 cores / 96 threads, one socket), Fedora
44, turbo off, THP off, shared_buffers 16 GB on huge pages, all data
cached. 16M rows, ~17k rows per value scattered over ~16k heap pages,
so each bitmap is ~17k exact pages. pgbench -M prepared, fixed
transactions per client, stock and patched interleaved ABBA, each built
twice with different code layouts (mold --shuffle-sections),
steady-state TPS. An A/A pair put the noise floor at 2.5%. Faults are
system-wide, per query.

96 clients, glibc defaults, TPS (page faults per query):

btree g = v 2,756 (734) -> 4,321 (0) +56.8%
GIN g = v (btree_gin) 2,816 (724) -> 4,081 (0) +44.9%
GIN ga @> ARRAY[v, w] 2,926 (711) -> 3,944 (0) +34.8%
BitmapAnd btree AND GIN 2,213 (1,092) -> 3,648 (0) +64.9%

Under musl, btree goes from 2,569 to 4,207 TPS (+63.8%) and BitmapAnd
from 1,838 to 3,472 (+88.9%), with 43 and 102 faults per query left.
Under jemalloc, which never faulted much, the gain is +4.7% to +11.9%:
that part is the doubling's rehash and copy.

What a backend keeps is at most work_mem in total, so 4 MB at the
default, and it shows in pg_backend_memory_contexts as "TIDBitmap
cache". A bitmap created with a smaller work_mem frees idle entries
that don't fit. There is no idle release, the memory is retained until
such a bitmap scan or backend exit. Freeing it at ReadyForQuery would
bring the faults back for every query, and catching a backend that sits
idle would need a timer. If large work_mem settings make this a
problem, a fixed cap below work_mem is the simple alternative.

The reproducer (table setup, pgbench scripts, measurement scripts) is
small; I can post it if anyone wants to run it. John, I'll follow up in
that thread on how the two relate.

best.

-greg

[1]: /messages/by-id/6a55187b-8b27-41a8-bef1-ef7259dccf8d@gmail.com
[2]: /messages/by-id/6193bdf3-218e-4cbc-b369-d964c52af4e0@gmail.com

Attachments:

t258368_1
v1-0001-Add-test-module-for-TIDBitmap.patch.gzapplication/gzip; name=v1-0001-Add-test-module-for-TIDBitmap.patch.gzDownload
v1-0002-Keep-TIDBitmap-pagetable-memory-for-the-next-bitm.patch.gzapplication/gzip; name=v1-0002-Keep-TIDBitmap-pagetable-memory-for-the-next-bitm.patch.gzDownload
#2David Geier
geidav.pg@gmail.com
In reply to: Greg Burd (#1)
Re: Keep TIDBitmap pagetable memory across bitmap scans

Hi Greg!

I'm ping'ing you two because this came up while reviewing the radix tree
thread you've been working on [1], it got me thinking. So I dove in and
measured it. I was going to post into your thread but because there is
a prototype patch that resulted from my investigation, I thought I'd
start a new thread.

Thanks for investigating this further.

A bitmap heap scan over many pages spends much of its time in the
kernel when many backends run it at once. The TIDBitmap pagetable is a
simplehash that starts at 256 slots and doubles until it fits. For a
bitmap of about 17k heap pages that is seven grows, from a 12 kB array
up to a 1.5 MB one, about 2.9 MB of zeroed allocations per query. Each
array goes to malloc, and with glibc's default settings the heap grows
with brk for each step and is trimmed back to the kernel at ExecutorEnd.
The next query faults the same pages in again, about 730 page faults per
query.

With many backends doing this at once, the faults and the trims contend
in the kernel. On a 96-thread host at 96 clients, 27% of all cycles are
in native_queued_spin_lock_slowpath under folio_lruvec_lock_irqsave (all
backends in one memory cgroup), and a third of the CPU is system time.

It's actually curious that it's that bad. All processes are independent
so they have their own page tables, mm_struct lists, etc., all with
their own locks. The kernel's page allocator should scale well enough to
not cause that level of contention.

I believe the folio_lruvec_lock_irqsave() stems from protecting the
cgroup's memory accounting. Could you rerun your test without cgroups?
This is still a good finding but it would be interesting as well to see
how it performs without cgroups.

David, I think you saw the same growth cost and measured presizing the
table: 3,034 page faults down to 0, and a bitmap index scan from 193 to
139 ms [2]. Presizing from the planner's estimate only helps where the
estimate is right, though. For "ga @> ARRAY[a, b]" on an int4[] GIN
index the estimate here is 4 rows against 17k, so the table grows from
256 slots as before. And under the two most common libc implementations
for Linux (musl, glibc) with a low mmap threshold, every array over 128
kB is mapped and unmapped each time. In a prototype I tried presizing
to the right size, but that took musl only from 768 to 424 faults per
query.

glibc's malloc uses sbrk() by default. I haven't looked into why causes
the documentation claims today it uses mmap(). Regardless, it causes the
same problem of repeatedly allocated and freed memory causing minor page
faults each time they're accessed the first time after being allocated
again.

The attached prototype patches try a different approach, they keep and
reuse the allocated memory instead.

0001 adds src/test/modules/test_tidbitmap. It builds up to 32 bitmaps
at once from synthetic block numbers, checks each one's contents by
iterating it, and raises errors while they are being built. The SQL
part compares BitmapAnd, BitmapOr, GIN prefix matches, rescans, an open
cursor, an error, a cancel, work_mem changes and a parallel bitmap heap
scan against a plan with no bitmap. It passes without 0002.

0002 keeps the pagetable array and the sorted page list of up to two
large private bitmaps per backend, in a memory context named "TIDBitmap
cache". A bitmap whose table reaches 2048 slots takes a free entry and
switches to the entry's array in one step. Bitmaps that find no free
entry work as before, and so do small bitmaps and shared ones. The
arrays are allocated in the cache context, and a reset callback on the
bitmap's own context gives the entry back, so an error that skips
tbm_free() neither frees them nor leaves a dangling owner.

While I think the direction of keeping the memory around is the right
one, I don't think we should do that at the Bitmap Index Scan (BIS)
level for two reasons:

1. A database with lots of connections could quickly spent gigabytes on
unused BIS buffers. Freeing the memory when unused quickly gets you
into memory allocator territory.
2. There are more places in the code where we double allocation sizes as
we go and hence cause avalanches of page faults repeatedly. It would
be good to fix them all in one go.

You showed already that the majority of the slowdown goes away by having
a memory allocator that less eagerly returns freed memory to the OS.

It seems like there's a threshold that controls how aggressively malloc
trims free memory that can be changed via mallopt(M_TRIM_THRESHOLD, -1).
How about giving this a try and thinking about using it to our advantage.

Is anyone aware of an effort to change PostgreSQL to use e.g. jemalloc
which better allows controlling when memory is returned?

Benchmark numbers:

c7i.metal-24xl (Xeon 8488C, 48 cores / 96 threads, one socket), Fedora
44, turbo off, THP off, shared_buffers 16 GB on huge pages, all data
cached. 16M rows, ~17k rows per value scattered over ~16k heap pages,
so each bitmap is ~17k exact pages. pgbench -M prepared, fixed
transactions per client, stock and patched interleaved ABBA, each built
twice with different code layouts (mold --shuffle-sections),
steady-state TPS. An A/A pair put the noise floor at 2.5%. Faults are
system-wide, per query.

96 clients, glibc defaults, TPS (page faults per query):

btree g = v 2,756 (734) -> 4,321 (0) +56.8%
GIN g = v (btree_gin) 2,816 (724) -> 4,081 (0) +44.9%
GIN ga @> ARRAY[v, w] 2,926 (711) -> 3,944 (0) +34.8%
BitmapAnd btree AND GIN 2,213 (1,092) -> 3,648 (0) +64.9%

Under musl, btree goes from 2,569 to 4,207 TPS (+63.8%) and BitmapAnd
from 1,838 to 3,472 (+88.9%), with 43 and 102 faults per query left.
Under jemalloc, which never faulted much, the gain is +4.7% to +11.9%:
that part is the doubling's rehash and copy.

That's quite impressive. Let's check how that looks without cgroups.

--
David Geier

#3Greg Burd
greg@burd.me
In reply to: David Geier (#2)
Re: Keep TIDBitmap pagetable memory across bitmap scans

On Tue, Nov 10, 2026, David Geier wrote:

It's actually curious that it's that bad. All processes are independent
so they have their own page tables, mm_struct lists, etc., all with
their own locks. The kernel's page allocator should scale well enough to
not cause that level of contention.

Hey David,

I believe the folio_lruvec_lock_irqsave() stems from protecting the
cgroup's memory accounting. Could you rerun your test without cgroups?

Sure, and guess what? It isn't the cgroup. Same host, same build, as
before and with glibc defaults, 96 clients, btree:

stock tps (faults/query) patched spinlock share
memcg on 2,746 (732) 4,284 29.5%
cgroup_disable=memory 2,874 (690) 4,273 27.4%

The memory controller costs about 5% here, but the contended lock is the
LRU list lock, and without memcg the lruvec is the node's. On a
one-socket host every backend still takes the same one, on every first
touch of a fresh page (lru_add) and again when brk trims the heap and
the pages are released.

To check that it isn't Linux-specific either, I ran the same test on
FreeBSD 14.5 on the same instance type. FreeBSD has no memcg. Its libc
malloc (jemalloc) keeps the memory and never stormed, so I forced the
same pattern with allocators that give memory back. With libumem
(4.3.2), which returns large frees with madvise(MADV_DONTNEED), DTrace
lockstat shows 87 s of spinning per 5 s on "vm active pagequeue", one
lock per memory domain, taken from madvise and from the fault path.
Stock btree there is 3,575 tps with 690 faults per query and 22% system
time; patched, 4,306 with 2. So it's a per-NUMA-node page queue lock
that every backend shares, on both kernels.

glibc's malloc uses sbrk() by default. I haven't looked into why causes
the documentation claims today it uses mmap().

Right, I should have been clearer: "a low mmap threshold" meant
MALLOC_MMAP_THRESHOLD_ set. With defaults, glibc's probes show brk: for
20 bitmap statements in one backend, 99 sbrk grows and 20 trims. The
mmap threshold starts at 128 kB but rises to the size of the largest
mmapped chunk freed, so by the time this matters, everything is on brk.

It seems like there's a threshold that controls how aggressively malloc
trims free memory that can be changed via mallopt(M_TRIM_THRESHOLD, -1).
How about giving this a try and thinking about using it to our advantage.

On its own it doesn't help, and I didn't expect that. Setting
M_TRIM_THRESHOLD (or M_TOP_PAD, or M_MMAP_THRESHOLD) also turns off the
dynamic threshold, so the mmap threshold stays at 128 kB. Every array
over 128 kB then goes to mmap and munmap instead of brk, and faults the
same. 96 clients. btree: stock TPS (faults/query) [patched TPS]; the
other three: stock faults per query:

btree hash join sort hash agg
glibc defaults 2,758 (732) [4,278] 1,199 1,020 0
M_TRIM_THRESHOLD only 2,799 (726) [4,283] 0 620 600
M_TRIM + M_MMAP_THRESHOLD 4,040 (0) [4,272] 0 0 0
jemalloc 4,046 (7) [4,268] 350 12 3

Trim alone moves the faults around: hash join stops faulting and hash
aggregate starts. Setting both thresholds removes them everywhere and
matches jemalloc. (Our earlier "trim threshold" run had worked because it
also set a 64 MB top pad, which keeps malloc from ever reaching the code
that decides to mmap.)

While I think the direction of keeping the memory around is the right
one, I don't think we should do that at the Bitmap Index Scan (BIS)
level for two reasons:

1. A database with lots of connections could quickly spent gigabytes on
unused BIS buffers. Freeing the memory when unused quickly gets you
into memory allocator territory.

The patch keeps at most work_mem per backend, and only in backends that
ran a large bitmap scan, so 800 MB for 200 such backends at the default.

For comparison, glibc with both thresholds set keeps whatever each
backend's high-water mark was, with no bound at all; jemalloc keeps
dirty pages for 10 s and then gives them back. But before you say it, I
agree the decay is better done by an allocator than by tidbitmap.c.

2. There are more places in the code where we double allocation sizes as
we go and hence cause avalanches of page faults repeatedly. It would
be good to fix them all in one go.

Yes. I added a hash join, a sort and a hash aggregate to the test.
With glibc defaults, the hash join faults 1,199 times per query and the
sort 1,020; the patch does nothing for either. They cost less in total
(4.5% and 9.7% system time against 33% for the bitmap scans), but it's
the same mechanism.

I agree a process-wide fix is the better target, and setting both glibc
thresholds at backend start would be a small one. The patch would still
be worth +5.5% to +11.8% on top of that, from skipping the rehash and
copy of the doubling, but that's a much smaller argument.

Is anyone aware of an effort to change PostgreSQL to use e.g. jemalloc
which better allows controlling when memory is returned?

One data point against just switching: mimalloc on FreeBSD gets 620 tps
on the btree query, against 3,982 with libc. mimalloc reserves its
arena in the postmaster, every backend inherits it, and on FreeBSD all
of them end up on one shared VM object. Every purge (madvise of 26 MB)
then takes that object's lock: 87% of all CPU time is spent spinning on
it. With MIMALLOC_PURGE_DELAY=-1 it gets 4,030. On Linux, mimalloc
behaves like glibc (724 faults per query). How an allocator interacts
with fork-without-exec is not something allocator benchmarks usually
measure and publicize.

On Tue, Nov 10, 2026, David Geier wrote in the radix tree thread:

A shot into the dark: sbrk() can only shrink if there's no allocation
sticking around after the freed memory. Maybe that causes the virtual
memory to not be returned in some cases?

That's it. Twenty bitmaps inside one statement trim the heap once (788
faults); twenty separate statements trim it twenty times (14,659
faults). The heap only shrinks at statement end, when the query's other
memory above the freed arrays goes too.

But it's curious that calloc() didn't help. Did you remove writing to the
status byte after changing to calloc()?

Yes, that version used calloc() and wrote nothing itself. The inserts
touch every page anyway: 17k entries in 32,768 slots of 48 bytes, 85
slots per 4 kB page, so the chance of a page getting no entry is about
e^-44. Why calloc() faulted more than palloc0 (1,161 against 732 per
query) I still haven't tracked down.

The more important part is that the radix tree grows incrementally while
the hash map needs to double in size and then be rehashed. That lowers
the number of page faults considerably.

The faults follow the memory touched per query, though, not the number
of grows. Presizing the table, so the final 1.5 MB is touched once,
took glibc with a low mmap threshold from 703 to 396 faults per query,
and musl from 768 to 424. I'd expect an incrementally grown tree whose
memory is given back after each query to land about there too: half the
faults, not none. That's inference; I haven't measured a radix tree.

So, where does all this digging this leave us? The kernel side is a
shared per-node lock, and memory given back per query hits it on both
Linux and FreeBSD. The fix probably belongs at the process level rather
than in tidbitmap.c, since hash join and sort have the same problem.

For glibc, setting M_MMAP_THRESHOLD and M_TRIM_THRESHOLD together is
enough; setting only one is not. I can look at what that would mean in
PostgreSQL (where to set it, and what bound to use) unless someone knows
a reason not to.

The setup: c7i.metal-24xl, Fedora 44 (kernel 7.3, glibc 2.43) and FreeBSD
14.5, stock and patched interleaved, two runs per side. libumem 4.3.2,
mimalloc 2.2.4 and jemalloc 5.3. The scripts and raw numbers are
available if anyone wants them.

best.

-greg

#4Greg Burd
greg@burd.me
In reply to: Greg Burd (#3)
Re: Keep TIDBitmap pagetable memory across bitmap scans

v2 attached, rebased on master (ef1b740441c). 0002 is unchanged; two
fixes in 0001's test:

- cfbot's 32-bit Linux job failed test_tidbitmap [1]https://github.com/postgres/postgres-cfbot/actions/runs/42661536023/job/129314681459. One query returned
the number of lossy pages for three bitmaps with a 1 MB limit, and that
number depends on the pointer size: tbm_calculate_entries() counts two
pointers per entry for the iteration arrays, so 1 MB allows 16,384
entries with 8-byte pointers and 18,724 with 4-byte ones, and fewer
pages go lossy. 16,514 became 18,874 on i386, which I reproduced with
an i386 build. The test now checks only that some pages went lossy, as
its neighbours already do.

- The cancel case printed a CONTEXT line that depends on where the
statement timeout fires, inside pg_sleep or not. It failed once in my
runs; it now runs with VERBOSITY terse.

The direction is still the open question from my last mail: whether to
fix this per allocation site, as 0002 does for the TIDBitmap, or once
for the whole process, since hash join and sort fault the same way. I'm
keeping the patch current while that's discussed.

best.

-greg

[1]: https://github.com/postgres/postgres-cfbot/actions/runs/42661536023/job/129314681459

Attachments:

t258368_4
v2-0002-Keep-TIDBitmap-pagetable-memory-for-the-next-bitm.patch.gzapplication/gzip; name=v2-0002-Keep-TIDBitmap-pagetable-memory-for-the-next-bitm.patch.gzDownload
v2-0001-Add-test-module-for-TIDBitmap.patch.gzapplication/gzip; name=v2-0001-Add-test-module-for-TIDBitmap.patch.gzDownload
#5David Geier
geidav.pg@gmail.com
In reply to: Greg Burd (#3)
Re: Keep TIDBitmap pagetable memory across bitmap scans

I believe the folio_lruvec_lock_irqsave() stems from protecting the
cgroup's memory accounting. Could you rerun your test without cgroups?

Sure, and guess what? It isn't the cgroup. Same host, same build, as
before and with glibc defaults, 96 clients, btree:

stock tps (faults/query) patched spinlock share
memcg on 2,746 (732) 4,284 29.5%
cgroup_disable=memory 2,874 (690) 4,273 27.4%

The memory controller costs about 5% here, but the contended lock is the
LRU list lock, and without memcg the lruvec is the node's. On a
one-socket host every backend still takes the same one, on every first
touch of a fresh page (lru_add) and again when brk trims the heap and
the pages are released.

Thanks for confirming this. So it's the soft page faults that install
the fresh page in the LRU.

To check that it isn't Linux-specific either, I ran the same test on
FreeBSD 14.5 on the same instance type. FreeBSD has no memcg. Its libc
malloc (jemalloc) keeps the memory and never stormed, so I forced the
same pattern with allocators that give memory back. With libumem
(4.3.2), which returns large frees with madvise(MADV_DONTNEED), DTrace
lockstat shows 87 s of spinning per 5 s on "vm active pagequeue", one
lock per memory domain, taken from madvise and from the fault path.
Stock btree there is 3,575 tps with 690 faults per query and 22% system
time; patched, 4,306 with 2. So it's a per-NUMA-node page queue lock
that every backend shares, on both kernels.

OK.

glibc's malloc uses sbrk() by default. I haven't looked into why causes
the documentation claims today it uses mmap().

Right, I should have been clearer: "a low mmap threshold" meant
MALLOC_MMAP_THRESHOLD_ set. With defaults, glibc's probes show brk: for
20 bitmap statements in one backend, 99 sbrk grows and 20 trims. The
mmap threshold starts at 128 kB but rises to the size of the largest
mmapped chunk freed, so by the time this matters, everything is on brk.

Ah, so by default glibc adapts its threshold to the observed allocation
sizes up to a limit.

It seems like there's a threshold that controls how aggressively malloc
trims free memory that can be changed via mallopt(M_TRIM_THRESHOLD, -1).
How about giving this a try and thinking about using it to our advantage.

On its own it doesn't help, and I didn't expect that. Setting
M_TRIM_THRESHOLD (or M_TOP_PAD, or M_MMAP_THRESHOLD) also turns off the
dynamic threshold, so the mmap threshold stays at 128 kB. Every array
over 128 kB then goes to mmap and munmap instead of brk, and faults the
same. 96 clients. btree: stock TPS (faults/query) [patched TPS]; the
other three: stock faults per query:

btree hash join sort hash agg
glibc defaults 2,758 (732) [4,278] 1,199 1,020 0
M_TRIM_THRESHOLD only 2,799 (726) [4,283] 0 620 600
M_TRIM + M_MMAP_THRESHOLD 4,040 (0) [4,272] 0 0 0
jemalloc 4,046 (7) [4,268] 350 12 3

Trim alone moves the faults around: hash join stops faulting and hash
aggregate starts. Setting both thresholds removes them everywhere and
matches jemalloc. (Our earlier "trim threshold" run had worked because it
also set a 64 MB top pad, which keeps malloc from ever reaching the code
that decides to mmap.)

Yeah, glibc's malloc seems inadequate to make that work properly. You
can always have a big enough TIDBitmap for the trim threshold to be too
small. Out of curiosity: why is only specifying the trim threshold not
enough? It shouldn't matter if it gets the memory via mmap() or sbrk().
The page faults is what hurts.

While I think the direction of keeping the memory around is the right
one, I don't think we should do that at the Bitmap Index Scan (BIS)
level for two reasons:

1. A database with lots of connections could quickly spent gigabytes on
unused BIS buffers. Freeing the memory when unused quickly gets you
into memory allocator territory.

The patch keeps at most work_mem per backend, and only in backends that
ran a large bitmap scan, so 800 MB for 200 such backends at the default.

For comparison, glibc with both thresholds set keeps whatever each
backend's high-water mark was, with no bound at all; jemalloc keeps
dirty pages for 10 s and then gives them back. But before you say it, I
agree the decay is better done by an allocator than by tidbitmap.c.

2. There are more places in the code where we double allocation sizes as
we go and hence cause avalanches of page faults repeatedly. It would
be good to fix them all in one go.

Yes. I added a hash join, a sort and a hash aggregate to the test.
With glibc defaults, the hash join faults 1,199 times per query and the
sort 1,020; the patch does nothing for either. They cost less in total
(4.5% and 9.7% system time against 33% for the bitmap scans), but it's
the same mechanism.

I agree a process-wide fix is the better target, and setting both glibc
thresholds at backend start would be a small one. The patch would still
be worth +5.5% to +11.8% on top of that, from skipping the rehash and
copy of the doubling, but that's a much smaller argument.

Your findings show that the amount of page faults is the problem because
the it causes contenteion on the lruvec lock to install the page.

If we use 2 MiB huge pages for the allocations that problem should go
away. Even if the Bitmap Index Scan or Hash Join needs less memory than
that, the waste is fairly limited and only temporary. With that, we
would also not need to keep the memory around for longer than necessary
because doing the allocation should be very cheap now.

Is anyone aware of an effort to change PostgreSQL to use e.g. jemalloc
which better allows controlling when memory is returned?

One data point against just switching: mimalloc on FreeBSD gets 620 tps
on the btree query, against 3,982 with libc. mimalloc reserves its
arena in the postmaster, every backend inherits it, and on FreeBSD all
of them end up on one shared VM object. Every purge (madvise of 26 MB)
then takes that object's lock: 87% of all CPU time is spent spinning on
it. With MIMALLOC_PURGE_DELAY=-1 it gets 4,030. On Linux, mimalloc
behaves like glibc (724 faults per query). How an allocator interacts
with fork-without-exec is not something allocator benchmarks usually
measure and publicize.

But how does that apply to jemalloc? We're using jemalloc with
PostgreSQL in production without any problems.

But I would anyways first looking into using huge pages backed memory.
IMHO, that would be the best and right solution, regardless of allocator.

The more important part is that the radix tree grows incrementally while
the hash map needs to double in size and then be rehashed. That lowers
the number of page faults considerably.

The faults follow the memory touched per query, though, not the number
of grows. Presizing the table, so the final 1.5 MB is touched once,
took glibc with a low mmap threshold from 703 to 396 faults per query,
and musl from 768 to 424. I'd expect an incrementally grown tree whose
memory is given back after each query to land about there too: half the
faults, not none. That's inference; I haven't measured a radix tree.

Not necessarily. The allocations have better chance to stick around in
the allocator or the memory contexts.

So, where does all this digging this leave us? The kernel side is a
shared per-node lock, and memory given back per query hits it on both
Linux and FreeBSD. The fix probably belongs at the process level rather
than in tidbitmap.c, since hash join and sort have the same problem.

For glibc, setting M_MMAP_THRESHOLD and M_TRIM_THRESHOLD together is
enough; setting only one is not. I can look at what that would mean in
PostgreSQL (where to set it, and what bound to use) unless someone knows
a reason not to.

I would explore the huge pages route next.

--
David Geier

#6Greg Burd
greg@burd.me
In reply to: David Geier (#5)
Re: Keep TIDBitmap pagetable memory across bitmap scans

On Mon, 16 Nov 2026 08:47:33 +0100, David Geier <geidav.pg@gmail.com> wrote:

Thanks for confirming this. So it's the soft page faults that install
the fresh page in the LRU.

Hi David,

Yeah, glibc's malloc seems inadequate to make that work properly. You
can always have a big enough TIDBitmap for the trim threshold to be too
small. Out of curiosity: why is only specifying the trim threshold not
enough? It shouldn't matter if it gets the memory via mmap() or sbrk().
The page faults is what hurts.

Right, the faults are what hurts, and with only the trim threshold set
they still happen, from munmap instead of brk. Setting it also sets
no_dyn_threshold (do_set_trim_threshold() in malloc.c), so the mmap
threshold stops adapting and stays at 128 kB. The pagetable and the
iteration arrays are each well over that, so they are mmapped, and free()
unmaps an mmapped chunk right away. The trim threshold only decides when
to shrink the top of the brk heap, which those chunks are no longer on.

If we use 2 MiB huge pages for the allocations that problem should go
away. Even if the Bitmap Index Scan or Hash Join needs less memory than
that, the waste is fairly limited and only temporary. With that, we
would also not need to keep the memory around for longer than necessary
because doing the allocation should be very cheap now.

I tried it with glibc's own switches. Same setup as before, stock TPS
(faults per query), then patched:

btree bitmapand
glibc defaults 2,734 (692) 4,351 2,201 (1,092) 3,672
THP enabled=always 2,736 (732) 4,341 2,203 (1,090) 3,672
hugetlb=1 (MADV_HUGEPAGE) 3,825 (2) 4,355 3,038 (2) 3,667
hugetlb=2 (MAP_HUGETLB) 4,091 (0) 4,407 3,259 (0) 3,729
both thresholds set 4,055 (0) 4,342 3,244 (0) 3,670

THP alone does nothing: no huge pages get used at all, because the brk
heap grows and shrinks in small steps and never lines up with a 2 MB
boundary I'd imagine.

glibc.malloc.hugetlb=1 rounds the heap to 2 MB and madvises it, which
gets rid of nearly all the faults, but the memory is still given back
each query, so every first touch is now a 2 MB page to zero (about
41,000 THP faults in an 8 s window).

It's also the noisiest arm: stock btree varied 4.7% between runs,
against under 1% for the others. hugetlb=2, with pages from a reserved
pool, gives no faults and matches setting both thresholds. It needs
vm.nr_hugepages sized for the backends' heaps as well as shared_buffers
(about 290 pages in use at 96 clients here), and glibc quietly falls
back to small pages when the pool runs out.

So yes, 2 MB pages do fix the faults. Hash join and sort stop faulting
too (1,198 and 1,020 per query with defaults; 0 under hugetlb=2). What
they don't remove is the rest of the doubling: on top of hugetlb=2 the
patch is still +7.7% on btree and +14.4% on bitmapand, about what it
gives over jemalloc or with both thresholds set. That part is the
rehash and the copy, not the faults.

But how does that apply to jemalloc? We're using jemalloc with
PostgreSQL in production without any problems.

It doesn't, as far as I can tell; I should have been clearer. The
problem was specific to mimalloc, which reserves a 1 GiB arena in the
postmaster, so every backend allocates from the same inherited range.
jemalloc maps memory as each backend needs it, after the fork, and
showed nothing like it: 4,046 TPS and 7 faults per query on Linux, and
on FreeBSD, where libc's malloc is jemalloc, 3,982 and 1.

Not necessarily. The allocations have better chance to stick around in
the allocator or the memory contexts.

I measured that too, and you're right that it's not just half the
faults. I rebased John's PoC v2 onto master, which needed only trivial
conflict fixes, and ran it in the same matrix:

btree bitmapand
stock radix stock radix
glibc defaults 2,728 4,914 2,201 3,388
both thresholds set 4,046 5,460 3,247 4,481

Under glibc defaults it halves the faults (692 to 382 per query on
btree), as I guessed, but that alone already gives +80% on btree; it's
noisier there, varying 4.2% between runs. With memory kept, the radix
tree comes out 26% ahead of my patch on btree (5,460 against 4,342) and
22% on bitmapand (4,481 against 3,670). Most of that is the sort:
building the iteration arrays and sorting them is about 16% of the
patched profile, against about 1% for the radix tree with memory kept,
since it iterates in key order anyway.

The caveat is that John's PoC still has lossification turned off (his
0002), so this measures the data structure, not a finished patch. None
of the bitmaps in this test go lossy, so that doesn't change these
numbers, but it would matter under a small work_mem.

So I think the right direction is the radix tree, plus something at the
process level for the faults. 2 MB pages from a pool, or keeping memory
in the allocator, both work for hash join and sort as well. Keeping the
hash table's memory, as my 0002 does, fixes only one consumer of a
structure that is better replaced. I'd rather put the effort into
helping John's series along: the test module from my 0001 can serve as
its test suite, and I can measure lossify once it's back.

John, would that help?

best.

-greg

#7John Naylor
johncnaylorls@gmail.com
In reply to: Greg Burd (#6)
Re: Keep TIDBitmap pagetable memory across bitmap scans

On Wed, Nov 18, 2026 at 4:11 AM Greg Burd <greg@burd.me> wrote:

So I think the right direction is the radix tree, plus something at the
process level for the faults. 2 MB pages from a pool, or keeping memory
in the allocator, both work for hash join and sort as well. Keeping the
hash table's memory, as my 0002 does, fixes only one consumer of a
structure that is better replaced. I'd rather put the effort into
helping John's series along: the test module from my 0001 can serve as
its test suite, and I can measure lossify once it's back.

John, would that help?

I haven't been following this thread closely, but I'm planning to
return to David's parallel BIS patch as a prerequisite for changing
the data structure.

--
John Naylor
Amazon Web Services

#8David Geier
geidav.pg@gmail.com
In reply to: Greg Burd (#6)
Re: Keep TIDBitmap pagetable memory across bitmap scans

Hi Gred,

If we use 2 MiB huge pages for the allocations that problem should go
away. Even if the Bitmap Index Scan or Hash Join needs less memory than
that, the waste is fairly limited and only temporary. With that, we
would also not need to keep the memory around for longer than necessary
because doing the allocation should be very cheap now.

I tried it with glibc's own switches. Same setup as before, stock TPS
(faults per query), then patched:

btree bitmapand
glibc defaults 2,734 (692) 4,351 2,201 (1,092) 3,672
THP enabled=always 2,736 (732) 4,341 2,203 (1,090) 3,672
hugetlb=1 (MADV_HUGEPAGE) 3,825 (2) 4,355 3,038 (2) 3,667
hugetlb=2 (MAP_HUGETLB) 4,091 (0) 4,407 3,259 (0) 3,729
both thresholds set 4,055 (0) 4,342 3,244 (0) 3,670

THP alone does nothing: no huge pages get used at all, because the brk
heap grows and shrinks in small steps and never lines up with a 2 MB
boundary I'd imagine.

That's curious. But I would also not want to rely on THP. THP makes for
unpredictable performance: there's no guarantee that a huge page can be
allocated and page migration / defragmentation can cause latency spikes.

glibc.malloc.hugetlb=1 rounds the heap to 2 MB and madvises it, which
gets rid of nearly all the faults, but the memory is still given back
each query, so every first touch is now a 2 MB page to zero (about
41,000 THP faults in an 8 s window).

Yes, so we should be able to decide in the code if to use huge pages or
not, based on the allocation size.

It's also the noisiest arm: stock btree varied 4.7% between runs,
against under 1% for the others. hugetlb=2, with pages from a reserved
pool, gives no faults and matches setting both thresholds. It needs
vm.nr_hugepages sized for the backends' heaps as well as shared_buffers
(about 290 pages in use at 96 clients here), and glibc quietly falls
back to small pages when the pool runs out.

It's the same pool that needs to be configured to make the main
PostgreSQL shared memory segment use huge pages. So the user would only
have to configure things once.

So yes, 2 MB pages do fix the faults. Hash join and sort stop faulting
too (1,198 and 1,020 per query with defaults; 0 under hugetlb=2). What
they don't remove is the rest of the doubling: on top of hugetlb=2 the
patch is still +7.7% on btree and +14.4% on bitmapand, about what it
gives over jemalloc or with both thresholds set. That part is the
rehash and the copy, not the faults.

I measured much less but also ran only a single query at a time. Maybe
you're bottlenecking on random DRAM accesses? But that part we would
improve on, at least for bitmap index code by no longer using the radix
tree.

But how does that apply to jemalloc? We're using jemalloc with
PostgreSQL in production without any problems.

It doesn't, as far as I can tell; I should have been clearer. The
problem was specific to mimalloc, which reserves a 1 GiB arena in the
postmaster, so every backend allocates from the same inherited range.
jemalloc maps memory as each backend needs it, after the fork, and
showed nothing like it: 4,046 TPS and 7 faults per query on Linux, and
on FreeBSD, where libc's malloc is jemalloc, 3,982 and 1.

OK.

Not necessarily. The allocations have better chance to stick around in
the allocator or the memory contexts.

I measured that too, and you're right that it's not just half the
faults. I rebased John's PoC v2 onto master, which needed only trivial
conflict fixes, and ran it in the same matrix:

btree bitmapand
stock radix stock radix
glibc defaults 2,728 4,914 2,201 3,388
both thresholds set 4,046 5,460 3,247 4,481

Under glibc defaults it halves the faults (692 to 382 per query on
btree), as I guessed, but that alone already gives +80% on btree; it's
noisier there, varying 4.2% between runs. With memory kept, the radix
tree comes out 26% ahead of my patch on btree (5,460 against 4,342) and
22% on bitmapand (4,481 against 3,670). Most of that is the sort:
building the iteration arrays and sorting them is about 16% of the
patched profile, against about 1% for the radix tree with memory kept,
since it iterates in key order anyway.

The caveat is that John's PoC still has lossification turned off (his
0002), so this measures the data structure, not a finished patch. None
of the bitmaps in this test go lossy, so that doesn't change these
numbers, but it would matter under a small work_mem.

Yes. QPS is not the right metric at this point. But number of page
faults shouldn't change too much with lossification added.

So I think the right direction is the radix tree, plus something at the
process level for the faults. 2 MB pages from a pool, or keeping memory
in the allocator, both work for hash join and sort as well. Keeping the
hash table's memory, as my 0002 does, fixes only one consumer of a
structure that is better replaced. I'd rather put the effort into
helping John's series along: the test module from my 0001 can serve as
its test suite, and I can measure lossify once it's back.

I would generally want a way to be able to use 2 MiB huge pages for temp
buffers such as hash maps or sort buffers. It doesn't only reduce page
faults but also helps with TLB pressure, page table size, etc.

How about adding a MCXT_ALLOC_TRY_2MB_HUGE_PAGES flag which makes it
possible to allocate huge pages via MemoryContextAllocExtended() /
palloc_extended()? If no huge pages can be allocated, the function would
fall back to normal pages.

Alternatively, we could simply use PostgreSQL's dynamic shared memory
(min_dynamic_shared_memory GUC). Dynamic shared memory is supposed to be
used by parallel workers because its part of the main shared memory
segment. But we could just allocate memory from that pool for single
process use as well, see dsm_create().
This would have the advantage of allowing for a lower allocation
granularity and memory wouldn't get zeroed out on allocation.

Once we have a proposal and maybe PoC patch, we should start a new
thread for that

On top of that we should move the handling of MCXT_ALLOC_ZERO from
MemoryContextAllocExtended() / palloc_extended() into the memory context
implementation so that we can allocate via calloc() and possibly save
the memset(). But that's on top.

--
David Geier

#9David Geier
geidav.pg@gmail.com
In reply to: John Naylor (#7)
Re: Keep TIDBitmap pagetable memory across bitmap scans

On 20.11.26 03:24, John Naylor wrote:

On Wed, Nov 18, 2026 at 4:11 AM Greg Burd <greg@burd.me> wrote:

So I think the right direction is the radix tree, plus something at the
process level for the faults. 2 MB pages from a pool, or keeping memory
in the allocator, both work for hash join and sort as well. Keeping the
hash table's memory, as my 0002 does, fixes only one consumer of a
structure that is better replaced. I'd rather put the effort into
helping John's series along: the test module from my 0001 can serve as
its test suite, and I can measure lossify once it's back.

John, would that help?

I haven't been following this thread closely, but I'm planning to
return to David's parallel BIS patch as a prerequisite for changing
the data structure.

That sounds great.

--
David Geier