Blue, yellow, and red Ethernet cables plugged into a server rack network switch
eBPF Use Cases
William  

How eBPF Steers Traffic Without Proxy Hops

An eBPF load balancer is worth running when you need fast packet or connection steering inside the kernel. It is a steering layer, not a proxy. I put XDP (eXpress Data Path) on the hot ingress path for L4 forwarding and use socket-level redirection for local service traffic. Before blaming throughput or latency, I check what the kernel actually did, using bpftool, the verifier log and the trace pipe.

Last updated: 2026-11-11

What does an eBPF load balancer actually do?

It picks a backend for each packet or connection from inside the kernel, then rewrites the traffic and sends it on. With eBPF, you write the packet forwarding logic that runs in the kernel. Some high-performance routers, firewalls and load balancers already work this way.

The scope is narrow on purpose. The program reads headers, hashes a flow, looks up a backend in a map and returns an action. It doesn't terminate TLS, read HTTP paths or retry a failed request. That work happens in userspace.

Run this first, before writing any code:

sudo bpftool feature probe kernel | grep -iE 'xdp|sched_cls|sk_msg|cgroup_sock_addr'
sudo bpftool feature probe dev eth0 | grep -i xdp

The first command tells you which program types your kernel can load. The second tells you what your NIC driver supports. If native XDP isn't there, your benchmark plans just changed.

Pick the hook by where the traffic flows

The attachment point decides what your balancer can see and what each packet costs. I choose it by asking where the traffic comes in and where it has to go.

HookWhere it runsWhat it seesGood load-balancing job
XDPNIC driver, before an sk_buff existsRaw frame, ingress onlyL4 forwarding, DDoS shedding, edge balancing
tc (clsact)In the stack, after the sk_buffIngress and egress, richer metadataEgress rewrite, UDP forwarding, return-path fixes
cgroup socket hooksAt connect() and sendmsg()The socket address before any packet existsService-IP to backend translation for local clients
sockmap / sk_msgBetween local socketsSocket dataSplicing local sockets together without a loopback trip

Most real deployments split the work. XDP takes the ingress flood, tc covers egress, and socket hooks cover pod-to-service traffic on the same host. Cram everything into one hook and you'll fight the verifier over something another hook would have done in a few lines.

The tc layer is also useful for UDP. udplb is a UDP load balancer and packet forwarder built with eBPF/BCC in the traffic control layer. Packets that match a destination address and port go to a different host, and the kernel does no further processing on them.

XDP load balancing handles the earliest decision

Network server in a rack with blue and green Ethernet cables transmitting glowing data streams

XDP runs at the NIC driver level, before the kernel network stack. Your program sees the frame while it's still a page in the receive ring, so dropping or bouncing it costs almost nothing. That's why Cilium uses XDP for packet filtering and load balancing.

An XDP load balancer relies on its forwarding return codes. XDP_TX sends the packet, modified or not, back out the interface it arrived on. XDP_REDIRECT sends it to a different network interface. These are the standard XDP tools for packet forwarding and load balancing.

Check which attach mode you actually got:

ip -d link show dev eth0 | grep -o 'xdp[a-z]*'
sudo bpftool net show dev eth0

xdpdrv means native mode, which is what you want. xdpgeneric means the kernel fell back to running your program later in the stack, and most of the speed is gone. If you're curious about pushing the program onto the card itself, I covered what XDP offload actually runs on the NIC.

The limits are real. XDP has no egress hook, it can't easily handle fragmented packets, and every header read needs a bounds check against data_end. For a full working setup, see my walkthrough of the Katran XDP load balancer.

Packet forwarding in eBPF needs explicit state and a return path

The kernel won't fill in anything you skipped. After your program returns XDP_TX, the kernel doesn't route the packet, doesn't run netfilter and doesn't fix your checksums. Here is what happens to a forwarded packet:

  1. Parse Ethernet, IP and TCP or UDP, checking every read against data_end.
  2. Hash the flow and look up the backend in a map.
  3. Rewrite the destination MAC, and the destination IP if you're doing NAT.
  4. Update the IP checksum and the L4 checksum incrementally.
  5. Return XDP_TX or XDP_REDIRECT.

