ByteGuideHub
Systems Performance / Memory Architecture • • 10 min read

Self-Hosted eBPF-Based Kernel Memory Tiering and CXL-Aware Page Migration for Heterogeneous Memory Systems

Build a self-hosted memory tiering stack: use eBPF to observe NUMA and CXL access patterns, then drive automatic page migration across DRAM, CXL memory, and NVMe tiers for AI and database workloads.

Sponsored / Ad Space

Self-Hosted eBPF-Based Kernel Memory Tiering and CXL-Aware Page Migration for Heterogeneous Memory Systems

Quick Summary (TL;DR) Modern servers increasingly mix fast DRAM, slower-but-cheaper CXL-attached memory, and NVMe-backed swap. Linux 6.6+ ships memory-tiering primitives (NUMA demotion, memory_tiering sysfs, dax_kmem hotplug), but the kernel’s default heuristics are workload-agnostic. This guide shows you how to build a self-hosted control plane: use eBPF to sample page-fault and NUMA-hinting behavior per cgroup, feed those aggregates into a policy engine, and drive page migration via process_madvise() and kernel tiering knobs. You’ll end up with an autonomous, observable tiering stack tuned for AI inference and database workloads—typically at 1–2% CPU overhead.


Why Heterogeneous Memory Needs a Tiering Control Plane

The economics of memory have split. DDR5 remains expensive per gigabyte; CXL-attached DRAM is cheaper and denser but adds latency (roughly 150–250 ns versus 80–100 ns for local DRAM); NVMe is cheapest but orders of magnitude slower. A single workload—say, a 70B-parameter model’s KV cache or a Postgres buffer pool—will have hot pages that must live in local DRAM and warm pages that tolerate CXL latency.

The kernel can already demote cold pages and promote hot ones, but it does so using generic NUMA-balancing heuristics that don’t know your SLOs, your cgroup boundaries, or which pages belong to which tenant. That gap is exactly where a self-hosted eBPF control plane earns its keep: observe at the kernel level, decide at the application level, act through stable kernel interfaces.

Prerequisites and Hardware Topology Baseline

Before writing a line of policy code, confirm the platform can support tiering.

