Enable HugePages for PostgreSQL: A Practical Guide
How HugePages relieve memory-intensive queries: shared_buffers, vm.nr_hugepages, THP — complete with a rollback plan.
Before you start. All values here are starting points, not rules. What fits your server depends on workload, memory and storage. Some steps intervene deeply — reserving kernel memory, dropping caches, restarting the service. Try them on a test system first, and only with a recent backup that you have verified can be restored. On the test system change one thing per step and measure before and after; only then do you bundle the changes into one maintenance window (section 5). Make sure you can undo every change — the rollback plan is in section 7. You are responsible for operating your systems.
Example starting point: A Linux server with plenty of RAM (e.g. 128 GB) and 16 CPU cores, Postgres 18, with
shared_buffers = 256 MB,effective_cache_size = 32 GBandhuge_pages = try. HugePages are practically not configured (HugePages_Total = 4→ 8 MB). Transparent HugePages (THP) is active. We meet this situation — lots of RAM, but Postgres still running with small initial values — regularly in our training courses, and it is exactly the case where tuning pays off most.
HugePages
PostgreSQL benefits from explicit HugePages — noticeably for queries that
touch a lot of shared memory at once, hardly for short index lookups. If
shared_buffers is still at a small value like 256 MB (on a server with
dozens of GB of RAM), the lever is even double: first raise shared_buffers, then enable HugePages. Without the first step,
HugePages bring little.
1. What are HugePages?
Your Linux kernel organises RAM in small units — so-called pages. The standard size is 4 KB. Every single page is mapped to physical memory through an address translation table (the “TLB” = Translation Lookaside Buffer). The TLB has only limited space (typically 64–1024 entries per CPU core).
HugePages are larger pages (2 MB or 1 GB instead of 4 KB). The effect:
- Fewer TLB entries for the same amount of RAM
- Fewer TLB misses
- Faster address translation for large memory regions
Postgres' shared_buffers is exactly such a large, constantly used
memory region — a perfect candidate for HugePages.
Figure: 4 KB pages vs. 2 MB HugePages
2. Where PostgreSQL benefits — and where it does not
Postgres keeps shared_buffers (the database's internal page cache) in
shared memory — a large, constantly used region. Every SELECT,
INSERT or UPDATE accesses this region. Without HugePages,
the kernel has to load TLB entries on every access, which costs CPU cycles.
Where the effect is — the order is reliable, the magnitude depends on your hardware and workload. Measure it on your system instead of taking a number from a table:
| Scenario | Expected gain |
|---|---|
| Analytical joins, large CTEs, wide scans | largest — a single query touches a lot of memory at once |
| Random OLTP with many small queries | small — few pages per query, little to gain |
| Bulk insert | small to moderate, depending on batch size |
Which queries and functions benefit in concrete terms?
Rule of thumb: the larger the area touched at the same time, the larger the HugePages gain. A query that reads only a few rows through an index hardly notices anything. A query that scans millions of rows and builds large intermediate results in memory notices the difference clearly.
Strong beneficiaries:
- Large aggregations/joins over millions of rows (reports, analyses)
- Recurring batch/night jobs that scan the same large tables completely
- Functions (SQL/PL/pgSQL) that iterate over or aggregate large amounts of data
- Long-running calculations with several large CTEs or window functions
Hardly any beneficiaries:
- Single-row lookups by primary key or index
- Small OLTP queries with a tiny working set
Example 1 — the typical winner: a large analytical query
Imagine a table sales with tens of millions of rows. A
query that rolls it up into daily revenue and computes a moving 30-day
average touches huge memory areas and builds large
intermediate results — exactly the scenario in which HugePages save CPU
overhead:
WITH daily_revenue AS (
SELECT date_trunc('day', sold_at) AS day
, category_id
, SUM(amount) AS revenue
FROM sales
WHERE sold_at >= CURRENT_DATE - INTERVAL '2 years'
GROUP BY 1, 2
),
moving AS (
SELECT day
, category_id
, AVG(revenue) OVER (
PARTITION BY category_id
ORDER BY day
ROWS BETWEEN 29 PRECEDING AND CURRENT ROW
) AS avg_30d
FROM daily_revenue
)
SELECT day, category_id, avg_30d
FROM moving
WHERE avg_30d > 10000
ORDER BY day;
Such queries scan millions of rows and hit the shared_buffers
area thousands of times. Without HugePages the CPU pays
a small TLB penalty on each of these hits — over millions of accesses that adds up.
Example 2 — a function that aggregates over a large table
A metric function that recomputes a large table completely on every call (typical for nightly batch calculations) benefits for the same reason:
CREATE OR REPLACE FUNCTION score_per_customer()
RETURNS TABLE(customer_id int, score numeric)
LANGUAGE sql
AS $$
SELECT customer_id
, SUM(amount) / NULLIF(COUNT(*), 0) AS score
FROM sales
WHERE cancelled_at IS NULL
GROUP BY customer_id
$$;
Every call reads the entire large table again through shared_buffers —
a lot of touched memory, many TLB lookups, a clear HugePages candidate.
Example 3 — the opposite: hardly any benefit
A point query by primary key reads only a handful of pages. The TLB share is negligible here — HugePages hardly help:
SELECT * FROM customer WHERE customer_id = 4711;
Remember: HugePages do not speed up “the database” across the board, but specifically memory-intensive large queries and batch functions.
3. Check the current status
3.1 Kernel side
grep -i huge /proc/meminfo
Interpretation:
HugePages_Total→ number of explicit HugePages (configurable viavm.nr_hugepages)HugePages_Free→ of those, freeHugePages_Rsvd→ reserved (e.g. by Postgres)AnonHugePages→ Transparent HugePages (automatic, by the kernel)Hugepagesize→ usually 2048 kB (2 MB)
If HugePages_Total = 0 or very small: Postgres does not use explicit HugePages.
3.2 Postgres side
SHOW huge_pages; -- 'try' | 'on' | 'off'
SHOW huge_pages_status; -- 'on' | 'off' (since PostgreSQL 17; actual state, see 6.1)
SHOW shared_buffers; -- typically 25 % of RAM on dedicated DB servers
SHOW effective_cache_size;
SHOW max_connections;
huge_pages = try (the default) means: PG tries to use HugePages,
but silently falls back to 4 KB pages if none are available. A perfect
mode for “trying does no harm” — but you do not notice that
the effect is missing.
3.3 THP status
cat /sys/kernel/mm/transparent_hugepage/enabled
cat /sys/kernel/mm/transparent_hugepage/defrag
Typical output: always [madvise] never. The brackets show the active
mode. For database servers never is recommended — see section 8.
4. Decision: what to set?
Step A — raise shared_buffers (do this first!)
A value of 256 MB is far too low for a server with dozens of GB of RAM (PostgreSQL's out-of-the-box value is 128 MB). Postgres rules of thumb:
| Server role | shared_buffers |
|---|---|
| Dedicated DB server | 25 % of RAM |
| Server with other large services (e.g. a second DB engine, mail stack) | 10–15 % of RAM |
| Shared hosting | 5–10 % of RAM |
On a server with ~128 GB of RAM that shares the machine with other services,
shared_buffers = 16 GB is a sensible middle way:
- Enough to cache large history and analysis tables generously
- Leaves 100+ GB for the OS file system cache and other services
Important: shared_buffers must not be larger than your available RAM
— and should never be higher than effective_cache_size.
Step B — calculate the right number of HugePages
Formula:
HugePages_needed = (shared_buffers + overhead) / 2 MB
Overhead covers PG metadata (WAL buffers, shared_preload_libraries,
etc.).
The server tells you the exact value. PostgreSQL calculates the number itself:
the parameter shared_memory_size_in_huge_pages (since PostgreSQL 15) states how many pages the
main shared memory area needs at the configured page size. The
PostgreSQL documentation shows how to query it before the server starts
(paths depend on the distribution; shared_buffers is already set to the new value in
postgresql.conf for this):
postgres -D $PGDATA -C shared_memory_size_in_huge_pages
On a running server, SHOW shared_memory_size_in_huge_pages; returns the
need of the running configuration. You enter this value in vm.nr_hugepages;
the documentation considers a larger number appropriate if other
programs on the machine also need HugePages.
Estimate before the change: As a rule of thumb, +10 % on the plain
size of shared_buffers is enough. It also applies to PostgreSQL 14 and older,
which lack the parameter.
Calculation for shared_buffers = 16 GB:
16 GB / 2 MB = 8192 pages
+ 10 % buffer = 9011 → rounded up to 9100
For other values (estimate, rounded up to the next hundred):
shared_buffers |
vm.nr_hugepages (with buffer) |
|---|---|
| 4 GB | 2300 |
| 8 GB | 4600 |
| 16 GB | 9100 |
| 32 GB | 18100 |
💡 Automatic calculator: In the PostgreSQL Configurator & Tuning Calculator (German)
vm.nr_hugepagesis calculated automatically from your chosenshared_buffers, including 10 % overhead and the 2 MB page size, and output as a ready configuration line for/etc/sysctl.d/99-postgresql.conf.
Step C — huge_pages = on instead of try
Recommendation: after a successful test run with try, switch to on.
Advantage: PG no longer starts if HugePages are missing — you notice
configuration regressions immediately instead of silent degradation.
5. Procedure (step by step)
⚠️ Maintenance window required — PG has to be restarted. All queries are aborted, and so are running batch jobs. Plan a window of 10–15 min.
5.1 Preparation
Baseline measurement — for comparison later:
SELECT pid, query_start, state, substring(query, 1, 80) AS q
FROM pg_stat_activity
WHERE state = 'active' AND backend_type = 'client backend'
ORDER BY query_start;
Note the current swap/memory usage:
free -h
grep -i huge /proc/meminfo
sysctl vm.swappiness # starting value for the rollback
Also note the THP values from section 3.3 and the line
GRUB_CMDLINE_LINUX_DEFAULT in /etc/default/grub; the rollback in section 7
needs them.
5.2 Postgres configuration
In /etc/postgresql/18/main/postgresql.conf:
# Memory
# Before: shared_buffers = 256MB
shared_buffers = 16GB
# Before: huge_pages = try
huge_pages = on
# Optional: adjust effective planner settings
# effective_cache_size = 64GB (25-50 % of RAM if the server is heavily Postgres-centric)
# Parallel workers — on 16 CPU cores the default (8) for max_worker_processes is too tight
# Before: max_worker_processes = 8
max_worker_processes = 32
# Before: max_parallel_workers = 12
max_parallel_workers = 16
# max_parallel_workers_per_gather = 4 (stays)
Background on the parallel workers: max_worker_processes is the hard
cap for background workers (parallel queries, logical replication,
extensions). Autovacuum does not count — it has
autovacuum_max_workers with its own slots. The PG default is 8 — too tight on a
16-core server. max_parallel_workers limits how many of these
workers serve parallel queries at the same time; the PostgreSQL documentation
points out that a value above max_worker_processes has no effect.
That is why both grow together, and max_worker_processes keeps some headroom
for logical replication and extensions. More parallel workers than CPU cores
bring little for CPU-bound load, so max_parallel_workers is set to
16 and max_worker_processes to 32. With the default of 8, all
concurrent parallel queries share at most eight workers; when none are left,
the plan runs with fewer workers than planned, in the worst case
serially.
Do not restart yet — prepare the kernel first.
5.3 Kernel side: allocate HugePages
# Allocate now (takes effect immediately, not persistent)
sudo sysctl vm.nr_hugepages=9100
# Verify
grep -i huge /proc/meminfo
# HugePages_Total: 9100
# HugePages_Free: 9100
# HugePages_Rsvd: 0
Important: If the system currently has heavy memory fragmentation, the kernel may allocate fewer than the requested number. Then:
# Compact memory (kernel compaction, only with CONFIG_COMPACTION)
echo 1 | sudo tee /proc/sys/vm/compact_memory
# Additionally release page cache so that larger contiguous blocks become free
# ⚠ Empties the ENTIRE page cache. The database reads cold from disk
# for a while afterwards — do not run at peak load.
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
sudo sysctl vm.nr_hugepages=9100 # try again
If still not enough → restart the system once (clean RAM) and allocate again. The PostgreSQL documentation says the same: repeat the command or reboot; immediately after boot most of the memory can be converted into HugePages.
5.4 Disable Transparent HugePages (THP)
THP and explicit HugePages can run side by side, but THP is discouraged for DB servers:
# Disable live
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
Persistent via GRUB (Debian/Ubuntu):
sudo nano /etc/default/grub
# Append transparent_hugepage=never to your existing GRUB_CMDLINE_LINUX_DEFAULT line
# (the line below is only an example — do not replace your own):
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash transparent_hugepage=never"
sudo update-grub
# Reboot only in the next maintenance window
Alternatively via a systemd unit (takes effect at the next reboot):
sudo tee /etc/systemd/system/disable-thp.service > /dev/null <<'EOF'
[Unit]
Description=Disable Transparent Huge Pages
After=sysinit.target local-fs.target
[Service]
Type=oneshot
ExecStart=/bin/sh -c "echo never > /sys/kernel/mm/transparent_hugepage/enabled"
ExecStart=/bin/sh -c "echo never > /sys/kernel/mm/transparent_hugepage/defrag"
[Install]
WantedBy=basic.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable disable-thp.service
sudo systemctl start disable-thp.service
5.5 Make it persistent (sysctl)
echo 'vm.nr_hugepages = 9100' | sudo tee -a /etc/sysctl.d/99-postgres-hugepages.conf
echo 'vm.swappiness = 10' | sudo tee -a /etc/sysctl.d/99-postgres-hugepages.conf
# Activate without reboot
sudo sysctl --system
5.6 Restart Postgres
sudo systemctl restart postgresql@18-main
# Check status
sudo systemctl status postgresql@18-main
sudo tail -50 /var/log/postgresql/postgresql-18-main.log
In the log, look for lines like:
LOG: database system is ready to accept connections
On errors → see section 9 (troubleshooting).
6. Verification
6.1 HugePages are reserved
grep -i huge /proc/meminfo
Expected:
HugePages_Total: 9100
HugePages_Free: 9100
HugePages_Rsvd: 8200 ← promised to PostgreSQL, not yet in use
AnonHugePages: 0 kB ← THP off; should approach 0 after the restart
From PostgreSQL 17 on, the most reliable proof is PostgreSQL itself:
SHOW huge_pages_status; -- on = the main shared memory area is in HugePages
On older versions — and as a cross-check — /proc/meminfo helps. As soon as PostgreSQL uses
its memory area, HugePages_Free drops below HugePages_Total.
HugePages_Rsvd shows only the part that is promised but not yet touched,
and it goes down over time. If HugePages_Free stays equal to
HugePages_Total and HugePages_Rsvd is 0, PostgreSQL is not using
HugePages.
6.2 Postgres log
sudo grep -i huge /var/log/postgresql/postgresql-18-main.log | tail -5
Expected: no warning like “could not map anonymous shared memory:
Cannot allocate memory”. If PG cannot start with huge_pages = on,
it says so here.
6.3 Performance smoke test
Measure the same query before/after — preferably one of your large aggregations (see section 2):
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*)
FROM sales
WHERE sold_at >= CURRENT_DATE - 30;
Interesting: shared hit=xxx stays high (good!), the execution time
should be noticeably lower.
7. Rollback
If something goes wrong, go back to the original state. You noted the starting values in section 5.1.
# 1. Stop PostgreSQL (it currently holds the HugePages)
sudo systemctl stop postgresql@18-main
# 2. Set postgresql.conf back to the values from before the change
# (example from 5.2: huge_pages = try, shared_buffers = 256MB,
# max_worker_processes = 8, max_parallel_workers = 12)
sudo nano /etc/postgresql/18/main/postgresql.conf
# 3. Release kernel HugePages
sudo sysctl vm.nr_hugepages=0
# 4. Remove the sysctl file and set the noted swappiness value again
sudo rm /etc/sysctl.d/99-postgres-hugepages.conf
sudo sysctl --system
sudo sysctl vm.swappiness=<noted value>
# 5. Set THP back to the noted values (live)
echo <noted value> | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo <noted value> | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
# 6. Remove the permanent THP switch-off, as far as you set it
# systemd unit from 5.4:
sudo systemctl disable --now disable-thp.service
sudo rm /etc/systemd/system/disable-thp.service
sudo systemctl daemon-reload
# GRUB: remove transparent_hugepage=never from GRUB_CMDLINE_LINUX_DEFAULT
# (write back the line you noted in 5.1), then:
sudo update-grub # takes effect at the next reboot
# 7. Start PostgreSQL
sudo systemctl start postgresql@18-main
8. Transparent HugePages (THP) — why switch them off?
THP is not the same as explicit HugePages:
| Feature | Explicit HugePages | Transparent HugePages (THP) |
|---|---|---|
| Allocation | Reserved by the admin | Automatic, by the kernel |
| For shared memory (PG) | ✅ Yes | ❌ No (anonymous pages only) |
| Predictable | ✅ Yes | ❌ Can suddenly fall back |
| Stall risk | None | Occasional latency spikes (stalls) during defrag |
| Recommendation for DB | ✅ Enable | ⚠️ Disable |
The THP “stall” effect: when the kernel decides to consolidate anonymous pages into
2 MB blocks (the khugepaged daemon), this can briefly cause
CPU spikes and latency peaks. For an OLTP database with guaranteed
response time that is bad.
You recognise that khugepaged is running by CPU spikes of the process of that name
in top. After disabling THP it goes away.
THP is only one of several kernel settings that help decide how a database performs. How they work together — swappiness, write-back thresholds, I/O scheduler and the right systemd unit — is covered in our article on the operating system under PostgreSQL (German). For Windows servers there is our article on Windows under the database server (German).
9. Troubleshooting
9.1 Postgres does not start with huge_pages = on
Error: FATAL: could not map anonymous shared memory: Cannot allocate memory
Cause: Too few HugePages allocated. (If the number is enough, a
permission may be missing: the PostgreSQL documentation names vm.hugetlb_shm_group
and the memory-lock limit ulimit -l for the operating system user of the
database server.)
Fix:
grep -i hugepages_total /proc/meminfo
# Compare the value with shared_buffers / 2048 kB
# If too low: raise vm.nr_hugepages or go back to huge_pages = try
9.2 HugePages_Total cannot be set
Symptom: sudo sysctl vm.nr_hugepages=9100 → only 4000 are shown
Cause: Memory fragmentation. The kernel finds no contiguous 2 MB blocks.
Fix (in this order):
# 1. Compact memory, then drop caches — this empties the page cache,
# afterwards the DB reads cold
echo 1 | sudo tee /proc/sys/vm/compact_memory
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
# 2. Try again
sudo sysctl vm.nr_hugepages=9100
# 3. If still not enough: plan a reboot
# (allocate HugePages as early as possible during boot → sysctl.d is enough)
9.3 Memory pressure from too many HugePages
Symptom: Other services suddenly get OOM-killed.
Cause: vm.nr_hugepages × 2 MB is permanently reserved and not
swappable. If that ties up too much of the RAM, too little is left for non-PG processes.
Fix: Reduce the number of HugePages (e.g. from 9100 to 5000) → reduce
shared_buffers accordingly.
9.4 huge_pages = on is enforced, but performance is worse
Unlikely, but possible with an unsuitable workload (very small
shared_buffers, dominant OS cache accesses). Then go back to try and
vm.nr_hugepages = 0. HugePages are no cure-all: whether they pay off
depends mainly on how much memory a single query touches; with a very small
shared_buffers the effect is small anyway (see section 2).
10. Summary and recommendation
Maintenance window (15 min) — all changes together:
shared_buffersfrom 256 MB → 16 GBhuge_pagesfromtry→ onmax_worker_processesfrom 8 → 32 (important parallel lever on 16 cores)max_parallel_workersfrom 12 → 16vm.nr_hugepages = 9100- THP →
never vm.swappiness = 10- Postgres restart
Expected effect on the next compute-intensive analysis or batch run:
| Lever | Gain |
|---|---|
| HugePages | fewer TLB entries per memory access → less management overhead; noticeable only for memory-intensive queries |
shared_buffers much larger |
more hits in its own cache — provided the frequently read part fits in afterwards |
max_worker_processes and max_parallel_workers raised |
more parallel queries get their planned workers, instead of running with fewer or none |
Taken together, I estimate the gain at a factor of 3–5 — by far the largest
share comes from the parallel workers and the larger shared_buffers,
not from HugePages. This is an estimate, not a measurement. It applies to the
starting point described above:
a server with plenty of RAM on which PostgreSQL still runs with small
initial values. If you have already configured sensibly, you get
correspondingly less out of it — and the calculation assumes the load is
CPU-bound and parallelisable. A run that waits for the disk
gains next to nothing from more workers.
A long, CPU-bound batch run whose parallel workers have been starving so far (for example a nightly analysis over large history tables) can get considerably shorter this way — by how much depends on the parallelisable share and can only be measured on your own run. If you operate a batch that can save its progress and resume (resume), you can even run the maintenance window in the middle of it.
References
- PostgreSQL Configurator & Tuning Calculator (German) — works out
vm.nr_hugepages, RAM split and sysctl parameters online - PostgreSQL docs: Linux Huge Pages
- Linux kernel: HugeTLB Pages
- Red Hat Performance Tuning: THP Disable
Frequently Asked Questions (FAQ)
From what amount of RAM do HugePages pay off for PostgreSQL?
There is no fixed limit. The PostgreSQL documentation names the benefit especially for large values of shared_buffers: the larger the memory area, the more management overhead the 2 MB pages save compared with standard 4 KB pages. At a few GB the gain is usually small and grows with the size of the area, most clearly for memory-intensive queries (section 2). Measure it on your system before you put in the effort.
What is the difference between HugePages and Transparent Huge Pages (THP)?
You create explicit HugePages as an administrator (vm.nr_hugepages, also possible at system start); they are reserved and are not swapped out. Transparent Huge Pages (THP) are formed dynamically in the background by the Linux kernel, which defragments memory for it — this can cause latency spikes on databases. For database servers never is the usual recommendation, and this guide follows it (section 8).
How do I check whether PostgreSQL is actually using HugePages?
From PostgreSQL 17 on, most directly with SHOW huge_pages_status;: on means the main shared memory area is in HugePages, off means a fallback to normal pages. On every version, /proc/meminfo (HugePages_Total, HugePages_Free and HugePages_Rsvd) shows whether PostgreSQL is using pages. With huge_pages = try the server silently falls back to normal pages if there are too few, with huge_pages = on it does not start at all in that case; that is why on is the safer setting after the test run.
Go deeper in training
HugePages are one lever among many, and they work only if shared_buffers fits. The interplay of memory, file cache and planner is covered in the seminar PostgreSQL Performance Tuning (German); for installation and operation of the instance, PostgreSQL Administration (German) is the matching course.
In-house training: PostgreSQL Administration
Kernel tuning, memory management (HugePages, overcommit), high availability and backup strategies in an intensive hands-on seminar.
View training PostgreSQL Administration (German)Open source: pg-clusterbackup
Automatic backup of all PostgreSQL clusters on a host (Debian, Ubuntu, RHEL family and Windows): one custom-format dump per database, parallel dumps and generation-based rotation.
Discover the tool on dozent.net