ebpfbased distributed tracing Overhead in Linux

The 3 AM Page: When the Ring Buffer Overran

The PagerDuty alert hit at 03:14 UTC. Our edge proxy tier—handling forty thousand TLS 1.3 terminations per second across a fleet of metal nodes running Linux 5.15—suddenly flatlined. Latency at the ninety-ninth percentile spiked from two milliseconds to over four hundred. CPU utilization across all sixty-four hyperthreads locked at one hundred percent, yet user-space application processes showed near-zero CPU consumption. The machine was burning all its cycles inside ring 0.

We did not consult a dashboard to guess the culprit. We already knew. Three days prior, security operations had deployed a new agent utilizing ebpfbased distributed tracing to capture context propagation headers across arbitrary system boundaries. The marketing collateral promised “zero-overhead observability.” The kernel told a different story. The perf ring buffers were dropping hundreds of thousands of events per second, triggering endless atomic fallback paths, locking up memory management structures, and starving the actual networking workload of compute time.

Zero-overhead is a lie. Every BPF program, every kprobe attachment, and every map lookup extracts a toll from the CPU. This post dissects the exact mechanics of that toll, exposing what happens when you instrument a high-throughput Linux kernel without understanding the hardware cost of observability.

The Mechanics of Kernel Intrusion

Every time you attach a bpf program to a tracepoint, kprobe, or trace_point, you are intercepting execution flow. The illusion of safety provided by the verifier hides a brutal physical reality: cache lines thrash, instructions execute outside the hot path, and atomic operations serialize parallel cores.

Kprobes vs. Tracepoints: The Cost of Flexibility

Kprobes modify live kernel text. When you register a kprobe on `sys_enter_clone`, the kernel replaces the first instruction of that function with a breakpoint instruction (`int3` on x86_64). When execution hits that address, a trap occurs, CPU context is saved, the exception handler fires, your BPF callback runs, and the original instruction is single-stepped out-of-line before returning to the kernel.

This trap-and-emulate cycle is extraordinarily expensive. You are invalidating the instruction pipeline and paying the penalty of a full context switch into debugging infrastructure. Static tracepoints, conversely, are compiled directly into the kernel image as conditional nops. When disabled, they cost a single-byte nop instruction. When enabled, the kernel patches the nop into a direct jump to a trampoline.

Even static tracepoints are not free. They serialize memory access and disrupt branch prediction. Consider a basic tracepoint handler written in modern BPF C:

#include <vmlinux.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_trace.h>

struct trace_event_raw_sys_enter {
    __u64 unused;
    long syscall_nr;
    unsigned long args[6];
};

SEC("tracepoint/raw_syscalls/sys_enter")
int handle_sys_enter(struct trace_event_raw_sys_enter *ctx) {
    __u32 pid = bpf_get_current_pid_tgid() >> 32;
    if (pid == 1) return 0; // Skip systemd

    bpf_printk("Syscall: %ld\n", ctx->syscall_nr);
    return 0;
}

char _license[] SEC("license") = "GPL";

That seemingly innocuous `bpf_printk` call writes to a specialized trace pipe. Under high concurrency, serialization on the global tracing ring buffer forces every CPU core to contend for the same memory locks. The resulting stall cycles degrade throughput faster than an unoptimized database query.

Context Switching and Register Saving Penalties

When your BPF program executes, it cannot rely on registers remaining untouched. The kernel trampoline saves caller-saved registers onto the stack. If your ebpfbased distributed tracing agent inspects function arguments deep in the network stack, such as inside `tcp_rcv_established`, the sheer volume of register saves creates memory bandwidth saturation.

Modern CPUs rely heavily on store buffers and out-of-order execution windows. Injecting BPF instructions forces the CPU to commit register states earlier than it would otherwise, stalling execution units. On a system processing millions of packets per second, this micro-architectural friction accumulates into a massive aggregate tax.

Memory Subsystem Attrition and Ring Buffer Contention

Data must move from kernel space to user space. This transit relies on BPF maps—specifically perf buffers or ring buffers. The architectural difference between these two data structures dictates whether your system survives production loads or melts down under traffic spikes.

Perf Buffers vs. BPF Ring Buffers

Legacy profiling systems rely on `BPF_MAP_TYPE_PERF_EVENT_ARRAY`. Every CPU core gets an independent ring buffer. When your BPF program writes an event, it allocates space in that core’s buffer. If the buffer is full, the event is dropped.

The drop mechanism sounds safe, but the allocation path is fraught with danger. The kernel must query atomic pointers to calculate head and tail offsets. Under heavy contention, multiple threads on the same core or migrating tasks hammer those atomic variables, causing cache line bouncing across sockets via the inter-socket interconnect (UPI on Intel, Infinity Fabric on AMD).

