ByteGuideHub
Observability & Networking • • 10 min read

Self-Hosted eBPF-Based TCP Connection Pool Exhaustion and File Descriptor Leak Detection in Microservices

A practical guide to using eBPF kprobes and tracepoints to trace socket lifecycle, detect file descriptor leaks and TCP connection pool exhaustion in Go/Java microservices without code changes, and build alerting dashboards.

Sponsored / Ad Space

Self-Hosted eBPF-Based TCP Connection Pool Exhaustion and File Descriptor Leak Detection in Microservices

Quick Summary (TL;DR)

  • Problem: Microservices silently leak file descriptors and exhaust TCP connection pools, causing cascading failures that are hard to diagnose with application-level metrics alone.
  • Solution: Use eBPF kprobes and tracepoints to track the full socket lifecycle (socket() → connect() → close()) and FD allocation without touching application code.
  • Stack: BCC/bpftrace for tracing, ebpf_exporter for Prometheus metrics, Grafana for dashboards and alerts.
  • Requirements: Linux kernel 5.2+ (ideally 5.8+), BTF enabled, CAP_BPF/root privileges.
  • Payoff: Sub-second visibility into leaked FDs and saturated pools, correlated with application behavior — all self-hosted, zero instrumentation.

Introduction

Every production microservice eventually hits two silent killers: file descriptor (FD) leaks and TCP connection pool exhaustion. Both start innocuously — a slow FD count creep, a few more TIME_WAIT sockets — and both end the same way: EMFILE: too many open files, connection refused, and a 3 AM page.

Traditional monitoring tells you that something broke, not why. Application-level metrics miss FD leaks entirely, and netstat polling is too coarse to catch transient spikes. eBPF changes the equation: it lets you observe kernel-level socket events with microsecond precision, without modifying a single line of Go or Java code.

This guide walks you through building a self-hosted detection system using eBPF kprobes, tracepoints, and a Prometheus/Grafana pipeline.

Understanding the Problem: Connection Pools and FD Leaks

TCP Connection Pool Exhaustion

Connection pools (in Go’s database/sql, Java’s HikariCP, or HTTP client pools) maintain a fixed set of reusable sockets. When requests outpace pool capacity — or when connections aren’t returned due to slow queries, deadlocks, or missing defer close() — the pool saturates. Symptoms include:

  • Requests queuing for a connection with growing latency
  • pool timeout errors under load
  • A spike in ESTABLISHED sockets on the client side
  • Cascading failures across downstream services

File Descriptor Leaks

Every socket, file, and pipe consumes an FD. Linux defaults to ulimit -n 1024 per process. A leak — say, a net.Conn that’s never closed on an error path — slowly consumes FDs until accept() fails with EMFILE. By then the service is already degraded.

The critical insight: FD leaks and pool exhaustion look similar from the app but diverge at the kernel. eBPF lets you see both.

Why eBPF? Advantages Over Traditional Monitoring

ApproachOverheadCode ChangesGranularityFD Visibility
netstat/ss pollingLowNone1–5s snapshotsAggregate only
Application metricsLowYes (instrument)Per-requestNone
lsof samplingHighNoneSecondsPer-process
eBPF kprobesVery lowNonePer-eventPer-FD
eBPF + BTF/CO-REVery lowNonePer-eventPer-FD, portable

eBPF programs run in a sandboxed VM inside the kernel, verified for safety. Overhead is typically <1% CPU when properly filtered.

Prerequisites and Environment Setup

System Requirements

  • Kernel: 5.2+ for BTF/CO-RE; 5.8+ recommended for BPF_MAP_TYPE_RINGBUF
  • BTF: /sys/kernel/btf/vmlinux must exist (check with ls)
  • Privileges: CAP_BPF + CAP_PERFMON (kernel 5.8+) or root
  • Distro: Ubuntu 20.04+, RHEL 8+, Debian 11+ (or any modern kernel)

Verify BTF support:

ls /sys/kernel/btf/vmlinux && echo "BTF available"
uname -r  # expect 5.2+

Installing Required Tools

# Ubuntu/Debian
sudo apt install -y bpfcc-tools bpftrace linux-headers-$(uname -r) \
    prometheus grafana

# For compiling custom eBPF programs
sudo apt install -y clang llvm libbpf-dev libbpfcc-dev

# Verify
sudo bpftrace -e 'tracepoint:sock:inet_sock_set_state { printf("ok\n"); exit(); }'

If that last command prints ok, your environment is ready.

Tracing Socket Lifecycle with eBPF

Key Kernel Events to Monitor

The socket lifecycle maps to a small set of kernel events:

flowchart LR
    A[socket syscall] -->|kprobe __sys_socket| B[FD allocated]
    B -->|kprobe tcp_connect| C[connect]
    C -->|tracepoint sock:inet_sock_set_state| D[ESTABLISHED]
    D -->|tracepoint inet_sock_set_state| E[TIME_WAIT / CLOSE]
    E -->|kprobe __close_fd| F[FD released]
    B -.->|no close event| G[FD LEAK]
    C -.->|pool saturated| H[POOL EXHAUSTION]
EventTypePurpose
__sys_socket / sock_allockprobeDetect FD allocation
tcp_connectkprobeTrack outbound attempts
sock:inet_sock_set_statetracepointState transitions
__close_fd / sock_releasekprobeDetect FD release
accept4kprobeInbound connection tracking

Writing the eBPF Program

Here’s a bpftrace one-liner to track socket allocations and releases per process:

sudo bpftrace -e '
tracepoint:sock:inet_sock_set_state
/args->newstate == 1/  // TCP_ESTABLISHED
{
    @sockets[pid, comm] = count();
}

kprobe:__close_fd
{
    @closes[pid, comm] = count();
}

interval:s:10
{
    print(@sockets);
    print(@closes);
    clear(@sockets);
    clear(@closes);
}'

For production, move to a compiled BPF program with libbpf for lower overhead. A minimal C skeleton for tracking FD allocation:

SEC("kprobe/sock_alloc")
int BPF_KPROBE(track_socket, struct socket *sock) {
    u32 pid = bpf_get_current_pid_tgid() >> 32;
    u64 ts = bpf_ktime_get_ns();
    bpf_map_update_elem(&alloc_map, &pid, &ts, BPF_ANY);
    return 0;
}

SEC("kprobe/sock_release")
int BPF_KPROBE(track_release, struct socket *sock) {
    u32 pid = bpf_get_current_pid_tgid() >> 32;
    bpf_map_delete_elem(&alloc_map, &pid);
    return 0;
}

Compiling and Loading the Program

clang -O2 -g -target bpf -c socket_trace.bpf.c -o socket_trace.bpf.o
sudo bpftool prog load socket_trace.bpf.o /sys/fs/bpf/socket_trace
sudo bpftool prog show pinned /sys/fs/bpf/socket_trace

Detecting File Descriptor Leaks

Tracking FD Allocation and Release

The core idea: maintain a per-process counter of alloc - release. If it grows monotonically without bound, you have a leak.

sequenceDiagram
    participant App
    participant Kernel
    participant eBPF
    participant Prometheus
    App->>Kernel: socket()
    Kernel->>eBPF: kprobe sock_alloc
    eBPF->>eBPF: fd_count[pid]++
    App->>Kernel: close(fd)
    Kernel->>eBPF: kprobe __close_fd
    eBPF->>eBPF: fd_count[pid]--
    eBPF->>Prometheus: expose fd_count
    Note over eBPF,Prometheus: Leak = monotonic increase

Identifying Leaks

A practical heuristic: if fd_count[pid] grows by more than 10% over a 5-minute window and never recovers, flag it. Combine with the /proc/<pid>/fd count for validation:

# Cross-check with procfs
ls /proc/<pid>/fd | wc -l

If the eBPF count and procfs count diverge, you have a missed kprobe — usually a non-socket FD (files, eventfd, epoll).

Detecting Connection Pool Exhaustion

Monitoring Pool Metrics

Pool exhaustion manifests as many ESTABLISHED sockets in TIME_WAIT or SYN_SENT on the client side, with a flat rate of close() calls. Track:

  • in_flight_connects — connect() calls without matching ESTABLISHED
  • time_wait_count — sockets stuck in TCP_TIME_WAIT (state 6)
  • pool_high_water — peak concurrent ESTABLISHED per process
sudo bpftrace -e '
tracepoint:sock:inet_sock_set_state
/args->newstate == 6/  // TCP_TIME_WAIT
{
    @time_wait[comm] = count();
}
interval:s:5 { print(@time_wait); clear(@time_wait); }'

Correlating with Application Behavior

Use bpf_get_current_comm() to attribute sockets to specific services, then join with HTTP/gRPC span data. A service showing rising TIME_WAIT while its request rate is flat is almost certainly pooling incorrectly — often missing keep-alive or a misconfigured MaxIdleConns.

Building Alerting and Dashboards

Exporting Metrics to Prometheus

The cleanest self-hosted path is ebpf_exporter. Define a config:

programs:
  - name: fd_leak
    metrics:
      counters:
        - name: process_fd_count
          help: "Open FDs per process"
          key: pid
          labels: [comm]
    kprobes:
      sock_alloc: {kprobe: sock_alloc}
      sock_release: {kprobe: sock_release}

