net/go.book
All Parts Marketing Resources PDF

eBPF and Go: Programmable Networking in the Kernel

"For decades the kernel was a black box: you could watch it from outside with tcpdump, or you could load a kernel module and hope it never panicked. eBPF is the third option the kernel spent years growing: a sandboxed, verified, JIT-compiled program you can attach to the exact moment a packet arrives, and a Go control plane that loads it, reads its maps, and tears it down cleanly."

Why the Kernel Needed a Programmable Datapath

Every packet that reaches your program has already crossed a long path through the kernel: the NIC driver, the network stack, sockets, the scheduler. Historically, if you wanted to see or change something along that path, you had two bad options. You could observe from outside (packet capture, /proc counters, strace) and lose both precision and performance. Or you could write a kernel module, which meant C code running with full kernel privileges, a rebuild for every kernel version, and a bug that takes the whole machine down instead of one process.

eBPF (extended Berkeley Packet Filter) is the answer that stuck. It started as a tiny packet filter for tcpdump, grew into a general in-kernel virtual machine in 2014, and is now the standard way to run sandboxed programs inside the Linux kernel: for networking, for tracing, for security policy, for scheduling. The important part is not that it is a VM. It is that the kernel's verifier proves a program is safe before it ever runs: bounded loops, checked memory accesses, no arbitrary pointer arithmetic, no way to crash or hang the kernel. Only after that proof does the JIT compile it to native instructions.

The kernel does not trust your eBPF program; it proves it. That proof, not good intentions, is what makes running user-written code in kernel space acceptable.

What eBPF Actually Is

An eBPF program is bytecode for a small register machine (ten general-purpose registers and a 512-byte stack), with no access to the filesystem, the scheduler, or arbitrary kernel memory. It can only call helpers the kernel exposes for its program type, and it can only touch memory the verifier has proven is in bounds.

Two other pieces complete the model. Maps are key/value stores shared between the kernel program and user space: counters, connection tables, configuration. Attach points decide when the program runs: on every packet at a hook, on a syscall, on a function entry, on a tracepoint.

The Hooks That Matter for Networking

XDP: the earliest hook

Express Data Path runs your program in the driver's receive path, before the kernel allocates a socket buffer for the packet. That is why XDP is used for DDoS mitigation and load balancing: you can decide to pass, drop, or redirect a packet at the earliest possible moment, for a fraction of the cost of the normal stack. You can also modify the packet, but the driver's support (native, generic, or offloaded mode) decides what is possible.

tc: the programmable qdisc

Traffic control hooks run later, after the packet has an sk_buff. They see both ingress and egress, can be organized in a hierarchy, and are the right tool when you need more context than XDP offers, or when you need egress shaping.

Socket filters

The original use case: a program attached to a socket decides which packets that socket receives. SO_ATTACH_BPF is how classic BPF filters, and their modern descendants, still work.

Tracing: kprobe, tracepoint, uprobe

For observability, kprobes fire on kernel function entry and exit, tracepoints on stable kernel events, uprobes on user-space functions. Instead of guessing why connect is slow, you attach to tcp_connect and record the latency in a map.

Maps: The Other Half

A map is what makes an eBPF program useful rather than merely fast. The common types for networking work:

Type Use it for
BPF_MAP_TYPE_ARRAY Fixed-size counters, config, small lookup tables
BPF_MAP_TYPE_HASH Connection tracking, per-IP state, LRU caches
BPF_MAP_TYPE_PERCPU_ARRAY Counters without atomic contention
BPF_MAP_TYPE_RINGBUF Streaming events from kernel to user space
BPF_MAP_TYPE_LRU_HASH Bounded state where eviction is acceptable

Maps are file descriptors in user space, which is why a Go program can read them, update them, and share them with another process by pinning them under /sys/fs/bpf.

The Go Toolchain in 2026

The Go side of eBPF is mature. cilium/ebpf is a pure-Go library that loads compiled objects, attaches programs, and reads maps without cgo. bpf2go (in the same project) generates Go types from a C file and embeds the compiled object, which is the standard workflow: //go:generate go run github.com/cilium/ebpf/cmd/bpf2go counter counter.bpf.c.

In this chapter we compile the C and load the object explicitly instead. It is a few lines more, but every step stays visible, which is what you want the first time.

A Complete XDP Program: Counting Packets by Protocol

The C program counts IPv4 packets by protocol as they arrive. Notice the shape of every safe eBPF parser: read data and data_end, check the header fits before dereferencing it, and return XDP_PASS unless you deliberately mean something else.

// counter.bpf.c -- counts packets per IP protocol at the XDP hook.
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <bpf/bpf_endian.h>
#include <bpf/bpf_helpers.h>

// Keys into the counter map.
#define PROTO_TCP 0
#define PROTO_UDP 1
#define PROTO_ICMP 2
#define PROTO_OTHER 3