The modern `BPF_MAP_TYPE_RINGBUF` introduced in Linux 5.8 improves memory efficiency by sharing a single ring buffer across multiple CPUs with multi-producer, single-consumer lockless mechanics using CAS (Compare-And-Swap) operations. However, lockless does not mean cost-free.

#include <vmlinux.h>
#include <bpf/bpf_helpers.h>

struct event {
    __u32 pid;
    __u64 timestamp;
    char comm[16];
};

struct {
    __uint(type, BPF_MAP_TYPE_RINGBUF);
    __uint(max_entries, 256 * 1024 * 1024); // 256MB allocation
} rb SEC(".maps");

SEC("kprobe/sys_enter_clone")
int trace_clone(struct pt_regs *ctx) {
    struct event *e;
    e = bpf_ringbuf_reserve(&rb, sizeof(*e), 0);
    if (!e) return 0;

    e->pid = bpf_get_current_pid_tgid() >> 32;
    e->timestamp = bpf_ktime_get_ns();
    bpf_get_current_comm(&e->comm, sizeof(e->comm));

    bpf_ringbuf_submit(e, 0);
    return 0;
}

char _license[] SEC("license") = "GPL";

Allocating a 256-megabyte ring buffer across NUMA nodes requires careful memory pinning. If your ebpfbased distributed tracing collector reads from this ring buffer on CPU 0 while events are written from CPU 63, you are forcing continuous cross-node memory synchronization through the memory controller.

NUMA Node Penalties and Memory Allocation Storms

When user-space collectors poll ring buffers using `epoll` or blocking reads, they allocate memory to process incoming trace spans. If the collector runs on NUMA node 1 while the kernel ring buffer resides in memory allocated on NUMA node 0, every data read incurs a remote memory access penalty.

Furthermore, dynamic memory allocation inside user-space tracing daemons interacting with high-frequency BPF outputs leads to heap fragmentation. The kernel must frequently service page faults and direct reclaim cycles if the tracing agent’s memory footprint grows unchecked during traffic surges.

Stack Tracing and Symbolication Overhead

Capturing a trace event is trivial. Figuring out *where* that event originated in terms of human-readable symbols is where systems grind to a halt. Distributed tracing requires end-to-end call stacks to reconstruct execution paths across asynchronous service boundaries.

The True Cost of `bpf_get_stackid`

Walking the kernel stack or user stack via `bpf_get_stackid` or `bpf_get_stack` is a perilous operation. To walk a stack safely, the BPF program must traverse frame pointers or consult DWARF debug information. This requires reading memory from arbitrary addresses, which may be swapped out, paged out, or protected.

When the kernel executes `bpf_get_stack`, it suspends normal scheduling invariants for that inspection window. It locks the task structure or relies on volatile pointer dereferencing with built-in safety checks:

#include <vmlinux.h>
#include <bpf/bpf_helpers.h>

struct {
    __uint(type, BPF_MAP_TYPE_STACK_TRACE);
    __uint(max_entries, 10000);
    __uint(key_size, sizeof(__u32));
    __uint(value_size, 128 * sizeof(__u64)); // 128 stack frames deep
} stack_traces SEC(".maps");

SEC("perf_event")
int sample_cpu(struct bpf_perf_event_data *ctx) {
    __u32 trace_id = bpf_get_stackid(ctx, &stack_traces, BPF_F_USER_STACK);
    if ((int)trace_id < 0) return 0;

    // Process trace_id...
    return 0;
}

char _license[] SEC("license") = "GPL";

The size of the value structure dictates the memory footprint. A stack trace map holding ten thousand entries with 128-frame depths consumes massive amounts of locked kernel memory. Every lookup hashes the stack trace, writing to hash map buckets and creating lock contention on the map’s internal spinlocks.

User-Space Unwinding Nightmares

User-space stack unwinding is notoriously fragile. Frame-pointer-based unwinding (`-fno-omit-frame-pointer`) adds a slight register pressure penalty to application code, but it is fast. Modern languages like Go, Rust, and Java, however, do not always adhere strictly to standard frame pointer conventions across all runtime versions.

When an ebpfbased distributed tracing tool attempts to unwind a Go binary without valid frame pointers, it falls back to DWARF-based unwinding tables. Parsing DWARF bytecode inside the kernel or forcing user-space daemons to resolve address ranges via `/proc/self/maps` introduces massive CPU overhead. The tracing tool ends up consuming more compute resources than the business logic it is meant to observe.

Network Stack Instrumentation Pitfalls