Step 3 is where most broken balancers fail. You need the next-hop MAC, so either your userspace agent writes it into a map or the program calls bpf_fib_lookup() to ask the kernel's routing table. A hardcoded MAC works in the lab and breaks the first time a router's ARP entry changes.

Then think about the return path. With destination NAT, the backend replies from its own address, and the client rejects those replies unless something reverses the rewrite. You can do that reverse NAT on the balancer, which forces symmetric routing. The other option is direct server return with IP-in-IP encapsulation, where backends reply straight to the client. I prefer encapsulation at any real scale, because the balancer then only carries the inbound half of the traffic.

Socket-level steering trims proxy hops

Traffic that starts on the same host often needs no packet rewriting at all. A cgroup connect4 program runs when an application calls connect() to a service IP. It swaps in a real backend address before any packet exists, so there's no per-packet NAT and no conntrack entry to translate.

Sockmap goes a step further. When two local sockets talk to each other, a sk_msg program can redirect data from one socket straight to the other and skip the loopback trip through TCP. A sidecar proxy on the same host is the obvious target, because it removes a hop that sits on every request.

The catch is that socket hooks only see local sockets. Traffic from another machine never calls connect() on this host, so anything coming in from outside still needs XDP or tc. An application in a different network namespace can also miss a hook attached to the wrong cgroup. I check attachments with:

sudo bpftool cgroup tree

If your program isn't listed under the cgroup your workload actually runs in, it isn't steering anything.

Connection state in maps is a correctness problem first

Use consistent hashing backed by a connection-tracking map. Plain hash % backend_count remaps almost every flow when one backend leaves. Live TCP connections then land on servers that have never seen them, and those servers reset them.

The layout that holds up uses two maps. The backend map holds the current set. The flow map, keyed on each flow's addresses, ports and protocol, pins an established flow to the backend it already chose. Packets in the middle of a flow check the flow map first and only hash on a miss.

Then come the failure modes nobody puts in the README:

  • Map full. An LRU hash map quietly evicts old flows under pressure. If the flow map is too small, long-lived connections lose their pin and get rehashed.
  • No expiry. A plain hash map never forgets anything. Without LRU or a userspace sweeper, it fills with dead flows and then refuses new ones.
  • Per-CPU confusion. BPF_MAP_TYPE_PERCPU_HASH avoids lock contention, but a flow whose packets land on different CPUs sees different state. Keep flow pinning in a shared map and use per-CPU maps for counters.
  • Racy updates. Swapping the backend set entry by entry exposes half-written state. Build the new table, then flip one pointer with a map-in-map.

Size the maps for peak connection count plus headroom. When they run out, the symptom looks like random network flakiness, and you'll spend hours on the wrong layer.

Where does a Layer-7 proxy still win?

It wins wherever the decision needs the request itself. Path-based routing, header matching, retries with backoff, circuit breaking, mTLS identity and per-request metrics all require parsing the application protocol. The kernel can't do that cheaply or safely.

Service discovery is the other half. Something has to watch the orchestrator, notice backends coming and going, and rewrite the maps. In an eBPF design that's a userspace agent, and its update delay is your failover time. A proxy does the same job but ties it to the request path.

My call for microservices: use eBPF steering for L4 service translation and anything that's pure forwarding. Keep a proxy for the services that need L7 policy, ideally one per node instead of one per pod. If all you need is round-robin across healthy pods, a sidecar on every pod is a cost you don't have to pay.

Measure overhead on your real path

Headline benchmarks measure someone else's workload. One research system, XLB, reports up to 1.5x higher throughput and 60% lower end-to-end latency than Istio and Cilium with over 50 microservice instances. That's a useful sign that sidecar hops cost something. Still, I treat it as a reason to run my own test, and I don't treat it as a forecast.

