ByteGuideHub
Observability & Networking • • 10 min read

Self-Hosted eBPF TCP Tracing: Zero-Instrumentation Latency Attribution with CO-RE and BTF

Build a kernel-agnostic eBPF tracer using CO-RE and BTF to trace TCP connection lifecycle (connect, close, retransmit) and attribute latency without application instrumentation. Step-by-step guide with ring buffer design, correlation IDs, and Grafana dashboards.

Sponsored / Ad Space

Self-Hosted eBPF TCP Tracing: Zero-Instrumentation Latency Attribution with CO-RE and BTF

Quick Summary (TL;DR)

  • What: A production-ready eBPF tracer that captures TCP connection lifecycle events (connect, close, retransmit) directly from the kernel using tracepoints.
  • Why: Attribute latency to network behavior without touching application code, redeploying services, or installing language-specific agents.
  • How: Use CO-RE (Compile Once – Run Everywhere) + BTF (BPF Type Format) so a single compiled binary runs on any modern kernel. Stream events through a ring buffer to a userspace collector, correlate by a stable connection ID, and export Prometheus metrics for Grafana.
  • Time to value: ~30 minutes if your kernel is 5.8+ with BTF enabled.

Modern distributed systems fail in ways that application-level tracing chronically misses: silent retransmits, slow handshakes, half-open connections, and kernel-side backpressure. This guide shows you how to build a self-hosted eBPF tracer that sees all of it — without a single line of instrumentation in your services.

Why eBPF for TCP Lifecycle Tracing?

Traditional APM tools instrument the application runtime (JVM agents, OpenTelemetry SDKs, sidecars). They see what your code thinks happened — not what the kernel actually did. A 200ms write() to a socket may have taken 180ms inside the network stack due to congestion control, retransmits, or receive-window stalls.

eBPF flips this: it observes the kernel’s own TCP state machine. You get ground-truth latency attribution, per-connection retransmit counts, and handshake timings — for every process on the host, including ones you can’t rebuild.

CapabilityApplication InstrumentationeBPF TCP Tracing
Code changes requiredYes (SDK, agent)None
Language coveragePer-runtimeAll processes
Sees kernel retransmitsNoYes
Sees handshake latencyApproximateExact
Overhead2–5% typical<1% typical
Works on legacy binariesNoYes

Prerequisites and Environment Setup

Kernel and BTF Requirements

You need Linux 5.8+ for full CO-RE and stable ring buffer support. Verify BTF is exposed:

ls -l /sys/kernel/btf/vmlinux
# -r--r--r-- 1 root root 6.1M ... /sys/kernel/btf/vmlinux
uname -r

If the file is missing, install the BTF package for your distro (linux-image-*-dbg on Debian/Ubuntu, kernel-debug on RHEL).

Toolchain Installation

# clang/llvm for BPF target, libbpf, bpftool, headers
sudo apt install -y clang llvm libbpf-dev libelf-dev bpftool \
    linux-tools-common linux-tools-$(uname -r) pkg-config

# Generate vmlinux.h from the running kernel's BTF
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h

Understanding CO-RE and BTF for Kernel Portability

How CO-RE Works

CO-RE solves the “recompile for every kernel” problem. Instead of hardcoding struct offsets, you write field accesses like sk->__sk_common.skc_dport. The compiler emits relocations (not offsets), and libbpf patches them at load time using the target kernel’s BTF — so the same .o file runs on 5.10, 6.1, and 6.6 without modification.

BTF and vmlinux.h

BTF is a compact, machine-readable description of every kernel type. vmlinux.h is that description rendered as C — include it instead of <linux/tcp.h>, and you get portable struct definitions with zero libc dependency.

flowchart LR
    A[eBPF C source] -->|clang -target bpf| B[.o with CO-RE relocs]
    B -->|libbpf at load time| C{Read BTF from<br/>/sys/kernel/btf/vmlinux}
    C -->|patch offsets| D[Kernel-adapted program]
    D --> E[Verifier]
    E --> F[Attached tracepoints]

Designing the eBPF Tracer

Hooking TCP Events

We use tracepoints (stable ABI) rather than kprobes where possible:

  • tcp:tcp_connect — SYN sent
  • sock:inet_sock_set_state — state transitions (SYN_SENT→ESTABLISHED, →CLOSE)
  • tcp:tcp_retransmit_skb — retransmission
  • tcp:tcp_receive_reset — RST received

Connection Correlation IDs

A stable key is (saddr, daddr, sport, dport). Pack it into a struct conn_key and use a BPF_MAP_TYPE_LRU_HASH to track per-connection state (start timestamp, retransmit count). LRU eviction prevents unbounded memory growth under load.

Ring Buffer Design for Event Delivery

BPF_MAP_TYPE_RINGBUF is preferred over perf buffers: single shared buffer, no per-CPU duplication, and bpf_ringbuf_reserve/submit gives you zero-copy variable-length records.

