Pre-Calculating HugePages for PostgreSQL

Huge pages (HugeTLB) are one of the most important PostgreSQL tuning steps, and they must be right before the server starts. They matter mainly for stability and reliability, more than for speed. Recently I also came across reports of up to 30% performance gain as an added benefit, but only for very specific workloads.

One challenge is that the huge pages available on the host should be a near perfect fit for what PostgreSQL is going to request:

  • If there are too few, PostgreSQL either refuses to start or quietly runs without huge pages.
  • If there are too many, the extra pages stay unused. Memory set aside for huge pages cannot be used for anything else, so it reduces the memory left for the filesystem page cache.

On a plain Linux host this is easy to fix, as the next sections show. On Kubernetes it is harder: we need to prepare the nodes with enough huge pages before pods can request them. One option is to first set up the cluster without huge pages, read the requirement from the running instance, create nodes with enough huge pages, and then change the pod so that it gets rescheduled onto the new nodes. That is a lot of steps. These discussions made me think about whether the required huge pages can be calculated in advance.

This post covers how huge pages have traditionally been sized for PostgreSQL, and then gives a formula that computes the requirement directly from PostgreSQL parameter values. The formula was derived from the PostgreSQL source code and checked against real PostgreSQL 16, 17 and 18 binaries.

I am not claiming that it is perfect. But it helps if you are looking for a number that is very close.

Background in plain words

If you already know what huge pages and Kubernetes operators are, skip this section.

Memory pages. Linux does not hand out memory byte by byte. It hands it out in fixed-size blocks called pages. The normal page size is 4 kB. For every process, the kernel keeps a page table: a map that says “this page of the process lives at that place in physical RAM”.

The problem with small pages. 8 GB of memory is about 2 million pages of 4 kB. The map for that many pages is large, and looking things up in it takes time. The CPU has a small cache for these lookups, called the TLB, but it can only remember a limited number of pages.

Huge pages. A huge page is simply a bigger page: usually 2 MB, sometimes 1 GB. The same 8 GB needs only 4096 pages of 2 MB. The map becomes about 500 times smaller, and the CPU cache covers much more memory.

Why PostgreSQL cares so much. PostgreSQL keeps its data cache (shared_buffers) in one big block of shared memory, and every connection is a separate process that uses that same block. Each process needs its own map of the shared memory. With 4 kB pages, a map of 8 GB can take up to 16 MB per connection. With hundreds of connections, the maps alone can eat gigabytes of RAM, and the server can run out of memory. With huge pages this cost almost disappears. Huge pages are also never swapped out. This is why huge pages are mostly about stability.

Huge pages must be reserved in advance. The Linux administrator tells the kernel how many huge pages to set aside (the “pool”). This memory is taken away from normal use, whether or not anyone uses it. PostgreSQL then asks for huge pages from this pool when it starts.

A few Kubernetes words used in this post:

Word Meaning
Node A machine (virtual or physical) that runs containers
Pod One or more containers running together on a node. A PostgreSQL instance runs in a pod
Pod specification The description of a pod: image, CPU, memory, and so on
Scheduler The part of Kubernetes that decides which node a pod runs on
Operator A program that runs databases on Kubernetes for you. It creates and updates the pods
Custom resource The YAML file where the user tells the operator what they want, for example “PostgreSQL 17 with shared_buffers = 8GB”

A note on units. In this post, MB and GB mean 1024-based units, the same as PostgreSQL uses. They are the same as Mi and Gi in Kubernetes. So 2 MB = 2Mi = 2097152 bytes.

How huge pages are traditionally calculated

Method 1: start the server and measure it

For many years the PostgreSQL documentation described this procedure: start PostgreSQL without huge pages, find the main PostgreSQL process (the postmaster), and see how big its memory is.

## The first line of postmaster.pid is the process ID of the postmaster $ head -1 $PGDATA/postmaster.pid 4170 ## Find the address space size, which is mostly the shared memory $ grep ^VmPeak /proc/4170/status VmPeak: 6490428 kB ## Check the size of one huge page $ grep ^Hugepagesize /proc/meminfo Hugepagesize: 2048 kB