A controlled comparison changes one thing at a time:

  1. Use your real packet sizes and request mix. Tiny packets and a single flow flatter everything.
  2. Record p50, p99 and p99.9 latency. Averages hide the tail your users complain about.
  3. Measure CPU per request on both the balancer and the backends.
  4. Run long enough for the flow maps to fill and age out.
sudo perf stat -e cycles,instructions,cache-misses -a -- sleep 30
sudo bpftool prog show --json | jq '.[] | {name, run_cnt, run_time_ns}'

Turn on per-program stats first with sysctl -w kernel.bpf_stats_enabled=1. Then run_time_ns / run_cnt gives nanoseconds per run, which tells you whether your program or the rest of the path is the bottleneck. For a lab, a veth pair split across two network namespaces gives you a direct Layer 2 link on one box. It's cheap and reproducible, though veth numbers won't match a physical NIC.

Debug from kernel evidence

Read the verifier log before you search for anything. The verifier checks for out-of-bounds memory accesses that could corrupt data or open a security hole. When it rejects a program, it names the exact instruction and the register state. Most rejections come from an unchecked read past data_end.

When the loader hides the log, strace shows what the bpf() syscall actually returned:

sudo strace -f -e trace=bpf ./lb-loader 2>&1 | grep -E 'BPF_PROG_LOAD|= -1'

An EACCES there means the verifier refused the program. EPERM usually means missing capabilities or a locked-memory limit.

If the program loads but packets vanish, trace the branches. bpf_trace_printk() writes to /sys/kernel/debug/tracing/trace_pipe, so put a print at the map lookup and before each return:

sudo cat /sys/kernel/debug/tracing/trace_pipe
sudo bpftrace -e 'tracepoint:xdp:xdp_exception { @[args->act] = count(); }'

The second command counts XDP_ABORTED events, which are drops your own code caused. Also check dmesg for driver complaints after attaching. One veth trap catches everybody once: redirecting into a veth often needs an XDP program on the peer, even one that only returns XDP_PASS, or the frames go nowhere.

Service chains and scaling can eat the speedup

Your balancer rarely runs alone. One host might carry an XDP firewall, a tc policy program, conntrack-based NAT and a socket hook from another tool. Each is fast on its own, but together they can add back the overhead you were trying to remove.

Ordering matters too. XDP programs can be managed with a dispatcher such as libxdp, and without one, two tools can quietly replace each other's program. Check bpftool net show after every deploy. Anything that pushes packets back through netfilter conntrack also brings back the per-packet cost XDP was meant to skip.

So when is it not worth it? If your traffic fits comfortably in IPVS or a single proxy, eBPF adds a verifier, a map lifecycle and a userspace agent you now have to maintain. I use it at the edge under heavy packet rates, for DDoS-facing ingress like the setup in XDP SYN flood protection, and for clusters where sidecar hops show up in the p99. Anywhere else, the complexity costs more than it saves.

FAQ

Can I run an XDP load balancer on a cloud VM?

Often, yes, but check the virtual NIC driver first. Some paravirtual drivers support native XDP only with certain queue counts or MTU sizes. Otherwise attaching fails or falls back to generic mode. Run the device probe from earlier on the actual instance type before you commit.

Does it coexist with iptables or nftables rules?

Partly. An XDP program acts before netfilter, so a packet you forward with XDP_TX never meets your iptables rules. If your security model depends on those rules, enforce the same policy inside the eBPF program or pass the traffic up with XDP_PASS.

Is generic XDP good enough for development?

For checking logic, yes. It behaves correctly on any driver, so you can test parsing, map lookups and rewrites in a namespace lab. Don't take performance numbers from it, and test native mode on real hardware before production.

How do I update backends without dropping connections?

Keep established flows in the pinning map and change only where new flows go. Mark a departing backend as draining, stop hashing new flows to it, and wait for its flow entries to age out. Only then remove it from the backend set.