Linux Internals
Memory Compaction in Linux: How the Kernel Fights Fragmentation
By NileVPS Team · Published · 4 min read
اقرأ المقال بالعربيA Linux server can report gigabytes of free memory and still fail to allocate a single 2 MB block. The reason is fragmentation: free memory exists, but it is scattered in small pieces between pages that are in use. Memory compaction is the kernel's answer. It moves pages around to rebuild large contiguous free areas, which huge pages, some drivers and certain kernel allocations need. Compaction is usually invisible, but when it runs at the wrong moment it can add noticeable latency, so it is worth knowing how it works and how to observe it.
Why contiguous memory matters
The kernel's page allocator, the buddy allocator, hands out memory in blocks of 2^order pages. Order 0 is a single 4 KB page, order 9 is 512 pages, or 2 MB on x86-64, the size of a transparent huge page. Most allocations are order 0, but higher orders are needed for:
- Transparent huge pages and explicit huge pages.
- Some network and storage driver buffers.
- Kernel structures that need physically contiguous memory.
Over time, as processes allocate and free memory, order-0 pages in use end up scattered across RAM. Plenty of free pages remain, but few large blocks.
Seeing fragmentation
/proc/buddyinfo lists, for each memory zone, how many free blocks exist of each order from 0 to 10:
cat /proc/buddyinfoIf the numbers on the right (high orders) are zero or very small while the left columns are large, memory is fragmented. With debugfs mounted, /sys/kernel/debug/extfrag/unusable_index gives a per-order score between 0 and 1, where higher values mean free memory is less usable for that order.
How compaction works
Compaction runs two scanners over a memory zone. A migration scanner starts at the bottom of the zone looking for movable pages in use. A free scanner starts at the top looking for free pages. Movable pages are copied from the bottom to free slots at the top, their page table entries are updated, and the bottom of the zone gradually becomes a contiguous free region.
Only movable pages can be moved. Most user-space memory and page cache is movable. Many kernel allocations, such as slab objects, are not. The kernel groups allocations by mobility type into separate blocks to keep unmovable pages from polluting every region, but this is a best effort, not a guarantee.
When compaction runs
| Trigger | What happens | Latency impact |
|---|---|---|
| Direct compaction | A process requesting a high-order block compacts memory itself before giving up | The requesting process stalls |
| kcompactd | A per-NUMA-node kernel thread compacts in the background when kswapd finishes reclaim | Low; runs asynchronously |
| Proactive compaction | kcompactd compacts preemptively to keep fragmentation below a target | Low, but uses some CPU |
| Manual | An administrator writes to /proc/sys/vm/compact_memory | Brief CPU burst |
Direct compaction is the one to watch. It happens in the context of the application allocating memory, often a page fault that wants a transparent huge page, so the application waits until compaction finishes or fails.
Monitoring compaction
The counters in /proc/vmstat tell you how often each case happens:
grep -E 'compact_(stall|fail|success|daemon_wake)' /proc/vmstatcompact_stallcounts direct compaction events, each one a process that had to wait.compact_failandcompact_successshow how those attempts ended.compact_daemon_wakecounts kcompactd wakeups.
A compact_stall value that climbs steadily under load on a latency-sensitive service is a signal to tune.
Tuning options
Transparent huge page defrag policy. This decides whether page faults may stall to compact:
cat /sys/kernel/mm/transparent_hugepage/defrag
echo defer+madvise | sudo tee /sys/kernel/mm/transparent_hugepage/defragWith defer+madvise, ordinary allocations fall back to small pages and wake kcompactd in the background, while only regions marked with madvise(MADV_HUGEPAGE) compact directly. always gives the most huge pages but the most stalls. The trade-offs between THP and explicit huge pages are covered in HugeTLB vs Transparent Huge Pages.
Proactive compaction. On kernels 5.9 and newer, vm.compaction_proactiveness (0 to 100, default 20) controls how aggressively kcompactd keeps memory defragmented in the background. Raising it moderately can reduce direct compaction for workloads that need many huge pages, at the cost of background CPU. Setting it to 0 disables proactive compaction.
sudo sysctl vm.compaction_proactiveness=30Manual compaction. Before starting a service that needs a large reservation of explicit huge pages, you can trigger compaction once:
echo 1 | sudo tee /proc/sys/vm/compact_memoryMake sysctl changes persistent in a file under /etc/sysctl.d/ only after measuring their effect.
A VPS perspective
On a virtual server, fragmentation happens inside your guest kernel just as on bare metal, and huge pages in the guest still need contiguous guest-physical memory. Long-running instances with a lot of churn, such as busy application servers, are the most likely to fragment. Giving the VM some free memory headroom makes compaction succeed more easily; if your workload is consistently close to the limit, a larger plan from the pricing page may be cheaper than chasing latency spikes.
FAQ
Is it safe to write to /proc/sys/vm/compact_memory on a production server?
It is safe in the sense that it does not lose data, but it causes a short burst of CPU work and page migration. Run it during a quiet period, not as a recurring cron job without a clear reason.
Does memory compaction free memory?
No. Compaction does not reclaim memory; it rearranges used pages so that existing free memory forms larger contiguous blocks. Freeing memory is the job of reclaim, which kswapd and direct reclaim handle.
Should I disable transparent huge pages to avoid compaction stalls?
It is one option, and some databases recommend it. A softer choice is setting the defrag policy to defer+madvise or madvise, which keeps huge pages available for applications that ask for them while preventing most page faults from stalling.