Then divide: 6490428 / 2048 = 3169.15. We cannot use part of a page, so we round up to 3170 pages.

Note: Later versions of the documentation replaced VmPeak with a pmap command (commit a3739e376fb). VmPeak is the size of everything the process has mapped. pmap picks out only the shared memory, so it is more accurate. But the idea is the same: run the instance first, then measure.

On a plain Linux host, the last step is to tell the kernel to reserve that many pages, and then restart PostgreSQL:

## Reserve 3170 huge pages now $ sudo sysctl -w vm.nr_hugepages=3170 ## Keep the setting after a reboot $ echo "vm.nr_hugepages = 3170" | sudo tee -a /etc/sysctl.conf ## Check that the kernel really got them $ grep ^HugePages_Total /proc/meminfo HugePages_Total: 3170

If the number was wrong, you change it and restart. That is why this is easy on a plain host.

Method 2: ask PostgreSQL (version 15 and later)

PostgreSQL 15 added a parameter that does the arithmetic for you. PostgreSQL computes it from the configuration; you cannot set it yourself.

$ postgres -D $PGDATA -C shared_memory_size_in_huge_pages 3170

This is exact. It includes every internal structure and every preloaded extension. It is the right answer whenever you can use it. But note what it needs: the PostgreSQL binary, the data directory, the final configuration, and a server that is not running. (On a server that is already running, SHOW shared_memory_size_in_huge_pages; gives the same number.)

Method 3: rule of thumb

“shared_buffers plus a bit.” Many runbooks use shared_buffers plus a few percent, or plus a fixed number of pages. It works until somebody raises max_connections or max_locks_per_transaction. These settings also use shared memory, so the old number becomes too small.

Why this does not work for Kubernetes operators

In Kubernetes, huge pages are a pod resource, declared like CPU and memory:

resources: requests: memory: 4Gi # normal memory (4 kB pages) hugepages-2Mi: 8470Mi # huge pages of 2 MB: 8470 MB = 4235 pages limits: memory: 4Gi hugepages-2Mi: 8470Mi

Note that the two are counted separately. Huge pages are not part of memory. This pod gets 4 GB of normal memory plus 8470 MB of huge pages.

A few properties of this resource make the traditional methods awkward:

  • The number is needed before the pod exists. The operator builds the pod specification from the custom resource. Methods 1 and 2 both need a container with the binary and the data directory, which is exactly what has not been created yet.
  • Huge pages are not overcommitted. For CPU and memory, a pod can request a small amount and be allowed to use more (request lower than limit). For huge pages this is not allowed: the request must equal the limit, and the node must already have that many pages reserved. The scheduler places the pod based on this number, so a guess that is too high wastes memory that no other pod can use.
  • A wrong number is expensive to correct. Changing the resource means recreating the pod. For a database that is a restart, and possibly a failover.
  • Too few fails quietly. The default setting is huge_pages = try. It means “use huge pages if possible, otherwise use normal pages”. There is no half way: if the full request cannot be reserved, PostgreSQL falls back to normal pages for the whole shared memory. The pod runs and nobody notices. But the shared memory now counts against the normal memory limit, which was sized on the assumption that shared memory lives in huge pages. In the example above, 8 GB of shared memory would have to fit into a 4 GB limit, so the pod will be killed for using too much memory.
  • On older systems it can even crash. With older container runtimes, PostgreSQL could not see the pod’s huge page limit when it asked for the pages. The request succeeded, and PostgreSQL crashed later with Bus error when it touched the memory. This was fixed in the container runtime specification in 2023, but you may still meet it on older clusters. This post from Crunchy Data explains it in detail.
  • The operator already has the inputs. shared_buffers, max_connections and the rest are in the custom resource. What is missing is a function that turns those values into a page count.

So an operator needs a direct calculation from parameter values. The rest of this post builds one.

What PostgreSQL actually puts in huge pages