Run it as a systemd service, then scrape :9435/metrics from Prometheus.

Creating Grafana Dashboards

Key panels to build:

  1. FD count per service — line chart, alert on slope > 0 for 10 min
  2. Socket state distribution — stacked bar (ESTABLISHED, TIME_WAIT, SYN_SENT)
  3. Pool saturation gauge — in_flight_connects / max_pool_size
  4. FD allocation rate — rate(process_fd_count[1m])

Setting Up Alerts

groups:
  - name: ebpf-socket-alerts
    rules:
      - alert: FdLeakSuspected
        expr: increase(process_fd_count[10m]) > 200
        for: 10m
        labels: {severity: warning}
        annotations:
          summary: "FD leak suspected in {{ $labels.comm }}"

      - alert: ConnectionPoolExhausted
        expr: sum by (comm) (process_socket_state{state="TIME_WAIT"}) > 500
        for: 5m
        labels: {severity: critical}

Comparison of eBPF Tools for Socket Tracing

ToolBest ForLanguageOverheadSelf-Hosted
bpftraceAd-hoc debugging, quick scriptsDSLLow✅
BCCProduction Python toolingPython + CLow✅
libbpf + CO-REPortable production agentsCVery low✅
PixieFull observability platformGoMedium✅
Cilium/HubbleK8s network observabilityGoLow–Medium✅
ebpf_exporterPrometheus metricsGoVery low✅

For a minimal footprint, combine libbpf (program) + ebpf_exporter (metrics) + Grafana (visuals).

Best Practices and Pitfalls

  • Filter aggressively. Attach to specific PIDs/namespaces to avoid tracing the whole host.
  • Use ringbuf, not perfbuf. BPF_MAP_TYPE_RINGBUF (kernel 5.8+) is faster and simpler.
  • Watch for missed kprobes. Attach to both sock_alloc and __sys_socket — some paths skip one.
  • Don’t alert on raw counts. Alert on rates and slopes; absolute FD counts vary wildly with workload.
  • Validate against procfs. Periodically reconcile eBPF counts with /proc/<pid>/fd to catch drift.
  • Test kernel compatibility. CO-RE handles most differences, but tracepoints like inet_sock_set_state vary across 4.x/5.x kernels.
  • Never run without limits. Set ulimit -n appropriately and monitor it — eBPF tells you why, not just when.

Conclusion

eBPF gives you X-ray vision into the socket layer without touching application code. By tracing socket() → connect() → close() and correlating FD counts with connection state transitions, you can catch leaks and pool exhaustion before they cascade. The self-hosted stack — bpftrace for exploration, libbpf + ebpf_exporter for production, Prometheus + Grafana for alerting — is mature, low-overhead, and entirely under your control.

Start with a bpftrace one-liner in staging. Graduate to a compiled agent once you trust the signal. Your 3 AM self will thank you.


FAQ

What are the kernel version requirements for eBPF socket tracing? You need Linux kernel 4.14 or later for basic eBPF kprobes and tracepoints. For advanced features like BTF and CO-RE, kernel 5.2+ is recommended. For full socket lifecycle tracing including the sock:inet_sock_set_state tracepoint, kernel 4.16+ is required.

Can I use this approach with containerized microservices? Yes, eBPF programs can trace sockets inside containers. You need to run the eBPF tool with sufficient privileges (CAP_BPF or root) and ensure the container runtime allows access to kernel tracepoints. Tools like BCC and bpftrace support container-aware tracing via PID namespace filtering.

How do I differentiate between connection pool exhaustion and a file descriptor leak? Connection pool exhaustion typically shows a high number of connections in TIME_WAIT or ESTABLISHED state without corresponding closes, while FD leaks show a steady increase in open file descriptors without matching closes. By tracking both socket states and FD counts, you can correlate and distinguish them.

Is it safe to run eBPF programs in production? Yes, eBPF programs are verified by the kernel for safety and have minimal overhead. However, you should test them in a staging environment first and monitor their impact. Use sampling or filtering to reduce overhead on high-traffic systems.

What are the alternatives to eBPF for socket monitoring? Traditional methods include netstat, ss, lsof, and application-level instrumentation. eBPF offers lower overhead, no code changes, and deeper kernel-level visibility. For some use cases, eBPF can replace or complement these tools.

How can I export eBPF metrics to Prometheus? You can use tools like ebpf_exporter or write a custom exporter that reads eBPF maps and exposes metrics via HTTP. Alternatively, use bpftrace to output metrics in a format that Prometheus can scrape via a textfile collector.

Sponsored / Ad Space