RequirementDetailVerify With
Kernel6.6+ LTSuname -r
Config: NUMACONFIG_NUMA=ygrep NUMA /boot/config-$(uname -r)
Config: TieringCONFIG_MEMORY_TIERING=ysame
Config: CXLCONFIG_CXL_BUS, CONFIG_DEV_DAX_KMEMsame
eBPF CO-RECONFIG_DEBUG_INFO_BTF=yls /sys/kernel/btf/vmlinux
Toolchainclang, libbpf, bpftool, python3bpftool version
CXL hardwareCXL 2.0+ Type-3 device (optional for dev)`lspci

You can build and validate the entire pipeline on a plain two-socket NUMA machine by treating the remote node as a stand-in “slow tier.” Add real CXL once the loop is proven.

Step 1: Map Your Memory Topology (NUMA, CXL, NVMe)

Inventory first. CXL memory appears either as a new NUMA node (via dax_kmem) or as a memory-only node with no CPUs. Capture the baseline:

# NUMA nodes, distances, and per-node memory
numactl -H
cat /sys/devices/system/node/node*/meminfo | grep MemTotal

# Memory tiers as the kernel sees them
ls /sys/devices/virtual/memory_tiering/
cat /sys/devices/virtual/memory_tiering/*/nodelist

# CXL regions and decoders
cxl list -M -R -D 2>/dev/null || ls /sys/bus/cxl/devices/

# Confirm dax_kmem brought CXL online as a node
dmesg | grep -iE 'dax_kmem|numa.*node'

Record node IDs and their distance values from numactl -H. Those distances become the weights your policy engine uses to decide whether a promotion is worth the TLB shootdown cost.

Step 2: Enable Kernel Memory Tiering Primitives

Turn on the kernel’s built-in machinery so your policy engine has a floor to build on.

# 1. Enable automatic NUMA balancing (drives hinting faults)
echo 1 > /proc/sys/kernel/numa_balancing

# 2. Allow demotion to slower tiers under pressure
sysctl -w vm.demotion_enabled=1
sysctl -w vm.numa_demotion_enabled=1

# 3. Set a scan rate that samples, not thrashes
sysctl -w kernel.numa_balancing_scan_delay_ms=1000
sysctl -w kernel.numa_balancing_scan_period_min_ms=1000
sysctl -w kernel.numa_balancing_scan_period_max_ms=60000

# 4. Persist across reboots
cat >> /etc/sysctl.d/90-tiering.conf <<'EOF'
kernel.numa_balancing = 1
vm.demotion_enabled = 1
vm.numa_demotion_enabled = 1
EOF

The kernel’s tiering is conservative by design. Your eBPF layer will add application-aware pressure on top of it—not replace it.

Step 3: Observe Access Patterns with eBPF

This is the heart of the system. The goal is not per-page decisions in the hot path, but aggregated histograms keyed by cgroup and virtual address range. Two tracepoints carry most of the signal:

  • numa_hint_faults / numa_hint_faults_local — the kernel’s own sampling of NUMA locality.
  • mm_page_alloc and the migrate_misplaced_* tracepoints — where pages land and how often they move.

A minimal CO-RE program (attached via bpftrace for prototyping, then ported to libbpf):

// tier_sample.bpf.c — sketch: aggregate hint faults per cgroup
struct key { u64 cgroup_id; u32 node; };
struct { __uint(type, BPF_MAP_TYPE_HASH);
         __type(key, struct key);
         __type(value, u64);
         __uint(max_entries, 16384); } fault_counts SEC(".maps");

SEC("tp/numa/numa_hint_faults")
int on_hint_fault(void *ctx) {
    struct key k = {};
    k.cgroup_id = bpf_get_current_cgroup_id();
    k.node = bpf_get_numa_node_id();
    u64 *v = bpf_map_lookup_elem(&fault_counts, &k);
    if (v) __sync_fetch_and_add(v, 1);
    else { u64 one = 1; bpf_map_update_elem(&fault_counts, &k, &one, 0); }
    return 0;
}
char LICENSE[] SEC("license") = "GPL";

Prototype quickly with bpftrace:

bpftrace -e '
tracepoint:numa:numa_hint_faults {
  @faults[cgroup, args->nid] = count();
}
interval:s:5 { print(@faults); clear(@faults); }'

Ship aggregates to userspace every few seconds via a ring buffer or map iteration. That 5-second cadence is the right granularity—fast enough to catch phase changes in inference traffic, slow enough to avoid overhead.

Step 4: Build the Migration Policy Engine

The policy engine is a long-running userspace daemon (Python or Go) that consumes eBPF aggregates and emits migration actions. Keep its logic explicit and testable.

flowchart TD
    A[eBPF samplers<br/>hint faults, allocs] --> B[Aggregate per cgroup/node<br/>every 5s]
    B --> C{Hot ratio > promote_threshold<br/>for N windows?}
    C -- Yes --> D[Promote: process_madvise<br/>MADV_COLD off / migrate to fast node]
    C -- No --> E{Cold ratio > demote_threshold<br/>and cooldown expired?}
    E -- Yes --> F[Demote: MADV_PAGEOUT<br/>or vm.demotion]
    E -- No --> G[Hold]
    D --> H[Rate limiter<br/>pages/sec per cgroup]
    F --> H
    H --> I[Log + emit Prometheus metrics]
    I --> B

Key design rules:

  1. Hysteresis is mandatory. Require a range to be hot for 3 consecutive windows before promotion; require a longer cooldown before demotion.
  2. Rate-limit per cgroup. Never migrate more than, say, 5,000 pages/sec for a single tenant.
  3. Work in address ranges, not single pages. process_madvise() operates on iovecs; batch aggressively.
# policy_engine.py — core loop (sketch)
PROMOTE_WINDOWS = 3
DEMOTE_COOLDOWN_S = 60
MAX_PAGES_PER_SEC = 5000

def decide(samples, state, now):
    actions = []
    for (cg, node), faults in samples.items():
        hot = faults > state.threshold_for(cg)
        state.streak[cg] = state.streak.get(cg, 0) + 1 if hot else 0
        if state.streak[cg] >= PROMOTE_WINDOWS and node != state.fast_node:
            actions.append(("promote", cg, node))
        elif (not hot and now - state.last_demote.get(cg, 0) > DEMOTE_COOLDOWN_S):
            actions.append(("demote", cg, node))
    return rate_limit(actions, MAX_PAGES_PER_SEC)

Step 5: Wire eBPF Signals to Page Migration

Two stable interfaces do the actual work:

  • process_madvise(2) — apply MADV_COLD, MADV_PAGEOUT, or (tier-aware) hints to a target process’s address ranges without stopping it.
  • move_pages(2) — explicit node placement for ranges you’ve already identified as hot.
// migrate.c — promote a range to the fast node
#include <numaif.h>
int promote(pid_t pid, void *addr, size_t len, int fast_node) {
    void *pages[1] = { addr };
    int nodes[1] = { fast_node };
    int status[1];
    return move_pages(pid, 1, pages, nodes, status, MPOL_MF_MOVE);
}

For demotion, prefer process_madvise(fd, &iov, 1, MADV_PAGEOUT, 0) on the target PID’s /proc/<pid> fd—the kernel then reclaims to the slow tier using its own demotion path, which is safer than forcing explicit placement under memory pressure.

sequenceDiagram
    participant W as Workload (PID)
    participant E as eBPF Sampler
    participant P as Policy Engine
    participant K as Kernel MM
    W->>E: page faults / hint faults
    E->>P: aggregates (cgroup, node, faults)
    P->>P: hysteresis + rate limit
    P->>K: process_madvise / move_pages
    K->>W: pages migrated (TLB shootdown)
    K-->>E: migrate_misplaced tracepoints

Step 6: Validate with AI and Database Workloads

Validate against two archetypes because their access patterns differ sharply:

  • AI inference — KV-cache grows monotonically; hot set is the current attention window. Expect frequent promotions early, steady state after.
  • Database — buffer pool has a stable hot set; demotions should be rare once warmed.
# AI: measure p99 latency and tier occupancy during a load test
python bench_infer.py --model llama --concurrency 32 &
watch -n2 'grep -E "MemTotal|MemFree" /sys/devices/system/node/node*/meminfo'

# Database: watch buffer-pool hit ratio and demotion counters
psql -c "SELECT * FROM pg_stat_bgwriter;" &
watch -n2 'grep -E "pgdemote|pgpromote|numa_pte" /proc/vmstat'

Success criteria: p99 latency stays within 10% of the all-DRAM baseline while ≥30% of the working set lives on CXL.

Tier Comparison and Cost-Per-GB Tradeoffs

TierLatencyBandwidthCost/GB (approx.)Best For
Local DDR5~80–100 ns~400 GB/s$$$$Hot KV cache, buffer pool hot set
CXL-attached DRAM~150–250 ns~64–128 GB/s$$Warm pages, model weights, cold buffers
NVMe (swap/zswap)~10–100 µs~7 GB/s$Cold anonymous pages, spillover

The break-even rule of thumb: promote a page to local DRAM only if its expected access frequency × latency saving exceeds the migration cost amortized over its residency. Your hysteresis thresholds encode that tradeoff empirically.

Operational Guardrails and Failure Modes

  • Thrashing — if promotion and demotion rates converge, widen thresholds and lengthen cooldowns.
  • eBPF ring-buffer drops — alert on lost_events; scale sampling down before scaling up.
  • TLB shootdown storms — cap MAX_PAGES_PER_SEC; batch by iovec.
  • Tier oversubscription — alert at 85% tier occupancy; demotion must have headroom to work.
  • Kernel regressions — pin your kernel version; tiering behavior changed materially between 6.1 and 6.8.
# Production alerting signals
grep -E 'pgdemote_kswapd|pgpromote_success|numa_pte_updates' /proc/vmstat
bpftool map dump name fault_counts | head

FAQ

Do I need a CXL-capable CPU to use this stack? No. The eBPF observation layer and policy engine work on any NUMA system. CXL memory simply appears as an additional NUMA node (or dax/kmem device) once the kernel exposes it. You can develop and validate the entire pipeline on a two-socket NUMA box using one node as a simulated “slow tier” before adding real CXL hardware.

Which kernel version supports memory tiering and CXL hotplug? Memory tiering (NUMA balancing with demotion, memory_tiering sysfs) matured around Linux 6.1–6.3, and CXL region/decoder support plus dax_kmem hotplug stabilized through 6.5–6.8. Use a 6.6+ LTS kernel for production; verify CONFIG_NUMA, CONFIG_MEMORY_TIERING, CONFIG_CXL_BUS, CONFIG_DEV_DAX_KMEM, and BTF for CO-RE eBPF programs.

Is eBPF fast enough to drive per-page migration decisions? eBPF should not make per-page decisions in the hot path. Use it for sampling and aggregation: kprobes/tracepoints on page faults, NUMA hinting faults, and migration events feed histograms keyed by cgroup and address range. The policy engine consumes these aggregates on a seconds-scale loop and issues migrations via process_madvise or the memory tiering sysfs knobs. This keeps overhead typically under 1–2% CPU.

How do I prevent thrashing between DRAM and CXL tiers? Add hysteresis: require a page or range to exceed an access threshold for multiple consecutive sampling windows before promotion, and use a lower threshold plus a cooldown period for demotion. Cap the migration rate per cgroup (pages/second) and monitor pgdemote_kswapd, pgpromote_success, and numa_pte_updates counters. If promotion and demotion rates converge, widen the thresholds.

Can this stack migrate pages for a running database without downtime? Yes, if you migrate at the process level using process_madvise with MADV_PAGEOUT or tier-aware advice on the target PID, or rely on kernel NUMA balancing for anonymous memory. For file-backed database pages, use fadvise/madvise on mapped ranges. Always test on replicas first; large migrations cause brief TLB shootdowns and can spike p99 latency, so throttle during peak hours.

What metrics should I alert on in production? Track per-tier occupancy, promotion/demotion throughput, migration failure counts, eBPF ring-buffer drops, NUMA hinting fault rates, and workload-level p99 latency and throughput. Alert when a tier exceeds 85% capacity, when demotion outpaces promotion for sustained periods (indicating an undersized fast tier), or when eBPF sampling overhead exceeds your CPU budget.

Sponsored / Ad Space