PostgreSQL uses huge pages for exactly one thing: the main shared memory segment. This is the one big block of memory that all PostgreSQL processes share. It is created at startup with a single request to the kernel (mmap with the MAP_HUGETLB flag). Nothing else in the server requests huge pages. work_mem , maintenance_work_mem  and parallel query memory are not part of it.

So the calculation is:

huge_pages_needed = ceil( shared_memory_size / huge_page_size )

ceil means “round up to the next whole number”. If the division gives 4220.1, we need 4221 pages.

The hard part is shared_memory_size. In the source this is CalculateShmemSize() in src/backend/storage/ipc/ipci.c. This function asks every part of PostgreSQL “how much shared memory do you need?” and adds up the answers. On a default PostgreSQL 18 instance (shared_buffers = 128MB) the segment is 149.8 MB and breaks down like this:

Structure What it is Size Driven by
Buffer blocks The data cache itself 128.0 MB shared_buffers
Buffer descriptors and related arrays Small records that describe each cached block 1.6 MB shared_buffers
WAL buffers Changes waiting to be written to the transaction log 4.0 MB wal_buffers
Asynchronous I/O handles (18+) Records for read requests that are in progress 5.6 MB backends, io_max_concurrency, io_max_combine_limit
Lock, predicate lock and buffer lookup hash tables Tables to track who holds which lock, and to find blocks in the cache 4.5 MB max_locks_per_transaction, max_pred_locks_per_transaction, backends
SLRU caches (transaction status, subtransactions, multixacts) Small caches for transaction bookkeeping 1.8 MB *_buffers parameters
Everything else about 2 MB backends, mostly fixed

(“Backends” here means PostgreSQL processes: one per connection, plus background workers.)

The data cache is by far the biggest part, but the other parts are not constant. They grow with connections, lock settings and, in PostgreSQL 18, with asynchronous I/O settings. This is why “shared_buffers plus a bit” stops working.

The formula

How to read the formulas

  • × means multiply.
  • min(a, b) is the smaller of the two values. max(a, b) is the larger.
  • np2(x) is the next power of two that is greater than or equal to x. Powers of two are 1, 2, 4, 8, 16 and so on. For example, np2(1000) = 1024, np2(1024) = 1024 and np2(1025) = 2048. PostgreSQL sizes many internal tables this way.
  • Division of page counts, like NB/32, is rounded down.

Inputs

Symbol Meaning
NB shared_buffers in 8 kB pages. For example, 8 GB is 8 × 131072 = 1048576 pages
WB wal_buffers in 8 kB pages. Default -1 means min(max(NB/32, 8), 2048), which is 16 MB once shared_buffers is 512 MB or more
L max_locks_per_transaction (default 64)
PL max_pred_locks_per_transaction (default 64)
TAQS track_activity_query_size in bytes (default 1024)

PostgreSQL sizes most things by process slots, not by max_connections alone. A slot is a reserved seat for one process. At startup PostgreSQL reserves a seat for every process that could ever run: client connections, background workers, replication senders and autovacuum workers. Memory is set aside for every seat, even if the seat stays empty.

MaxBackends = max_connections + max_worker_processes + max_wal_senders + AV AV = autovacuum_max_workers + 1 (PG 14-16) AV = autovacuum_max_workers + 2 (PG 17) AV = autovacuum_worker_slots + 2 (PG 18+) P = MaxBackends + A all process slots B = MaxBackends + max_prepared_transactions lock owners

A is the number of slots for PostgreSQL’s own helper processes (checkpointer, WAL writer and so on). Its value is in the “Version constants” table below. B counts everything that can hold locks: backends, plus prepared transactions, which keep their locks even when no process is attached.

Shared memory size, in bytes

shared_memory_size = BUFFERS + WAL + SLRU + DSM + LOCKS + PREDLOCKS + BACKENDS + AIO + FASTPATH + EXTENSIONS + FIXED

