If your PostgreSQL host runs a shared_buffers measured in tens of gigabytes, every backend that maps that segment builds its own page tables for it — millions of 4 KiB entries each — and every buffer access that misses the TLB pays for a multi-level page walk in hardware. Explicit huge pages replace those 4 KiB mappings with 2 MiB ones, cutting the entry count by 512 and widening the CPU’s TLB reach over the pool. This guide covers sizing the reservation with postgres -C shared_memory_size_in_huge_pages rather than guessing, setting vm.nr_hugepages and making it stick, choosing huge_pages = on against try on purpose, the permissions people trip over, and how to prove from /proc that the pages are in use rather than merely reserved. This is a different kernel mechanism from transparent huge pages, and the advice for the two is opposite.
What you’ll accomplish
- Compute the exact number of huge pages your cluster’s shared memory needs, from the server itself.
- Reserve them with
vm.nr_hugepagesand persist that, or reserve at boot when the host is too fragmented to do it at runtime. - Set
huge_pagestoonortrywith a clear understanding of how each one fails. - Confirm the postmaster is genuinely backed by huge pages using
/proc/meminfo,/proc/<pid>/statusandhuge_pages_status. - Measure the page-table memory you got back, and know why the query-time win is smaller and less predictable.
Prerequisites
- A Linux host with
CONFIG_HUGETLBFS=yandCONFIG_HUGETLB_PAGE=y. Every mainstream distribution kernel has both. Windows supportshuge_pagestoo, but everything below is Linux. - Version differences matter.
shared_memory_size_in_huge_pages, which makes the sizing reliable, needs PostgreSQL 15;huge_pages_status, used in validation, needs 16;huge_page_size, for requesting 1 GB pages, needs 14. On 13 and 14 you derive the page count yourself — the fallback is in step 2. rootorsudo, and the ability to restart the cluster:huge_pagesis start-time only.shared_memory_typemust bemmap, the default. Undersysv,huge_pagesis ignored on Linux.- On x86-64 the default huge page size is 2 MiB; on arm64 and POWER it varies. Read it rather than assuming it.
- This is a host-level setting. A container cannot create the reservation; it has to exist on the node and be handed in explicitly.
How it works
PostgreSQL’s shared memory — shared_buffers plus the lock tables, WAL buffers and other fixed structures — is one MAP_SHARED anonymous mapping created by the postmaster and inherited by every backend. Because it is a shared mapping rather than a shared page table, each process builds its own leaf-level entries covering the parts it has touched.
The arithmetic is unforgiving. A 64 GiB segment is 16,777,216 pages of 4 KiB. At 8 bytes per entry that is 128 MiB of page tables per backend that touches the whole pool, so a cluster with a few hundred backends can spend tens of gigabytes of kernel memory describing memory it already has — PageTables in /proc/meminfo is where that shows up. With 2 MiB pages the same segment needs 32,768 entries, roughly 256 KiB per backend. That saving is arithmetic, not a benchmark, and it is the most dependable reason to do this.
The second effect is the TLB. A typical x86-64 core has an L2 TLB of a couple of thousand entries for 4 KiB pages, covering about 8 MiB of address space without a page walk. Random access across a 64 GiB pool misses that constantly, and each miss walks four levels of page tables. Huge pages use separate TLB entries covering 2 MiB each, taking the covered range into the gigabytes and shortening the walk itself, because the PMD entry is the leaf.
Those pages come from a reserved pool, not the general allocator. vm.nr_hugepages tells the kernel how many to carve out; from that moment they are unavailable to anything that has not asked for hugetlbfs memory — not the page cache, not process heap — and they are never swapped. A feature for a database, a liability if you over-reserve.
It is not the mechanism behind transparent huge pages, where the kernel promotes ordinary anonymous pages behind your back and can stall a thread compacting memory to do it. THP should generally still be off on a database host, and turning it off does not disable what this guide sets up. Our guide on transparent huge pages and database latency covers that side, including why THP’s shmem_enabled never applied to shared_buffers anyway.
Step-by-step
-
Confirm huge page support and the default size. Two reads tell you whether this host can do it at all.
grep -E 'Hugepagesize|HugePages_Total|Hugetlb:' /proc/meminfo ls /sys/kernel/mm/hugepagesExpected:
HugePages_Total: 0 Hugepagesize: 2048 kB Hugetlb: 0 kB hugepages-1048576kB hugepages-2048kBHugepagesizeis the default this kernel will use. The directory listing shows every size the CPU supports;hugepages-1048576kBmeans 1 GB pages are available, which needs thepdpe1gbCPU flag. If/sys/kernel/mm/hugepagesdoes not exist, the kernel was built without hugetlbfs and you can stop here. -
Ask the server how many pages it needs. This is the step that replaces guesswork. The parameter is runtime-computed, so the server has to be stopped for
-Cto return it, and you must point at the data directory.sudo systemctl stop postgresql sudo -u postgres /usr/lib/postgresql/17/bin/postgres -D /var/lib/postgresql/17/main -C shared_memory_size_in_huge_pagesExpected: a bare integer, for example
8352. That is the page count for the whole shared memory area, not justshared_buffers— the lock tables and everything else sized bymax_connectionsandmax_locks_per_transactionare included.-1means huge pages are unsupported here. On PostgreSQL 13 or 14, where the parameter does not exist, start withhuge_pages = try, readVmPeakfrom the postmaster’s/proc/<pid>/statusand divide byHugepagesizerounding up — less precise, so add more headroom. -
Reserve the pages. Add headroom over the computed value. Two or three percent absorbs a modest
shared_buffersbump later; more than that is memory taken from the page cache for nothing.sudo sysctl -w vm.nr_hugepages=8600 cat /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepagesExpected:
sysctlechoesvm.nr_hugepages = 8600, and the sysfs file reads back8600. Read it back — this is not optional. The kernel allocates what it can and does not error when it comes up short, so a lower value is the normal signal that memory is fragmented. That case is in troubleshooting. -
Make the reservation persistent. A
sysctl -wlasts until reboot. Write it under/etc/sysctl.d/so it is reapplied.sudo tee /etc/sysctl.d/60-postgresql-hugepages.conf >/dev/null <<'EOF' # 8352 pages needed by shared_memory_size_in_huge_pages, plus headroom vm.nr_hugepages = 8600 EOF sudo sysctl --systemExpected:
sysctl --systemlists the files it reads, including* Applying /etc/sysctl.d/60-postgresql-hugepages.conf ..., then echoesvm.nr_hugepages = 8600. Keep the comment: the next person needs to know the number came from the server, not a blog post. Our notes on sysctl hardening and persistence cover how these files are ordered and overridden. -
Reserve at boot instead, if runtime allocation is unreliable. On a host up for months, or when you want 1 GB pages, do it on the kernel command line where all memory is still free. Append to the existing value in
/etc/default/grub:GRUB_CMDLINE_LINUX="... hugepagesz=2M hugepages=8600"sudo update-grubExpected:
Generating grub configuration file ... done. Usesudo grub2-mkconfig -o /boot/grub2/grub.cfgon the RHEL family. After the reboot,cat /proc/cmdlinemust show the parameters andHugePages_Totalmust match. Drop thesysctl.dfile if you go this route, so the two cannot disagree. -
Grant permissions, if your platform needs them. The PostgreSQL manual notes you may need
vm.hugetlb_shm_groupto let the database user use huge pages, orulimit -lto let it lock memory. Under the defaultshared_memory_type = mmapon a current kernel, usually neither is needed —vm.hugetlb_shm_groupgoverns System V segments only. If a permission error appears at startup, raise the memory lock limit with a systemd drop-in:sudo systemctl edit postgresql@17-main.service[Service] LimitMEMLOCK=infinityExpected: after
sudo systemctl daemon-reload,systemctl show -p LimitMEMLOCK postgresql@17-main.serviceprintsLimitMEMLOCK=infinity. Adjust the unit name for your packaging —postgresql.serviceon the RHEL family. -
Set the policy in
postgresql.conf. Pick deliberately.huge_pages = ononmeans the postmaster refuses to start if the reservation is not there. That is loud, and on a dedicated database host it is what you want: the alternative is a server that comes up looking healthy while quietly running on 4 KiB pages after someone shrank the reservation.try, the default, falls back silently. It is the right choice where one configuration ships to hosts whose sysctls you do not control — but then monitorhuge_pages_status, because nothing else will tell you. -
Restart and read the log. A reload is not enough; this parameter is start-time only.
sudo systemctl start postgresql sudo journalctl -u postgresql -n 20 --no-pagerExpected: the ordinary
database system is ready to accept connections. Nothing in the log announces success with huge pages — which is exactly why the next section exists.
Validate it works
Ask the server directly. On PostgreSQL 16 and newer this is the shortest answer, and the only way to catch a silent fallback under try:
psql -U postgres -c 'SHOW huge_pages_status;'
huge_pages_status
-------------------
on
Check the pool from the kernel side. Four counters, and the relationship between them is the point:
grep -E 'HugePages_|Hugepagesize' /proc/meminfo
HugePages_Total: 8600
HugePages_Free: 6120
HugePages_Rsvd: 2100
HugePages_Surp: 0
Hugepagesize: 2048 kB
Total is what you reserved. Rsvd is committed to a mapping but not yet faulted in — PostgreSQL maps the whole segment at startup, so it starts high and falls as the pool warms. Free still counts reserved pages, so the number genuinely available to anything else is Free minus Rsvd: here 4020. If Free equals Total and Rsvd is 0 on a running server, nothing has claimed the pool and you are on 4 KiB pages.
Attribute the pages to the postmaster. This separates reserved from in use, and tells explicit huge pages apart from THP:
grep -E 'HugetlbPages|AnonHugePages|VmPTE' /proc/$(head -1 /var/lib/postgresql/17/main/postmaster.pid)/status
VmPTE: 220 kB
AnonHugePages: 0 kB
HugetlbPages: 5079040 kB
HugetlbPages counts explicit huge pages faulted in by this process — about 4.8 GiB here, matching Total minus Free above. AnonHugePages at 0 confirms THP is not involved. And VmPTE at a few hundred kilobytes rather than tens of megabytes is the page-table saving from the first diagram, visible on one process.
Look at the host-level number. Compare PageTables in /proc/meminfo before and after at a comparable connection count; on a connection-heavy cluster it can fall by an order of magnitude, and unlike a latency figure it does not need a controlled benchmark to be believable. For query throughput, run your own workload both ways. Expect low single-digit percent on CPU-bound OLTP with a large shared_buffers, and sometimes nothing at all on an I/O-bound one.
Troubleshooting
FATAL: could not map anonymous shared memory: Cannot allocate memoryafter settinghuge_pages = on. The accompanyingHINTnamesshared_buffersandmax_connectionsand prints the requested byte count. The reservation is smaller than what the server needs — either you sized it before ashared_bufferschange, orsysctlquietly allocated fewer pages than requested. Recompute withpostgres -C shared_memory_size_in_huge_pagesand compare againstHugePages_Total. To get back up fast, sethuge_pages = tryand restart, then fix the reservation without an outage hanging over you.sysctl -wsucceeded butnr_hugepagesreads back lower. Memory is fragmented and the kernel could not assemble that many contiguous 2 MiB blocks. Compact first withsudo sysctl -w vm.compact_memory=1, then re-issue thevm.nr_hugepagesline and read it back. If it still falls short, use the boot-time reservation in step 5, where the allocation happens before anything has fragmented memory. Repeated failures are a reason to prefer the kernel command line permanently on that host.- The pages are reserved, but
HugetlbPageson the postmaster is0. The reservation exists and nothing is using it. Underhuge_pages = trythis is the silent fallback: the mapping failed and the server carried on with 4 KiB pages. CheckSHOW huge_pages_status, then look for a gap between what is reserved and what the server asked for — a raisedshared_buffers, a raisedmax_connections, orhuge_page_size = 1GBwith only 2 MiB pages reserved. - It worked, then stopped after a configuration change. Any change to
shared_buffers,max_connections,max_locks_per_transaction,max_prepared_transactionsorwal_bufferschanges the shared memory size and therefore the page count. Recompute after every one. This is why the sizing belongs in configuration management next to the parameters that drive it, not in a one-off shell command. - The reservation is gone after a reboot. Either the
sysctl.dfile is not being read — confirm withsudo sysctl --systemand look for its name in the output — or something re-applies a competing value.cloud-initand vendor tuning profiles both write sysctl files on cloud images; checkls /etc/sysctl.d/, and remember a higher-numbered file wins.tunedon the RHEL family can also own this.
When this is the wrong approach
The win scales with the size of shared_buffers and the number of backends mapping it. On a host with a 2 GiB shared_buffers and twenty connections, the page tables you save amount to a few megabytes; reserving memory the page cache can no longer use costs more than the walk you avoided. As a rough line, this starts earning its operational overhead somewhere above 8 to 16 GiB of shared_buffers.
Containers and Kubernetes are a genuine complication rather than a formality. Huge pages have to be reserved on the node, the kubelet exposes them as a hugepages-2Mi resource the pod must request and limit explicitly, and the pod may need IPC_LOCK. Get any of it wrong and you have taken memory from the node and given nothing to Postgres. If the cluster is not yours to configure, use huge_pages = try and move on. Do not reach for 1 GB pages by default either: they must be reserved at boot, cannot be reclaimed without one, and round the segment up to the next gigabyte.
This is also no substitute for right-sizing. If shared_buffers is oversized for the working set, huge pages only make a wasteful configuration cheaper to walk; if the real problem is hundreds of idle backends, a pooler does more — see PgBouncer connection pooling for PostgreSQL. And none of it changes the transparent huge pages decision, which on a database host is still generally never.
The authoritative references are the PostgreSQL manual on resource consumption parameters and its kernel resources chapter, which documents the Linux huge pages procedure this guide expands on.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.