struct {
	__uint(type, BPF_MAP_TYPE_ARRAY);
	__uint(max_entries, 4);
	__type(key, __u32);
	__type(value, __u64);
} proto_counts SEC(".maps");

SEC("xdp")
int count_protocols(struct xdp_md *ctx)
{
	void *data = (void *)(long)ctx->data;
	void *data_end = (void *)(long)ctx->data_end;

	struct ethhdr *eth = data;
	if ((void *)(eth + 1) > data_end) {
		return XDP_PASS;
	}

	__u32 key = PROTO_OTHER;
	if (eth->h_proto == bpf_htons(ETH_P_IP)) {
		struct iphdr *ip = (void *)(eth + 1);
		if ((void *)(ip + 1) <= data_end) {
			switch (ip->protocol) {
			case IPPROTO_TCP:
				key = PROTO_TCP;
				break;
			case IPPROTO_UDP:
				key = PROTO_UDP;
				break;
			case IPPROTO_ICMP:
				key = PROTO_ICMP;
				break;
			}
		}
	}

	__u64 *count = bpf_map_lookup_elem(&proto_counts, &key);
	if (count) {
		__sync_fetch_and_add(count, 1);
	}

	return XDP_PASS;
}

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

Compile it with clang, targeting the BPF architecture:

clang -O2 -g -Wall -target bpf -c counter.bpf.c -o counter.bpf.o

The SEC("xdp") attribute is what places the compiled code in an ELF section the loader can find by name; the map definition lives in a .maps section with BTF metadata describing its key and value types.

The Go loader reads that object, finds the program and map by name, attaches the program to an interface, and polls the map:

// counter.go -- loads counter.bpf.o, attaches it to an interface and
// prints the per-protocol packet counts every two seconds.
package main

import (
	"fmt"
	"log"
	"net"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/cilium/ebpf"
	"github.com/cilium/ebpf/link"
	"github.com/cilium/ebpf/rlimit"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "usage: %s <interface>\n", os.Args[0])
		os.Exit(2)
	}
	// Older kernels charge eBPF maps and programs against RLIMIT_MEMLOCK.
	if err := rlimit.RemoveMemlock(); err != nil {
		log.Printf("remove memlock limit: %v", err)
	}

	iface, err := net.InterfaceByName(os.Args[1])
	if err != nil {
		log.Fatalf("interface %q: %v", os.Args[1], err)
	}

	spec, err := ebpf.LoadCollectionSpec("counter.bpf.o")
	if err != nil {
		log.Fatalf("load spec: %v", err)
	}
	var objs struct {
		CountProtocols *ebpf.Program `ebpf:"count_protocols"`
		ProtoCounts    *ebpf.Map     `ebpf:"proto_counts"`
	}
	if err := spec.LoadAndAssign(&objs, nil); err != nil {
		log.Fatalf("load objects: %v", err)
	}
	defer objs.CountProtocols.Close()
	defer objs.ProtoCounts.Close()

	xdp, err := link.AttachXDP(link.XDPOptions{
		Program:   objs.CountProtocols,
		Interface: iface.Index,
	})
	if err != nil {
		log.Fatalf("attach XDP to %s: %v", iface.Name, err)
	}
	defer xdp.Close()
	log.Printf("counting packets on %s; Ctrl-C to stop", iface.Name)

	names := []string{"TCP", "UDP", "ICMP", "other"}
	ticker := time.NewTicker(2 * time.Second)
	defer ticker.Stop()
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)

	for {
		select {
		case <-ticker.C:
			for i, name := range names {
				var n uint64
				err := objs.ProtoCounts.Lookup(uint32(i), &n)
				if err != nil {
					log.Printf("lookup %s: %v", name, err)
					continue
				}
				fmt.Printf("%s=%d ", name, n)
			}
			fmt.Println()
		case <-stop:
			return
		}
	}
}

Attach it to the loopback interface, which carries plenty of traffic and cannot break anything:

go mod init counter
go get github.com/cilium/ebpf@latest
sudo ./counter lo

You should see a line every two seconds while curl or ping generates traffic on lo:

TCP=42 UDP=8 ICMP=6 other=0

Reading Counters Without Lying to Yourself

The array map plus __sync_fetch_and_add above is correct, but every packet on every CPU contends for the same cache line. For high packet rates, switch the map to BPF_MAP_TYPE_PERCPU_ARRAY: the kernel gives each CPU its own copy of every value, so the update becomes a plain increment with no atomics, and user space sums the copies:

struct {
	__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
	__uint(max_entries, 4);
	__type(key, __u32);
	__type(value, __u64);
} proto_counts SEC(".maps");
var perCPU []uint64
if err := objs.ProtoCounts.Lookup(uint32(i), &perCPU); err != nil {
	log.Printf("lookup %d: %v", i, err)
	continue
}
var total uint64
for _, v := range perCPU {
	total += v
}

The library allocates the slice with one element per possible CPU. The trade-off is memory proportional to CPUs times entries, which is irrelevant for four counters and very relevant for a million-entry connection table.