Term Formula
BUFFERS NB × 8332 + 8 × np2(NB + 128) + R × min(NB, 10 000 000)
WAL WB × 8200
SLRU clog × 16552 + other × 8360
DSM min_dynamic_shared_memory (in bytes; default 0)
LOCKS 361 × B × L + 26.4 × np2(B × L)
PREDLOCKS 211.3 × B × PL + 26.4 × np2(B × PL)
BACKENDS B × 5950 + MaxBackends × Cs + P × TAQS + max_replication_slots × 320
AIO (PG 18+ only) P × IOC × (144 + 24 × ICL)
FASTPATH (PG 18+ only) (B + A) × G × 72
EXTENSIONS what shared_preload_libraries modules request
FIXED version constant F

Version constants:

Constant PG 16 PG 17 PG 18
R (bytes per checkpointer request) 24 32 32
Cs (bytes per backend) 1060 1060 1370
A (auxiliary process slots) 6 7 38
F (fixed part) 600000 620000 740000

For PostgreSQL 14 and 15, use the PG 16 column. Their sizing code matches 16, but they were not tested.

Where the numbers come from

Buffers. Each 8 kB buffer costs 8332 bytes: 8192 for the block itself, 64 for its descriptor, 16 for an I/O condition variable (used to wait for a read or write to finish), 20 for a checkpoint sort entry and 40 for its entry in the buffer lookup table (used to find a block in the cache). The np2() part is the bucket array of that lookup table. The last part is the checkpointer’s request queue. Together this is about shared_buffers × 1.023. In plain words: the data cache needs about 2.3% more memory than the shared_buffers value.

WAL. Each WAL buffer is one 8192-byte page plus 8 bytes of bookkeeping.

Locks. The lock table holds B × L entries, with two more tables alongside it. The 361 already includes the 10% safety margin that PostgreSQL adds. The bucket arrays of these tables are sized to a power of two, so the total does not grow smoothly. It jumps in steps; that is the np2() part. Predicate locks, used by serializable transactions, follow the same pattern. They are allocated whether or not anyone uses SERIALIZABLE.

Backends. Every lock owner costs about 5950 bytes and every backend another Cs bytes of per-process records. P × TAQS is the space where each process stores the text of its current query (what you see in pg_stat_activity). Each replication slot costs about 320 bytes.

SLRU caches. These are small caches for transaction bookkeeping, such as “did transaction 12345 commit?”. clog is the number of transaction status buffers, which cost twice as much as the others. other is the sum of the rest.

Version clog other
PG 14–16 min(128, max(4, NB/512)) min(256, max(4, NB/256)) + 80
PG 17+ transaction_buffers subtransaction_buffers + commit_timestamp_buffers + multixact_member_buffers + multixact_offset_buffers + notify_buffers + serializable_buffers

In PG 17+ these are normal parameters. transaction_buffers, subtransaction_buffers and commit_timestamp_buffers default to 0, which means auto-tune: min(1024, max(16, NB/512 rounded down to a multiple of 16)). They reach the cap of 1024 once shared_buffers is 4 GB or more. The other four default to 32, 16, 16 and 32.

Asynchronous I/O (PostgreSQL 18+). PostgreSQL 18 can start several reads at once and collect the results later. It keeps a record (“handle”) for each read in progress.

  • IOC is io_max_concurrency. The default -1 means min(64, max(1, NB / P)).
  • ICL is io_max_combine_limit in 8 kB pages. The default is 16 (128 kB).

On a normally sized server IOC is 64, so this adds about 34 kB per process slot.

Fast-path locks (PostgreSQL 18+). Each process has a small private array for taking common locks quickly. Before PostgreSQL 18 its size was fixed. From 18 it grows with max_locks_per_transaction:

  • G is min(1024, max(1, np2(L) / 16)). With the default L = 64, G is 4.

Fixed part. F covers the many small structures that do not depend on any parameter.

A simpler upper bound

The np2() steps make the exact formula harder to use by hand or in a spreadsheet. If you do not need the exact number, replace LOCKS + PREDLOCKS + B × 5950 with:

B × (6000 + 414 × L + 264 × PL)

