Skip to content

Transparent huge pages and database latency — diagnose THP, then disable it properly

Why transparent huge pages cause p99 latency spikes and resident-memory bloat under Redis, MongoDB, PostgreSQL and MySQL, how to read the kernel counters that prove it, and how to disable THP so it survives a reboot.

If your database shows a sub-millisecond median with p99 spikes into the hundreds of milliseconds, high sys CPU that no query explains, and resident memory well above the size of the working set, transparent huge pages are a prime suspect. THP is a kernel feature that silently promotes ordinary 4 KiB anonymous pages into 2 MiB ones. That is a real win for large sequential workloads and a liability for databases, which fault memory in scattered patterns and fork constantly. The fix is almost always to set enabled to never (or madvise) and make that survive a reboot — but only after you have confirmed THP is what you are actually looking at. This guide covers both halves: the diagnosis, then the three persistence mechanisms that actually work.

What you’ll accomplish

  • Read the current THP policy and huge page size from /sys/kernel/mm/transparent_hugepage/ and know what the bracketed value means.
  • Prove or rule out THP as the cause using AnonHugePages in /proc/meminfo, per-process smaps_rollup, and the thp_* and compact_* counters in /proc/vmstat.
  • Change the policy at runtime and understand exactly what that does and does not undo.
  • Make the setting persistent three different ways — a systemd oneshot unit ordered before the database, a kernel command line parameter, or a tuned profile on the RHEL family — and pick the right one for your host.
  • Know when leaving THP on madvise is the better answer than turning it off.

Prerequisites

  • A Linux host with THP compiled in, which is every mainstream distribution kernel since 2.6.38. Root or sudo for the sysfs writes.
  • On x86-64 the transparent huge page is 2 MiB, matching the PMD level of the page tables. On arm64 with a 4 KiB base page it is also 2 MiB; with a 64 KiB base page it is 512 MiB. Read the value rather than assuming it.
  • Very old RHEL 6 kernels expose the knobs under /sys/kernel/mm/redhat_transparent_hugepage/ instead. Everything else in this guide is identical, only the path changes.
  • This is a host-level setting. Inside a container /sys is read-only, so THP has to be changed on the node, not in the workload.
  • Changing the policy does not split huge pages that already exist. Plan on restarting the database process to see the full effect.

How it works

THP is not the same thing as explicitly reserved huge pages. Reserved hugepages (hugetlbfs, vm.nr_hugepages, the HugePages_Total line in /proc/meminfo) are carved out of memory at boot or on demand, are never swapped, and are only used by applications that deliberately ask for them — PostgreSQL’s huge_pages setting or MySQL’s large_pages. THP is the opposite: nothing asks for it, the kernel just does it, and it applies to anonymous memory the process never opted into.

There are two ways a 2 MiB page appears, and they cost differently.

Two paths that create a transparent huge page: the faulting thread allocating one directly, and khugepaged collapsing 512 small pages in the background

The first is at fault time. When a process touches new anonymous memory and the policy allows it, the kernel tries to hand back a 2 MiB page instead of a 4 KiB one. If a free, correctly aligned 2 MiB block exists, this is fast and strictly good — one TLB entry now covers 512 times more memory. If no such block exists, the defrag setting decides what happens next, and this is where latency comes from. With defrag set to always, the kernel runs direct memory compaction inside the faulting thread, moving pages around to manufacture a contiguous block while your query waits. On a long-running host with fragmented memory that stall is tens to hundreds of milliseconds, and it lands in one request’s tail latency. With madvise or defer, the fault falls back to 4 KiB immediately and compaction is handed to kcompactd in the background.

The second path is khugepaged, a kernel thread that wakes periodically, scans page table entries, and collapses runs of 512 eligible 4 KiB pages into one 2 MiB page. That collapse takes the mapping lock briefly and copies 2 MiB of data each time. It does not sit in a query’s critical path, but it is where the steady background sys time and the khugepaged process at the top of top come from.

Then there is fork. Databases fork constantly — Redis for BGSAVE and BGREWRITEAOF, PostgreSQL for every backend connection. After a fork, parent and child share pages copy-on-write.

Copy-on-write after fork with 4 KiB pages versus a 2 MiB page: the same one-byte write copies 4 KiB in one case and 2 MiB in the other

With 4 KiB pages, a one-byte write in the parent copies 4 KiB. With a 2 MiB huge page, the same write copies the whole 2 MiB. For a Redis instance taking scattered writes during a background save, that is a 512x amplification on both the copy cost and the resident memory growth — which is why a 6 GB dataset can produce a 12 GB RSS mid-save. See Redis memory tuning and sizing maxmemory for how that fits into the rest of the memory budget.

Step-by-step

1. Read the current policy. Three files tell you everything about the current state. The value in square brackets is the active one:

cat /sys/kernel/mm/transparent_hugepage/enabled
cat /sys/kernel/mm/transparent_hugepage/defrag
cat /sys/kernel/mm/transparent_hugepage/hpage_pmd_size
[always] madvise never
always defer defer+madvise [madvise] never
2097152

enabled=always is the setting that gets databases in trouble. 2097152 confirms the 2 MiB page size on this architecture.

2. Confirm THP is actually being used. A policy of always means nothing if no huge pages exist. Check the system total:

grep -E 'AnonHugePages|HugePages_Total|Hugepagesize' /proc/meminfo
AnonHugePages:   6295552 kB
HugePages_Total:       0
Hugepagesize:       2048 kB

Roughly 6 GB is currently backed by transparent huge pages, and no reserved hugepages are configured. That is the signal you want before doing anything else.

3. Attribute it to a process. smaps_rollup aggregates every mapping of one process, so you can see how much of a specific database’s resident memory is huge-page backed:

grep -E '^(Rss|AnonHugePages)' /proc/$(pgrep -o redis-server)/smaps_rollup
Rss:             7340032 kB
AnonHugePages:   6291456 kB

Here almost all of Redis’s resident memory is in 2 MiB pages. If AnonHugePages is a few megabytes, THP is not your problem and you should stop here.

4. Read the allocation and compaction counters. /proc/vmstat keeps monotonic counters since boot. The ratio between them, and how fast they move, is the diagnosis:

grep -E 'thp_fault_alloc|thp_fault_fallback|thp_collapse_alloc|compact_stall|compact_fail' /proc/vmstat
compact_stall 18422
compact_fail 9310
thp_fault_alloc 214883
thp_fault_fallback 40217
thp_collapse_alloc 51190

compact_stall counts the times a thread was made to compact memory synchronously — every one of those is a paused allocation. A compact_fail close to compact_stall means the host paid the stall and did not even get a huge page out of it, which is the worst case. Sample twice a minute apart; a compact_stall climbing by hundreds per minute on a latency-sensitive host is enough evidence on its own.

5. Correlate with system CPU. Compaction and khugepaged both burn kernel time, so the sy column moves with them:

vmstat 1 5
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 3  1      0 812344  91232 4210556    0    0     0    24 8121 15330 21 34 44  1  0

34% system time with modest user time and no I/O wait is characteristic. If you are not sure whether the load is CPU, I/O or something else, work through reading Linux load average and triaging a busy host first.

6. Change the policy at runtime. This takes effect immediately for new faults:

echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
never
never

Existing huge pages are not split by this, and the memory a running database already faulted in stays as it is. Restart the database to get a clean state. If you prefer to keep THP available to applications that explicitly ask for it, write madvise instead of never to enabled.

7. Persist it with a systemd unit. This is the option that works everywhere and is the only one that lets you guarantee ordering relative to the database. Create /etc/systemd/system/disable-thp.service:

[Unit]
Description=Disable transparent huge pages
DefaultDependencies=no
After=sysinit.target local-fs.target
Before=mongod.service redis-server.service postgresql.service

[Service]
Type=oneshot
RemainAfterExit=yes
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

List every database unit on the host in Before=; naming a unit that does not exist is harmless. Then enable it:

sudo systemctl daemon-reload
sudo systemctl enable --now disable-thp.service
systemctl status disable-thp.service
● disable-thp.service - Disable transparent huge pages
     Loaded: loaded (/etc/systemd/system/disable-thp.service; enabled; preset: enabled)
     Active: active (exited) since Tue 2026-07-28 03:41:12 UTC; 2s ago

active (exited) with RemainAfterExit=yes is the correct end state for a oneshot unit.

8. Or persist it on the kernel command line. This applies before any userspace runs, which removes the ordering question entirely. Edit /etc/default/grub and append to the existing value:

GRUB_CMDLINE_LINUX="crashkernel=auto rhgb quiet transparent_hugepage=never"

Regenerate the bootloader configuration with the command for your distribution:

sudo grub2-mkconfig -o /boot/grub2/grub.cfg
sudo update-grub

The first is the RHEL family, the second is Debian and Ubuntu. The parameter accepts always, madvise or never. There is no boot parameter for defrag, so if you want to change that as well you still need the sysfs write or a tuned profile.

9. Or use a tuned profile on the RHEL family. If tuned is running, it owns this setting and will reassert it, so fighting it with a sysfs write is pointless. Check what is active:

tuned-adm active
Current active profile: throughput-performance

throughput-performance, the default on RHEL server installs, sets THP to always. Create /etc/tuned/nothp/tuned.conf inheriting from it:

[main]
include=throughput-performance

[vm]
transparent_hugepages=never
sudo tuned-adm profile nothp
tuned-adm active
Current active profile: nothp

Validate it works

Confirm the policy. The bracket should have moved:

cat /sys/kernel/mm/transparent_hugepage/enabled
cat /sys/kernel/mm/transparent_hugepage/defrag
always madvise [never]
always defer defer+madvise madvise [never]

Confirm existing huge pages are gone after a restart. Until the database restarts, its old huge pages remain mapped:

sudo systemctl restart redis-server
grep AnonHugePages /proc/meminfo
AnonHugePages:         0 kB

Confirm nothing is allocating them any more. Sample the counter twice; with never in place, thp_fault_alloc must be flat:

grep -E 'thp_fault_alloc|compact_stall' /proc/vmstat; sleep 60; grep -E 'thp_fault_alloc|compact_stall' /proc/vmstat
thp_fault_alloc 214883
compact_stall 18422
thp_fault_alloc 214883
compact_stall 18422

Confirm it survives a reboot. This is the step people skip and regret:

sudo reboot
cat /proc/cmdline
cat /sys/kernel/mm/transparent_hugepage/enabled
BOOT_IMAGE=/vmlinuz-5.14.0 root=/dev/mapper/rhel-root ro crashkernel=auto transparent_hugepage=never
always madvise [never]

Troubleshooting

  • enabled reads never but AnonHugePages is still large. Flipping the switch does not split pages that already exist; it only stops new ones being created. Restart the process that owns them and re-check smaps_rollup. If the number persists across a restart, you are looking at reserved hugepages, not THP — check HugePages_Total and the Hugetlb line in /proc/meminfo, which enabled has no effect on.
  • The setting reverts after a reboot even though you wrote to sysfs. A sysfs write is never persistent. On RHEL, CentOS Stream, Rocky and Alma, tuned re-applies its profile at boot and can overwrite what a script set. Run tuned-adm active and tuned-adm verify — if tuned is running, use a profile rather than a script, or the kernel command line, which tuned cannot override.
  • The unit is enabled but the database still started with huge pages. Ordering. Check the unit actually ran before the database with systemd-analyze critical-chain mongod.service. If your database unit is not listed in Before=, systemd is free to start them in parallel. This is also the reason rc.local is the wrong tool: rc-local.service runs late in multi-user.target, well after most database units, so by the time it writes never the database has already faulted in its heap and khugepaged has been collapsing pages for a minute. It is also absent by default on several current distributions.
  • tee: /sys/kernel/mm/transparent_hugepage/enabled: Permission denied in a container. /sys is mounted read-only in containers by design, and THP is a kernel-wide setting with no per-namespace equivalent. Set it on the host, or on Kubernetes with a privileged node-bootstrap DaemonSet or an image customization — not in the application pod.
  • THP is off and the latency spikes did not go away. Then THP was not the cause. Go back to step 4: if compact_stall was flat and AnonHugePages was small before the change, the evidence was never there. Look at swap pressure, NUMA imbalance, or storage — tuning swappiness and swap behaviour covers the neighbouring failure mode, where reclaim rather than compaction is what pauses the thread.

When this is the wrong approach

Turning THP off is a database tuning, not a general one, and never is not automatically the right value.

  • madvise is often the better setting than never. It keeps huge pages for applications that explicitly ask via madvise(MADV_HUGEPAGE) — the JVM with -XX:+UseTransparentHugePages, some analytics and numerical workloads — while leaving databases on 4 KiB pages. Redis’s own startup warning recommends madvise for this reason, and Redis 6.2 and newer opts itself out with the disable-thp yes directive, which calls prctl(PR_SET_THP_DISABLE) for its own process regardless of the system setting. On a mixed-workload host, madvise gets you the fix without the regression.
  • This says nothing about explicitly reserved huge pages. PostgreSQL’s huge_pages = try and MySQL’s large_pages use hugetlbfs, are pre-reserved, never swapped, and never compacted on the fly. They are generally a good idea for a large shared buffer pool. Disabling THP does not disable them, and should not be read as advice against them.
  • PostgreSQL’s shared buffers are not affected by this knob at all. Shared memory is governed by the separate /sys/kernel/mm/transparent_hugepage/shmem_enabled file, which defaults to never. The THP exposure for PostgreSQL is per-backend anonymous memory and the fork cost of new connections, not shared_buffers.
  • The case is weaker for InnoDB than for Redis or MongoDB. MySQL’s buffer pool is one long-lived allocation faulted in early, so it neither triggers repeated compaction nor forks. Measure before applying the same setting you use on a Redis host.
  • On non-database hosts, always can be the faster choice. Build farms, batch analytics and model training touch large contiguous regions and benefit measurably from fewer TLB misses. A fleet-wide transparent_hugepage=never in your base image is a performance regression for those machines.

The authoritative reference is the kernel’s own transparent hugepage documentation, which specifies every sysfs file and counter named above, alongside Redis latency troubleshooting for the fork and copy-on-write side of the problem.

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.