sequenceDiagram
    participant K as Kernel (eBPF)
    participant RB as Ring Buffer
    participant U as Userspace Collector
    participant P as Prometheus
    K->>RB: reserve + fill event
    K->>RB: submit
    RB-->>U: poll() wakes
    U->>U: correlate by conn_key
    U->>P: update histograms/counters

Implementing the eBPF Program

Step 1: Define Data Structures

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

struct conn_key {
    __u32 saddr, daddr;
    __u16 sport, dport;
};

struct conn_state {
    __u64 start_ns;
    __u32 retransmits;
};

struct event {
    struct conn_key key;
    __u64 ts_ns;
    __u32 pid;
    __u8  kind;      // 1=connect 2=established 3=close 4=retransmit
    __u32 retrans;   // cumulative retransmits at event time
};

struct {
    __uint(type, BPF_MAP_TYPE_LRU_HASH);
    __type(key, struct conn_key);
    __type(value, struct conn_state);
    __uint(max_entries, 65536);
} conns SEC(".maps");

struct {
    __uint(type, BPF_MAP_TYPE_RINGBUF);
    __uint(max_entries, 1 << 20);
} events SEC(".maps");

Step 2: Attach to Tracepoints

SEC("tracepoint/tcp/tcp_connect")
int trace_connect(struct trace_event_raw_tcp_event_sk *ctx)
{
    struct sock *sk = ctx->sk;
    struct conn_key k = {};
    k.saddr = BPF_CORE_READ(sk, __sk_common.skc_rcv_saddr);
    k.daddr = BPF_CORE_READ(sk, __sk_common.skc_daddr);
    k.sport = BPF_CORE_READ(sk, __sk_common.skc_num);
    k.dport = bpf_ntohs(BPF_CORE_READ(sk, __sk_common.skc_dport));

    struct conn_state s = { .start_ns = bpf_ktime_get_ns(), .retransmits = 0 };
    bpf_map_update_elem(&conns, &k, &s, BPF_ANY);
    emit(ctx, &k, 1, 0);
    return 0;
}

Step 3: Handle Connection Lifecycle

Use sock:inet_sock_set_state to catch the ESTABLISHED and CLOSE transitions. Check newstate and emit an event with elapsed time computed from the stored start_ns:

SEC("tracepoint/sock/inet_sock_set_state")
int trace_state(struct trace_event_raw_inet_sock_set_state *ctx)
{
    if (ctx->protocol != IPPROTO_TCP) return 0;
    struct conn_key k = {
        .saddr = ctx->saddr, .daddr = ctx->daddr,
        .sport = ctx->sport, .dport = ctx->dport,
    };
    if (ctx->newstate == TCP_ESTABLISHED) emit(ctx, &k, 2, 0);
    if (ctx->newstate == TCP_CLOSE)       emit(ctx, &k, 3, 0);
    return 0;
}

Step 4: Capture Retransmits

SEC("tracepoint/tcp/tcp_retransmit_skb")
int trace_retrans(struct trace_event_raw_tcp_event_sk_skb *ctx)
{
    struct sock *sk = ctx->sk;
    struct conn_key k = {};
    k.saddr = BPF_CORE_READ(sk, __sk_common.skc_rcv_saddr);
    k.daddr = BPF_CORE_READ(sk, __sk_common.skc_daddr);
    k.sport = BPF_CORE_READ(sk, __sk_common.skc_num);
    k.dport = bpf_ntohs(BPF_CORE_READ(sk, __sk_common.skc_dport));

    struct conn_state *s = bpf_map_lookup_elem(&conns, &k);
    __u32 rc = s ? ++s->retransmits : 1;
    emit(ctx, &k, 4, rc);
    return 0;
}

Step 5: Submit Events to Ring Buffer

static __always_inline void emit(void *ctx, struct conn_key *k, __u8 kind, __u32 rc)
{
    struct event *e = bpf_ringbuf_reserve(&events, sizeof(*e), 0);
    if (!e) return;
    e->key = *k;
    e->ts_ns = bpf_ktime_get_ns();
    e->pid = bpf_get_current_pid_tgid() >> 32;
    e->kind = kind;
    e->retrans = rc;
    bpf_ringbuf_submit(e, 0);
}

Building the Userspace Collector

Reading from the Ring Buffer

Using libbpf’s ring_buffer__new, the collector polls events with a callback. Keep the callback lean — copy the event and push it onto a lock-free queue for a worker goroutine/thread to process.

static int on_event(void *ctx, void *data, size_t len)
{
    struct event *e = data;
    collector_enqueue(e);   // non-blocking
    return 0;
}

rb = ring_buffer__new(bpf_map__fd(skel->maps.events), on_event, NULL, NULL);
while (!stop) ring_buffer__poll(rb, 100 /* ms */);

Correlating Events and Computing Latency