This is an upper bound: it assumes the worst case of every np2() step, so it should give a number that is equal to or a little higher than the real one. It never came out below the real value in testing. On average it is about 1% high. It can be up to 8% high when lock tables dominate, for example thousands of connections with a large max_locks_per_transaction.

Two rules of thumb follow from it, with default lock settings:

  • The buffer pool costs shared_buffers × 1.023.
  • Each connection slot costs about 50 kB on PostgreSQL 16 and 17, and about 85 kB on 18.

Worked example

PostgreSQL 17, shared_buffers = 8GB, max_connections = 200, everything else default, 2 MB huge pages.

First the inputs. The defaults used here are max_worker_processes = 8, max_wal_senders = 10, autovacuum_max_workers = 3, max_prepared_transactions = 0 and L = PL = 64.

NB = 8 GB / 8 kB = 1048576 MaxBackends = 200 + 8 + 10 + (3 + 2) = 223 P = 223 + 7 = 230 B = 223 + 0 = 223 B × L = B × PL = 223 × 64 = 14272 np2 = 16384

Then each term. AIO and FASTPATH are zero because this is PostgreSQL 17. DSM and EXTENSIONS are zero because of the defaults.

Term Calculation Bytes
BUFFERS 1048576 × 8332 + 8 × 2097152 + 32 × 1048576 8787066880
WAL 2048 × 8200 16793600
SLRU 1024 × 16552 + (1024 + 1024 + 32 + 16 + 16 + 32) × 8360 34873088
LOCKS 361 × 14272 + 26.4 × 16384 5584730
PREDLOCKS 211.3 × 14272 + 26.4 × 16384 3448211
BACKENDS 223 × 5950 + 223 × 1060 + 230 × 1024 + 10 × 320 1801950
FIXED 620000
Total 8850188459

huge pages = ceil(8850188459 / 2097152) = ceil(4220.1) = 4221

PostgreSQL 17.5 itself reports 4221 for this configuration.

Note that 8 GB of shared_buffers needs 8.24 GB of huge pages. A pod that requests only hugepages-2Mi: 8Gi gets 4096 pages. That is 125 pages short, so PostgreSQL would not use huge pages at all.

Raise max_connections to 800 and the answer becomes 4235 pages on 17, and 4249 on 18.

The calculation as code

This is a sample calculation function an operator could port. It’s a working python code, But consider it as a pseudo code to explain the calculation. It returns the shared memory size in bytes and the number of huge pages.

