ByteGuideHub
Systems Performance / Kernel Engineering • • 10 min read

Self-Hosted eBPF-Based Kernel Live Memory Defragmentation and Compaction for Latency-Sensitive Workloads

A practical guide to diagnosing memory fragmentation-induced tail latency on self-hosted Linux hosts using eBPF, then applying proactive compaction and hugepage defragmentation strategies safely.

Sponsored / Ad Space

Self-Hosted eBPF-Based Kernel Live Memory Defragmentation and Compaction for Latency-Sensitive Workloads

Quick Summary (TL;DR) Memory fragmentation silently inflates p99/p999 latency on self-hosted Linux hosts by forcing synchronous compaction and direct reclaim onto the allocation fast path. Use eBPF to prove fragmentation is the cause (buddyinfo order failures + alloc_pages stalls), then enable proactive compaction (Linux 5.9+) and tune THP defragmentation to move that work off the hot path. Validate with before/after latency percentiles, automate with systemd + monitoring, and always keep a one-line rollback.

Why Fragmentation Shows Up as Tail Latency

A freshly booted host hands out contiguous page blocks effortlessly. After days or weeks of allocation churn, free memory becomes scattered into small, non-contiguous fragments. When a workload suddenly needs a high-order allocation — a 2 MB transparent hugepage, a large kmalloc, a network ring buffer, or a DMA region — the allocator can’t satisfy it from the free lists.

The kernel then falls back to synchronous compaction (migrating pages inline, on the requesting thread) and possibly direct reclaim. Both run on the allocation fast path, so the unlucky thread that triggers them stalls for milliseconds. That’s your tail latency: the median is untouched, but p999 explodes. Because these stalls are rare and correlated with memory state, they’re nearly invisible to application-level metrics — which is exactly why eBPF is the right lens.

flowchart TD
    A[Workload requests high-order pages] --> B{Contiguous block free?}
    B -- Yes --> C[Fast allocation - low latency]
    B -- No --> D{Synchronous compaction succeeds?}
    D -- Yes --> E[Stall on fast path - tail latency spike]
    D -- No --> F[Direct reclaim + retry]
    F --> G[Multi-ms stall or allocation failure]
    E --> H[Latency percentiles degrade]
    G --> H
    H --> I[eBPF detects alloc_pages stalls + buddyinfo failures]

Prerequisites and Safety Baseline

Before touching tunables, confirm your platform supports the mechanisms and that you have a rollback path.

  • Kernel: 6.1 LTS or newer recommended (proactive compaction landed in 5.9; fixes through 5.15/6.x). Verify CONFIG_COMPACTION=y and CONFIG_TRANSPARENT_HUGEPAGE=y.
  • Observability: bpftrace ≥ 0.19, perf, bpftool, and BTF (/sys/kernel/btf/vmlinux) present.
  • Access: root or CAP_BPF + CAP_PERFMON.
  • Safety baseline: capture current values of every tunable, note the maintenance window, and have a rollback script ready. Never change compaction tunables without a latency baseline (Step 1).
# Snapshot the safety baseline
mkdir -p /root/mem-tuning-backup
cp /proc/sys/vm/compaction_proactiveness /root/mem-tuning-backup/ 2>/dev/null
cp /proc/sys/vm/compact_unevictable_allowed /root/mem-tuning-backup/ 2>/dev/null
cat /sys/kernel/mm/transparent_hugepage/defrag > /root/mem-tuning-backup/thp_defrag
uname -r && grep -E 'CONFIG_(COMPACTION|TRANSPARENT_HUGEPAGE)' /boot/config-$(uname -r)

Step 1: Establish a Latency and Allocation Baseline

You cannot fix what you haven’t measured. Capture two baselines for at least 24 hours (ideally a full workload cycle):

  1. Application latency: p50/p99/p999 from your service’s own histograms or a sidecar like hdrhistogram.
  2. Allocator pressure: periodic buddyinfo and vmstat snapshots.
# Log free-block counts per order (order 0 = 4KB ... order 10 = 4MB)
while true; do
  echo "$(date +%s) $(grep -E 'Normal|DMA32' /proc/buddyinfo)"
  sleep 10
done >> /var/log/buddyinfo.log &

# Track compaction and THP activity
vmstat -w 10 | awk '{print strftime("%s"), $0}' >> /var/log/vmstat.log &

A healthy host keeps meaningful free counts at order 9–10. If those columns trend toward zero while order 0 stays high, you have external fragmentation.

Step 2: Observe the Page Allocator with eBPF

Now prove the stalls reach your workload. Trace the time spent inside __alloc_pages and attribute slow calls to stack traces.