Distributed tracing shines brightest when tracking requests across microservices. In a Linux environment, this involves hooking into the socket layer, parsing TLS records, or intercepting system calls like `sys_enter_sendto` and `sys_exit_recvfrom`.

Socket Buffers and Packet Inspection Costs

Placing a kprobe on `tcp_sendmsg` allows an observability agent to read HTTP headers and extract distributed tracing context propagation tokens (such as W3C Trace Context headers: `traceparent`). However, inspecting socket buffers safely requires copying memory from kernel space to BPF stack space using `bpf_probe_read_kernel`.

#include <vmlinux.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_trace.h>

SEC("kprobe/tcp_sendmsg")
int BPF_KPROBE(trace_tcp_sendmsg, struct sock *sk, struct msghdr *msg, size_t size) {
    // Extract socket family and ports
    __u16 family = BPF_CORE_READ(sk, __sk_common.skc_family);
    if (family != AF_INET) return 0;

    __u16 dport = BPF_CORE_READ(sk, __sk_common.skc_dport);

    // Reading user-space message vectors requires safe copy helpers
    char buffer[64];
    if (msg->msg_iter.iov && size > 0) {
        bpf_probe_read_user(buffer, sizeof(buffer), msg->msg_iter.iov->iov_base);
        // Parse HTTP/gRPC headers here...
    }

    return 0;
}

char _license[] SEC("license") = "GPL";

Every call to `bpf_probe_read_user` checks page table permissions and handles potential page faults gracefully. If an application passes an invalid pointer or triggers a minor page fault inside a kprobe context, the kernel must handle the fault exception path. Doing this for every outgoing HTTP request on a high-throughput API gateway destroys request latency consistency.

UDS vs. TC vs. XDP Overhead Profiles

Where you place your tracing hooks changes the cost equation dramatically. The following diagnostic command reveals the active tracepoints and raw performance counters associated with network-layer tracing overhead on interface `eth0`:

sudo bpftool prog show
sudo perf stat -e cache-misses,instructions,cycles -p $(pgrep -f tracing-agent) -- sleep 5

Placing hooks at the Traffic Control (TC) layer (`clsact`) is cheaper than socket-layer kprobes because you operate directly on `__sk_buff` metadata without wrestling with user-space memory pointers. XDP (eXpress Data Path) is even faster, executing directly in the network driver before socket buffer allocation occurs, but XDP lacks the rich application context required for distributed tracing span correlation.

Engineering Pragmatism: How to Measure and Mitigate

You cannot eliminate observability overhead, but you can bound it. Production environments demand strict operational discipline to prevent monitoring tools from causing the very outages they are deployed to prevent.

Sampling Strategies and Dynamic Rate Limiting

Capturing one hundred percent of traces is an expensive luxury reserved for low-traffic staging environments. In production, you must implement head-based or tail-based sampling directly within the BPF layer or the immediate user-space daemon.

Using BPF map lookups for rate-limiting ensures that high-volume endpoints do not flood the ring buffer. A simple token bucket implemented inside a BPF map drops excess spans before they consume memory bandwidth:

#include <vmlinux.h>
#include <bpf/bpf_helpers.h>

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1024);
    __type(key, __u32);
    __type(value, __u64);
} rate_limit_map SEC(".maps");

SEC("kprobe/sys_enter_execve")
int check_rate_limit(struct pt_regs *ctx) {
    __u32 key = 0;
    __u64 *tokens = bpf_map_lookup_elem(&rate_limit_map, &key);

    __u64 now = bpf_ktime_get_ns();
    if (tokens && *tokens > now) {
        // Rate limit exceeded, drop trace event
        return 0;
    }

    // Refresh tokens (10ms interval)
    __u64 next_allowed = now + 10000000;
    bpf_map_update_elem(&rate_limit_map, &key, &next_allowed, BPF_ANY);

    // Proceed with tracing logic...
    return 0;
}

char _license[] SEC("license") = "GPL";

Continuous Verification with Perf and BPF Tooling

Never deploy an ebpfbased distributed tracing agent without profiling its resource consumption under simulated peak load. Use standard Linux diagnostic primitives to audit your kernel agents continuously:

# Monitor BPF program runtime and execution count
sudo bpftool prog show --json | jq '.[] | {id: .id, name: .name, run_cnt: .run_cnt, run_time_ns: .run_time_ns}'

# Check memory locked by BPF maps
ulimit -l
sudo bpftool map show

If your BPF programs accumulate cumulative execution times exceeding a few milliseconds per second of CPU time, or if your ring buffer drop counters climb steadily, your observability pipeline is actively damaging system stability. Adjust your filters, restrict your tracepoints, and remember: if your monitoring breaks production, no one cares about your distributed trace graph.

Related Articles

Explore more insights and best practices:

Leave a Comment