#!/usr/bin/env python3 """Estimate PostgreSQL shared memory and huge pages from parameter values. Units: shared_buffers / wal_buffers in 8kB pages (wal_buffers -1 = auto), min_dynamic_shared_memory in MB, track_activity_query_size in bytes, io_max_combine_limit in 8kB pages. Set ckpt_cap=False for minor releases older than 14.19 / 15.14 / 16.10 / 17.6.""" import math MB = 1024 * 1024 # F (fixed) ckpt-request per lock-owner per backend aux procs CONST = {16: (600_000, 24, 5950, 1060, 6), 17: (620_000, 32, 5950, 1060, 7), 18: (740_000, 32, 5950, 1370, 38)} def np2(n): # next power of two >= n return 1 << max(0, (int(n) - 1).bit_length()) def shared_memory_bytes(ver, p, quick=False): F, R, c_b, c_s, A = CONST[ver] NB = p["shared_buffers"] if ver >= 18: MaxBackends = p["max_connections"] + p["autovacuum_worker_slots"] + 2 else: MaxBackends = p["max_connections"] + p["autovacuum_max_workers"] + (2 if ver == 17 else 1) MaxBackends += p["max_worker_processes"] + p["max_wal_senders"] P = MaxBackends + A # all process slots B = MaxBackends + p["max_prepared_transactions"] # lock owners L, PL = p["max_locks_per_transaction"], p["max_pred_locks_per_transaction"] WB = p.get("wal_buffers", -1) if WB == -1: WB = min(max(NB // 32, 8), p.get("wal_segment_pages", 2048)) auto = lambda v: v if v else min(1024, max(16, NB // 512 - (NB // 512) % 16)) if ver >= 17: clog = auto(p.get("transaction_buffers", 0)) other = (auto(p.get("subtransaction_buffers", 0)) + auto(p.get("commit_timestamp_buffers", 0)) + p.get("multixact_member_buffers", 32) + p.get("multixact_offset_buffers", 16) + p.get("notify_buffers", 16) + p.get("serializable_buffers", 32)) else: clog = min(128, max(4, NB // 512)) other = min(256, max(4, NB // 256)) + 32 + 8 + 16 + 8 + 16 s = F s += NB * 8332 + 8 * np2(NB + 128) # buffer pool + lookup table s += R * (min(NB, 10_000_000) if p.get("ckpt_cap", True) else NB) # checkpointer queue s += WB * 8200 # WAL buffers s += clog * 16552 + other * 8360 # SLRU caches s += p.get("min_dynamic_shared_memory", 0) * MB # preallocated DSM if quick: s += B * (6000 + 414 * L + 264 * PL) # locks, upper bound else: s += B * c_b s += 361 * B * L + 26.4 * np2(B * L) # heavyweight lock tables s += 211.3 * B * PL + 26.4 * np2(B * PL) # predicate lock tables s += MaxBackends * c_s + P * p.get("track_activity_query_size", 1024) s += p.get("max_replication_slots", 10) * 320 if ver >= 18: s += (B + A) * max(1, min(1024, np2(L) // 16)) * 72 # fast-path lock arrays ioc = p.get("io_max_concurrency", -1) if ioc == -1: ioc = min(64, max(1, NB // P)) s += P * ioc * (144 + 24 * p.get("io_max_combine_limit", 16)) # AIO handles s += p.get("extensions_bytes", 5242880 * 3) # shared_preload_libraries. I would suggest 5MB per extension return int(s) def huge_pages(ver, p, huge_page_kb=2048, quick=False): return math.ceil(shared_memory_bytes(ver, p, quick) / (huge_page_kb * 1024)) if __name__ == "__main__": # Example: PostgreSQL 17, shared_buffers = 8GB, max_connections = 800, other values default version = 17 huge_page_kb = 2048 # Hugepagesize from /proc/meminfo, in kB params = dict(shared_buffers=8 * 131072, # 8 GB, given in 8kB pages (1 GB = 131072) max_connections=800, max_worker_processes=8, max_wal_senders=10, autovacuum_max_workers=3, autovacuum_worker_slots=16, max_prepared_transactions=0, max_locks_per_transaction=64, max_pred_locks_per_transaction=64) size = shared_memory_bytes(version, params) pages = huge_pages(version, params, huge_page_kb) print(f"Shared memory size : {size} bytes ({size / MB:.0f} MB)") print(f"Huge pages needed : {pages} pages of {huge_page_kb} kB each " f"({pages * huge_page_kb / 1024:.0f} MB)")

Output:

Shared memory size : 8895309044 bytes (8483 MB) Huge pages needed : 4242 pages of 2048 kB each (8484 MB)

The second figure, 8484 MB, is the value for hugepages-2Mi in the pod specification. It could be little more than the shared memory size because we can only ask for whole pages.

What parameters alone cannot tell you

The requirement is not decided by parameter values alone. An operator has to know these too.

Huge page size.One instance’s memory can be split into 4242 blocks of 2 MB each, or 9 blocks of 1 GB each. On arm64, the default block size depends on the kernel’s base page size and can be 512 MB. The block size you choose determines the resource name you request: hugepages-2Mi for 2 MB blocks or hugepages-1Gi for 1 GB blocks. PostgreSQL uses the system’s default block size unless you set huge_page_size  to pick a different one.

PostgreSQL version, including the minor version. Same parameters (shared_buffers = 8GB, max_connections = 200), measured:

Version Shared memory 2 MB pages
16.9 8404 MB 4202
17.5 8441 MB 4221
18.6 8450 MB 4225