# Histogram of alloc_pages latency (µs), showing only slow tails
bpftrace -e '
kprobe:__alloc_pages {
  @start[tid] = nsecs;
}
kretprobe:__alloc_pages /@start[tid]/ {
  $d = (nsecs - @start[tid]) / 1000;
  @us = hist($d);
  if ($d > 500) { @slow[comm] = count(); }
  delete(@start[tid]);
}
interval:s:30 { print(@us); print(@slow); clear(@start); clear(@slow); }'

Run for short windows (30–60 s) to keep overhead low. A bimodal histogram — a tight cluster under 10 µs plus a fat tail past 500 µs — is the fingerprint of synchronous compaction and reclaim. Correlate those spikes with your p999 timeline. If they align, fragmentation is a credible cause; if not, investigate scheduler or lock contention first.

Step 3: Quantify External Fragmentation and Hugepage Availability

Translate raw buddyinfo into a fragmentation index and check THP supply.

# Fragmentation index: 1 - (largest free block / total free pages)
awk '/Normal/ {
  total=0; max=0;
  for (i=2; i<=NF; i++) { p=$i*(2^(i-2)); total+=p; if ($i>0) max=2^(i-2); }
  printf "total_free=%d largest_block=%d frag_index=%.3f\n", total, max, 1-(max/total);
}' /proc/buddyinfo

cat /proc/meminfo | grep -E 'AnonHugePages|Compact|Direct'
cat /sys/kernel/mm/transparent_hugepage/enabled

A fragmentation index above ~0.9 combined with rising compact_stall in /proc/vmstat means the allocator is fighting for contiguity. Watch thp_fault_alloc vs thp_fault_fallback — a high fallback ratio means THP requests are failing and falling back to 4 KB pages.

Step 4: Choose Between Proactive Compaction and Hugepage Defragmentation

These share the compaction engine but differ in trigger and target. Pick based on what your workload actually needs.

flowchart LR
    A{Fragmentation confirmed?} -- No --> Z[Investigate scheduler/IO/locks]
    A -- Yes --> B{Workload needs THP or high-order allocs?}
    B -- Yes, THP-heavy --> C[Tune THP defrag = madvise or defer+madvise]
    B -- Mixed / general --> D[Enable proactive compaction]
    C --> E[Set compaction_proactiveness 20-40]
    D --> E
    E --> F[Validate p999 + buddyinfo]
  • Proactive compaction (/proc/sys/vm/compaction_proactiveness, 0–100, default 20) runs asynchronously in kcompactd and keeps memory defragmented in the background so the fast path stays fast. Set it to 20–40 for latency-sensitive hosts.
  • THP defrag (/sys/kernel/mm/transparent_hugepage/defrag) controls whether THP faults trigger synchronous compaction. always maximizes hugepages but causes stalls; madvise is the safe default for latency-sensitive services; defer+madvise (5.16+) defers to kcompactd and is the best of both.

Step 5: Apply Tunables Safely with a Rollback Plan

Change one thing at a time, measure, and keep the rollback in your shell history.

# 1. Enable proactive compaction (async, off the fast path)
echo 30 > /proc/sys/vm/compaction_proactiveness

# 2. Prefer deferred THP defrag over synchronous stalls
echo defer+madvise > /sys/kernel/mm/transparent_hugepage/defrag

# 3. Persist via sysctl / tmpfiles
cat >> /etc/sysctl.d/99-mem-compaction.conf <<'EOF'
vm.compaction_proactiveness = 30
EOF
cat > /etc/tmpfiles.d/thp-defrag.conf <<'EOF'
w /sys/kernel/mm/transparent_hugepage/defrag - - - - defer+madvise
EOF

# Rollback (one line each)
# echo 20 > /proc/sys/vm/compaction_proactiveness
# echo madvise > /sys/kernel/mm/transparent_hugepage/defrag

To force a one-time defrag during a maintenance window (no reboot, no cache drop):

echo 1 > /proc/sys/vm/compact_memory
# or per NUMA node:
echo 1 > /sys/devices/system/node/node0/compact

Step 6: Validate, Monitor, and Automate

Re-run the Step 1–2 baselines for the same duration. Success looks like: p999 down, compact_stall flat, buddyinfo order 9–10 healthy, and thp_fault_fallback reduced. Then automate detection so regressions page you before users notice.

# Prometheus node_exporter already exposes node_vmstat_compact_stall,
# node_buddyinfo, and THP counters. Alert on:
#   rate(node_vmstat_compact_stall[5m]) > 0.1
#   fragmentation_index > 0.92 for 15m
# Schedule a nightly gentle defrag if the index is high:
cat > /etc/cron.d/nightly-compact <<'EOF'
0 3 * * * root [ "$(awk '/Normal/{t=0;m=0;for(i=2;i<=NF;i++){t+=$i*(2^(i-2));if($i>0)m=2^(i-2)};printf "%.0f",(1-(m/t))*100}' /proc/buddyinfo)" -gt 92 ] && echo 1 > /proc/sys/vm/compact_memory
EOF