Maintain a userspace map[conn_key]connState (with TTL eviction) that mirrors the kernel map. On kind==2 (ESTABLISHED), compute handshake_ms = (ts - start_ns)/1e6. On kind==3 (CLOSE), compute lifetime_ms. On kind==4, increment a retransmit counter for the key.

Exporting Metrics to Prometheus

Aggregate before exporting — never expose raw connection IDs (cardinality bomb).

var (
  handshakeHist = prometheus.NewHistogramVec(prometheus.HistogramOpts{
    Name: "tcp_handshake_duration_seconds",
    Buckets: []float64{.001,.005,.01,.025,.05,.1,.25,.5,1,2.5},
  }, []string{"dport"})
  retransTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
    Name: "tcp_retransmits_total",
  }, []string{"dport"})
)

Visualizing with Grafana Dashboards

Key Metrics and Panels

PanelMetricType
Handshake p50/p95/p99tcp_handshake_duration_secondsHistogram heatmap
Retransmit raterate(tcp_retransmits_total[5m])Time series
Active connectionssum(tcp_conn_active)Stat
Connections by remote porttopk(10, sum by (dport)(...))Bar gauge
Close reason breakdowntcp_close_total{reason}Pie

Example PromQL Queries

# p95 handshake latency by remote port
histogram_quantile(0.95,
  sum by (le, dport) (rate(tcp_handshake_duration_seconds_bucket[5m])))

# retransmit percentage of total connections
100 * rate(tcp_retransmits_total[5m]) / rate(tcp_conn_total[5m])

# connections stuck in SYN_SENT > 5s (alert)
sum(tcp_syn_sent_age_seconds > 5)

Comparison: eBPF Tracing vs. Traditional Instrumentation

DimensioneBPF CO-RE TracerJaeger/Zipkin SDKService Mesh Sidecar
App code changesNoneRequiredNone (but sidecar)
Kernel-level visibilityFullNonePartial
Kernel portabilitySingle binary (5.8+)N/AN/A
Overhead<1%2–5%5–15%
Retransmit attributionNativeNoNo
Setup complexityMediumLowHigh
Works on 3rd-party binariesYesNoYes

Best Practices and Pitfalls

  • Filter early in-kernel. Drop events for loopback or irrelevant ports inside the BPF program — every byte through the ring buffer costs CPU.
  • Cap map sizes. Always use LRU_HASH for connection state; a plain hash map will exhaust memory during a SYN flood.
  • Beware of bpf_probe_read on user pointers. Prefer BPF_CORE_READ for kernel structs; it emits CO-RE relocations automatically.
  • Pin your vmlinux.h. Regenerate it only when you deliberately upgrade your target kernel baseline; commit it to your repo.
  • Test with bpftool prog tracelog before attaching to production. Verify the verifier accepts the program on your oldest supported kernel.
  • Watch ring buffer drops. Expose bpf_ringbuf_discard/drop counters as a Prometheus metric — silent drops are the #1 debugging trap.
  • Don’t export raw conn_key. Cardinality will destroy Prometheus. Aggregate at the collector.

Conclusion

Self-hosted eBPF tracing with CO-RE and BTF gives you kernel-truth latency attribution that no application SDK can match — with a single portable binary and no code changes. Start with the four tracepoints above, ship the ring buffer + Prometheus pipeline, and iterate from there. The result is a tracer that keeps working across kernel upgrades and legacy workloads, which is exactly what production observability demands.

FAQ

What kernel version do I need for CO-RE and BTF? You need Linux kernel 5.2 or later for BTF support, and 5.8+ for full CO-RE capabilities (including the ring buffer). Most modern distributions (Ubuntu 20.04+, RHEL 8+, Debian 11+) ship BTF. Verify with ls /sys/kernel/btf/vmlinux.

Can I use this tracer in production without performance impact? Yes. eBPF programs are highly efficient — overhead is typically <1% CPU when tracing TCP events. Use a ring buffer with an appropriate size, filter in-kernel, and always test in staging first. Monitor ring buffer drop counters.

How do I handle high-cardinality connection IDs? Use an LRU_HASH map with bounded max_entries for connection tracking, and aggregate in userspace. Never export raw connection IDs to Prometheus; export latency histograms and counters keyed only by low-cardinality labels like dport.

What if my kernel doesn’t have BTF? You can generate BTF manually with pahole from kernel debug symbols (pahole --btf_encode_detached), or fall back to non-CO-RE eBPF with hardcoded offsets — though this sacrifices portability and is not recommended.

How do I trace retransmits accurately? Hook the tcp:tcp_retransmit_skb tracepoint, increment a per-connection counter in the conns map, and include the cumulative count in every emitted event. Correlate with the same conn_key used for connect/close events so retransmits attribute to the right connection.

Can I extend this to UDP or other protocols? Yes — the architecture is identical. Hook udp_sendmsg/udp_recvmsg (or the udp:* tracepoints) and adapt the correlation key; UDP has no handshake, so you’ll track datagram rates and drop counts instead of lifecycle latency.

Sponsored / Ad Space