PostgreSQL 17 made SLRU buffers larger by default. PostgreSQL 18 added asynchronous I/O structures. Minor releases can change the number too: the August 2025 minors (14.19, 15.14, 16.10, 17.6) capped the checkpointer request queue at 10 million entries. Before those releases the term is R × NB with no cap. That matters once shared_buffers  is above 76 GB (which is 10 million pages of 8 kB), and is worth about 250 pages at 200 GB.

Extensions. Libraries in shared_preload_libraries  add their own shared memory, usually sized by their own parameters. pg_stat_statements  adds about 2 MB at its default of 5000 entries, and roughly 390 to 460 bytes for each extra entry depending on version. Other extensions need to be measured one by one. A simple way is to run Method 2 once with the extension and once without, and take the difference.

Build and platform. The constants above are for x86-64 with the default 8 kB block size. Other architectures arrange structures in memory differently (padding), so the sizes can differ a little.

Kernel features. With io_method = io_uring  on PostgreSQL 18, extra ring memory goes into the segment, and how much depends on the kernel and liburing. In one measurement it was 6 to 14 kB per process slot.

Settings that switch huge pages off. huge_pages = off  needs none. With shared_memory_type = sysv , PostgreSQL does not use huge pages on Linux.

What not to add. Parallel query memory and other dynamic shared memory segments do not use huge pages, with one exception: min_dynamic_shared_memory  is taken from the main segment and is counted. Backend private memory (work_mem and so on) is not counted. Transparent Huge Pages (THP) are a separate kernel feature and do not draw from the pool.

How accurate is it?

The formula was checked against real servers, PostgreSQL 16.9, 17.5 and 18.6 on x86-64:

  • 110 random configurations per version, from 28 MB to 7.7 GB, varying every parameter in the formula. The exact size was read from the server’s own startup debug message.
  • 5 large configurations per version, from 24 GB to 300 GB of shared_buffers  and up to 5000 connections, compared with postgres -C shared_memory_size_in_huge_pages .
Formula Result
Full Within one 2 MB page of PostgreSQL’s own number in all 345 cases
Simple upper bound Never below the real value; about 1% high on average, 8% at worst

What was not tested: PostgreSQL 14 and 15 (their sizing code matches 16), PostgreSQL 19, and arm64.

Recommendations for operator environments

  1. Compute the requirement from the parameters in the custom resource, using the PostgreSQL major version and the node’s huge page size.
  2. Add the shared memory of preloaded extensions.
  3. Add a margin of 1%, with a minimum of 2 pages. It covers the formula’s error and small differences between minor versions.
  4. Set the pod’s huge page request and limit to the result, and recompute whenever a parameter in the formula changes. All of them need a restart anyway.
  5. Remember that a hot standby needs max_connections, max_prepared_transactions, max_locks_per_transaction, max_wal_senders and max_worker_processes at least as high as the primary, so replicas need at least as many pages.
  6. After startup, verify. On PostgreSQL 17 and later:
  • SHOW huge_pages_status; -- must be 'on' SHOW shared_memory_size_in_huge_pages; -- compare with what was provisioned

    Consider huge_pages = on instead of try once sizing is automated. With on, PostgreSQL refuses to start if it cannot get its huge pages. A pod that fails to start is easier to notice than one that silently runs without huge pages.

Summary

  • PostgreSQL’s huge page requirement is its shared memory size divided by the huge page size, rounded up.
  • The traditional ways to get it need a running or at least an initialized instance. A Kubernetes operator needs the number earlier, when it writes the pod specification.
  • Shared memory is shared_buffers × 1.023, plus WAL and SLRU buffers, plus lock tables and per-backend structures that grow with max_connections and max_locks_per_transaction, plus asynchronous I/O structures on PostgreSQL 18.
  • The formula in this post reproduces PostgreSQL’s own figure to within one 2 MB page across the tested configurations. The remaining unknowns are the version, the huge page size and preloaded extensions.

The post Pre-Calculating HugePages for PostgreSQL appeared first on Percona.