Mastering eBPF Kernel Socket Filters (4014)
Introduction
eBPF socket filters (introduced in Linux 3.19, significantly hardened in 4.14) allow user‑space programs to attach sandboxed bytecode directly to a socket’s receive path. This enables ultra‑low‑latency packet classification, load‑balancing decisions, and observability without leaving the kernel. In Kubernetes, they power CNI plugins like Cilium and Calico for L7 policy enforcement, service mesh sidecar bypass, and zero‑copy telemetry.
Kernel Socket Filter Architecture
The BPF_PROG_TYPE_SOCKET_FILTER program runs in the context of sk_filter hook. Key data structures:
struct sk_buff– packet metadata accessible viabpf_skb_load_byteshelpers.struct bpf_sock_ops– for TCP‑level decisions (since 4.13).struct bpf_sock_addr– for connect/bind redirection (4.14+).
Verification ensures bounded loops, no unbounded pointer arithmetic, and safe memory access. The JIT compiler (x86_64, arm64, s390x) translates bytecode to native instructions, yielding near‑native throughput.
Integration with Kubernetes CNI
CNI plugins leverage socket filters for pod‑level L7 visibility. The typical flow:
- CNI daemon loads a socket filter program into the kernel via
bpf_prog_load. - During pod sandbox creation, the CNI attaches the program to the pod’s veth endpoint using
setsockopt(SO_ATTACH_BPF). - The filter inspects every inbound/outbound packet, enforcing network policies (e.g., allow only HTTP GET on /healthz).
- Metrics are exported via BPF maps to user‑space collectors (Prometheus, Datadog).
Because the filter runs in the kernel, there is no context switch overhead, making it ideal for high‑throughput microservice meshes.
eBPF/XDP kernel filter evaluates TCP/UDP frames directly on server NIC.
Best Practices & Debugging
- Map sizing: Pre‑allocate per‑CPU hash maps for counters to avoid lock contention.
- Tail calls: Use
bpf_tail_callto chain filters (max 32) for modular policy composition. - Verifier logs: Enable
bpf_log_bufduring development; inspect withbpftool prog show. - Testing: Use
bpf_prog_test_runfor unit tests in CI pipelines. - Upgrades: Leverage
bpf_prog_attachwithBPF_F_REPLACEfor zero‑downtime rollouts.
Conclusion
eBPF socket filters (kernel 4.14+) provide a programmable, safe, and high‑performance datapath primitive that is now foundational for Kubernetes networking. By mastering the verifier constraints, JIT nuances, and CNI integration patterns, platform engineers can build custom observability, security, and traffic‑shaping logic that runs at line rate. The accompanying benchmark chart, code sandbox, cost estimator, CLI builder, and network topology visualizer in this article give you a hands‑on toolkit to prototype and productionize your own socket filter solutions.