Testing eBPF Locally Without Breaking Your Network

XDP runs before the kernel's routing decision, so a bug that returns XDP_DROP everywhere takes the interface down instantly. Test in a network namespace with a veth pair, never on your real interface first:

sudo ip netns add ebpf-lab
sudo ip link add veth0 type veth peer name veth1
sudo ip link set veth1 netns ebpf-lab
sudo ip addr add 10.0.0.1/24 dev veth0
sudo ip addr add 10.0.0.2/24 dev veth1 netns ebpf-lab
sudo ip link set veth0 up
sudo ip -n ebpf-lab link set veth1 up
sudo ip -n ebpf-lab link set lo up
sudo ./counter veth0

Then generate traffic from inside the namespace (sudo ip netns exec ebpf-lab ping -c 3 10.0.0.1) and watch the counters. When you are done:

sudo ip netns del ebpf-lab
sudo ip link del veth0

Loading eBPF programs needs CAP_BPF and CAP_NET_ADMIN (or root); in containers, those capabilities are usually dropped, which is why eBPF tooling in Kubernetes runs as a privileged DaemonSet.

Production: What Bites

  • The verifier is strict, and its error messages assume you know why. Bounded loops, no reading uninitialized stack, no pointer arithmetic across maps. Most failures are a missing bounds check or a loop the verifier cannot prove terminates.
  • XDP sees raw packets, not streams. Parsing TCP reassembly or HTTP there is a mistake; do stateless decisions and push stateful work to tc or user space.
  • Return XDP_PASS unless you mean it. The default path must be "do no harm".
  • Driver support varies. Check mode with ip link show dev eth0; generic mode works almost everywhere but is slower.
  • Maps are memory you must size. A hash map with a million entries of 64-byte values is 64 MB per CPU if it is per-CPU.
  • Portability needs CO-RE. Reading kernel struct fields directly breaks across versions; bpf_core_read plus BTF makes one object work on many kernels. This is why modern projects compile with -g and ship BTF.
  • Measure the overhead. A per-packet program runs per packet; a few instructions matter at 10 Mpps. Use bpftool prog show and perf top before and after.
  • You now own kernel-adjacent failure modes. A detached program disappears; a pinned one survives restarts. Decide explicitly.

When Not to Use eBPF

If a userspace proxy, an iptables rule, or a library solves the problem, eBPF is extra complexity with a privileged deployment. Skip it if you need portable code across operating systems, if your platform does not grant the capabilities, or if the logic is stateful at layer 7. The right mental model is: eBPF is for hot-path decisions and kernel visibility, not for application logic.

The Ecosystem in 2026

Cilium uses eBPF for Kubernetes networking and policy; Tetragon for runtime security; Parca for continuous profiling; Pixie for observability. On the tooling side, bpftool inspects programs and maps, bpftrace is a high-level tracing language, and bpf2go remains the standard way to embed objects in Go binaries. Reading a real project's C and Go side by side is the fastest way to learn after this chapter.

Frequently Asked Questions

Do I need a C compiler to write eBPF with Go? For most real programs, yes: the kernel-side program is usually C (or Rust) compiled to BPF bytecode, and Go handles loading, attaching, and map access. Pure-Go assemblers exist, and cilium/ebpf can emit instructions directly, but C with clang is the mainstream path and what the examples in this chapter use.

Why did my program fail to load with permission denied? Loading requires CAP_BPF and CAP_NET_ADMIN, or root. In containers those are usually dropped. The other common cause is the old RLIMIT_MEMLOCK limit, which rlimit.RemoveMemlock() raises when the kernel charges eBPF memory against it.

Is XDP faster than a normal socket program? For the work it does, yes: the packet has no socket, no routing lookup, and no copy yet. But "faster" only matters if you need that work on every packet. A well-written Go server is not made faster by adding eBPF; a DDoS filter or a load balancer is.

Can I write my whole service as eBPF? No, and you should not want to. eBPF programs are small, bounded, and stateless by design; the Go program remains the control plane that configures, observes, and decides. That split is the normal architecture, not a limitation to work around.

Key Takeaways

  • eBPF is a verified, JIT-compiled in-kernel VM: the verifier proves safety before anything runs.
  • Attach points define the job: XDP for the earliest packet decisions, tc for ingress/egress shaping, kprobes and tracepoints for visibility, socket filters for classic filtering.
  • Maps are the bridge between kernel and Go: counters, state, and ring buffers passed as file descriptors.
  • cilium/ebpf is the pure-Go control plane; clang compiles the C; bpf2go optionally embeds the object.
  • Every packet parser must check data_end before reading, and every program should default to XDP_PASS.
  • Prefer per-CPU maps for counters, bound your maps, and test in a network namespace before touching a real interface.
  • Use eBPF when you need per-packet decisions or kernel visibility. Use Go for everything else.
Discuss this chapter Star the book
Comment on GitHub
Rate