Skip to content

Allocate explicit huge pages for PostgreSQL shared_buffers on Linux

Size vm.nr_hugepages from postgres -C shared_memory_size_in_huge_pages instead of guessing, choose huge_pages = on or try deliberately, grant the right permissions, and confirm from /proc/meminfo and the postmaster status that the pages are in use.

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_hugepages and persist that, or reserve at boot when the host is too fragmented to do it at runtime.
  • Set huge_pages to on or try with a clear understanding of how each one fails.
  • Confirm the postmaster is genuinely backed by huge pages using /proc/meminfo, /proc/<pid>/status and huge_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=y and CONFIG_HUGETLB_PAGE=y. Every mainstream distribution kernel has both. Windows supports huge_pages too, 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.
  • root or sudo, and the ability to restart the cluster: huge_pages is start-time only.
  • shared_memory_type must be mmap, the default. Under sysv, huge_pages is 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.

Side-by-side comparison of a 64 GiB PostgreSQL shared memory segment mapped with 4 KiB pages against the same segment mapped with 2 MiB huge pages, showing the per-backend page table entry count, the resulting page table memory, and the effective TLB reach in each case

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

Four-stage procedure for enabling explicit huge pages: compute the page count from the server, reserve and persist the sysctl, choose the on or try policy, then verify from proc, with a warning that reserved pages leave the general allocator

  1. 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/hugepages

    Expected:

    HugePages_Total:       0
    Hugepagesize:       2048 kB
    Hugetlb:               0 kB
    hugepages-1048576kB  hugepages-2048kB

    Hugepagesize is the default this kernel will use. The directory listing shows every size the CPU supports; hugepages-1048576kB means 1 GB pages are available, which needs the pdpe1gb CPU flag. If /sys/kernel/mm/hugepages does not exist, the kernel was built without hugetlbfs and you can stop here.

  2. 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 -C to 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_pages

    Expected: a bare integer, for example 8352. That is the page count for the whole shared memory area, not just shared_buffers — the lock tables and everything else sized by max_connections and max_locks_per_transaction are included. -1 means huge pages are unsupported here. On PostgreSQL 13 or 14, where the parameter does not exist, start with huge_pages = try, read VmPeak from the postmaster’s /proc/<pid>/status and divide by Hugepagesize rounding up — less precise, so add more headroom.

  3. Reserve the pages. Add headroom over the computed value. Two or three percent absorbs a modest shared_buffers bump 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_hugepages

    Expected: sysctl echoes vm.nr_hugepages = 8600, and the sysfs file reads back 8600. 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.

  4. Make the reservation persistent. A sysctl -w lasts 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 --system

    Expected: sysctl --system lists the files it reads, including * Applying /etc/sysctl.d/60-postgresql-hugepages.conf ..., then echoes vm.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.

  5. 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-grub

    Expected: Generating grub configuration file ... done. Use sudo grub2-mkconfig -o /boot/grub2/grub.cfg on the RHEL family. After the reboot, cat /proc/cmdline must show the parameters and HugePages_Total must match. Drop the sysctl.d file if you go this route, so the two cannot disagree.

  6. Grant permissions, if your platform needs them. The PostgreSQL manual notes you may need vm.hugetlb_shm_group to let the database user use huge pages, or ulimit -l to let it lock memory. Under the default shared_memory_type = mmap on a current kernel, usually neither is needed — vm.hugetlb_shm_group governs 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=infinity

    Expected: after sudo systemctl daemon-reload, systemctl show -p LimitMEMLOCK postgresql@17-main.service prints LimitMEMLOCK=infinity. Adjust the unit name for your packaging — postgresql.service on the RHEL family.

  7. Set the policy in postgresql.conf. Pick deliberately.

    huge_pages = on

    on means 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 monitor huge_pages_status, because nothing else will tell you.

  8. 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-pager

    Expected: 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 memory after setting huge_pages = on. The accompanying HINT names shared_buffers and max_connections and prints the requested byte count. The reservation is smaller than what the server needs — either you sized it before a shared_buffers change, or sysctl quietly allocated fewer pages than requested. Recompute with postgres -C shared_memory_size_in_huge_pages and compare against HugePages_Total. To get back up fast, set huge_pages = try and restart, then fix the reservation without an outage hanging over you.
  • sysctl -w succeeded but nr_hugepages reads back lower. Memory is fragmented and the kernel could not assemble that many contiguous 2 MiB blocks. Compact first with sudo sysctl -w vm.compact_memory=1, then re-issue the vm.nr_hugepages line 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 HugetlbPages on the postmaster is 0. The reservation exists and nothing is using it. Under huge_pages = try this is the silent fallback: the mapping failed and the server carried on with 4 KiB pages. Check SHOW huge_pages_status, then look for a gap between what is reserved and what the server asked for — a raised shared_buffers, a raised max_connections, or huge_page_size = 1GB with 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_transactions or wal_buffers changes 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.d file is not being read — confirm with sudo sysctl --system and look for its name in the output — or something re-applies a competing value. cloud-init and vendor tuning profiles both write sysctl files on cloud images; check ls /etc/sysctl.d/, and remember a higher-numbered file wins. tuned on 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.