Comparison Table: Compaction and Defragmentation Strategies

StrategyTriggerRuns OnCPU CostStall RiskBest For
Proactive compactionkcompactd backgroundkcompactd threadsLow, rate-limitedNone on fast pathGeneral latency-sensitive hosts
THP defrag alwaysTHP faultRequesting threadHigh, burstyHigh (sync)Batch/throughput jobs
THP defrag madvisemadvise(MADV_HUGEPAGE)Requesting threadModerateModerateServices that opt in
THP defrag defer+madvisekcompactd deferredkcompactdLowMinimalLatency-critical services
Manual compact_memoryAdmin writeDirectOne-shotBriefMaintenance windows
Per-node nodeN/compactAdmin writeDirectOne-shotBriefNUMA-targeted cleanup

Common Pitfalls and How to Avoid Them

  • Chasing fragmentation without proof. Confirm with buddyinfo + eBPF stalls first; otherwise you may tune the wrong subsystem.
  • Setting compaction_proactiveness to 100. It burns CPU for diminishing returns. Stay in 20–40.
  • Leaving THP defrag on always. This is a classic hidden tail-latency source. Use defer+madvise.
  • Dropping caches as a “fix.” It forces cold-start page faults and doesn’t defragment. Avoid.
  • Long-running high-frequency eBPF probes. Cap capture windows and aggregate per-CPU to keep overhead negligible.
  • Forgetting persistence. /proc and /sys writes vanish on reboot — use sysctl.d and tmpfiles.d.

Conclusion

Fragmentation-induced tail latency is a memory-state disease with a fast-path symptom. The workflow is always the same: measure application percentiles and buddyinfo, prove the link with eBPF allocator tracing, choose the right lever (proactive compaction for general hosts, deferred THP defrag for THP-heavy services), apply one change at a time with rollback ready, and automate monitoring so the next regression is caught early. Done this way, you can defragment live production memory without reboots, cache drops, or guesswork — and turn unpredictable p999 spikes into a flat, boring line.

FAQ

Does enabling proactive compaction increase CPU usage on latency-sensitive hosts? Yes, but usually modestly. Proactive compaction runs in the background and is rate-limited by compaction_proactiveness and the kcompactd threads. On most hosts the CPU cost is a few percent of a single core — far cheaper than the multi-millisecond stalls caused by direct reclaim and synchronous compaction on the allocation fast path. Measure with eBPF and perf before and after enabling it.

Can I defragment memory without rebooting or dropping caches? Yes. Proactive compaction, kcompactd, and hugepage defragmentation all operate on live memory. You can trigger compaction on demand by writing to /proc/sys/vm/compact_memory, and you can compact a specific node with /sys/devices/system/node/nodeN/compact. Dropping caches is not required and is generally counterproductive because it forces cold-start page faults.

What is the difference between proactive compaction and hugepage defragmentation? Proactive compaction asynchronously migrates movable pages to create contiguous free blocks for any high-order allocation. Hugepage defragmentation is a related mechanism that specifically targets the creation of 2 MB contiguous regions for transparent hugepages, controlled by /sys/kernel/mm/transparent_hugepage/defrag. They share the compaction engine but differ in trigger policy and target.

How do I know if fragmentation is actually causing my tail latency? Correlate three signals: elevated p99/p999 latency, high /proc/buddyinfo order-9 or order-10 failures, and eBPF traces showing long stalls in alloc_pages or direct compaction paths. If tail latency spikes align with high-order allocation failures or direct reclaim events, fragmentation is a credible cause. If not, look at scheduler, I/O, or lock contention first.

Is it safe to run eBPF tracing tools in production? Yes, with care. Use low-overhead tools such as bpftrace with sampling or short capture windows, avoid attaching to every allocation event for long periods, and prefer per-CPU aggregation. Test in staging first, cap the number of probes, and always have a way to detach probes quickly. Modern kernels with BTF make this significantly safer.

Which kernel version should I run for reliable proactive compaction? Proactive compaction landed in Linux 5.9, and several fixes and tunables improved through 5.15 and 6.x. For production self-hosted hosts, 6.1 LTS or newer is recommended. Check that CONFIG_COMPACTION and CONFIG_TRANSPARENT_HUGEPAGE are enabled, and verify the presence of /sys/kernel/mm/transparent_hugepage/defrag and compaction_proactiveness.

Sponsored / Ad Space