Self-Hosted eBPF TCP/IP Stack Bypass with AF_XDP and io_uring for Ultra-Low-Latency Networking
Quick Summary (TL;DR)
- AF_XDP lets a userspace process receive packets directly from a NIC queue via a shared memory region (UMEM), bypassing the kernel TCP/IP stack while keeping the NIC under kernel control.
- XDP eBPF programs steer packets to a specific AF_XDP socket with
bpf_redirect_map()at line rate, before the kernel allocates ansk_buff.- io_uring batches TX/RX submissions and completions, cutting syscall overhead and enabling
IORING_SETUP_IOPOLL-style busy-polling.- Expect sub-10 µs packet round-trips on modern 10G/25G NICs with zero-copy mode, dedicated cores, and tuned IRQ/CPU affinity.
- AF_XDP is a pragmatic middle ground between the standard kernel stack and full DPDK bypass—easier to operate, slightly higher latency than DPDK, but far more flexible.
Introduction: Why Bypass the Kernel TCP/IP Stack?
The Linux networking stack is a marvel of generality—and that generality costs you. Every packet traverses softirq processing, socket layer lookups, memory allocation for sk_buff structures, and TCP state machine bookkeeping. For a web server, this is fine. For a market-data feed, a DDoS scrubbing appliance, or a 5G user-plane function, each of those steps adds microseconds you cannot afford.
Kernel bypass traditionally meant DPDK: take the NIC with vfio-pci, dedicate cores, manage hugepages, and reimplement everything. It works, but it is operationally heavy. AF_XDP offers a third path: the kernel still owns the NIC, still runs its driver, and still lets you ip link and ss the interface—but selected packets are redirected into a userspace memory region with zero copies and no sk_buff allocation.
This guide walks through building a production-grade AF_XDP data plane, using eBPF XDP for steering and io_uring for efficient I/O batching. By the end you will have a working mental model, configuration snippets, and benchmark methodology.
Prerequisites and Hardware Considerations
Before writing a line of code, verify your platform supports the fast path.
| Requirement | Minimum | Recommended |
|---|---|---|
| Linux kernel | 5.4 | 6.1+ (mature AF_XDP + io_uring) |
| NIC driver | XDP copy-mode support | Zero-copy: i40e, ice, mlx5, bnxt |
| CPU | 4 cores | 8+ cores, isolated via isolcpus |
| Memory | 4 GB | 16 GB, 1 GB hugepages for UMEM |
| Toolchain | clang 10, libbpf 0.6 | clang 15+, libbpf 1.2+, libxdp |
Verify zero-copy support on your interface:
ethtool -i eth0 | grep driver
# Look for "xdpsock" in the driver's supported features
ip link set dev eth0 xdp off # ensure clean state
Check that your kernel has the required config:
zgrep -E 'CONFIG_XDP_SOCKETS|CONFIG_IO_URING' /proc/config.gz
# CONFIG_XDP_SOCKETS=y
# CONFIG_IO_URING=y
Also isolate cores for the data plane. Add to your kernel command line:
isolcpus=2-7 nohz_full=2-7 rcu_nocbs=2-7
Architecture Overview: AF_XDP, XDP, and io_uring
The data path has three cooperating pieces. The diagram below shows how a packet flows from the wire into your application.
flowchart LR
NIC[NIC RX Queue] -->|DMA| UMEM[(UMEM<br/>shared memory)]
XDP[XDP eBPF Program<br/>bpf_redirect_map] -->|steer| XSK[AF_XDP Socket]
UMEM --> XSK
XSK -->|RX Ring| APP[Userspace App<br/>io_uring loop]
APP -->|TX Ring| XSK
XSK -->|bpf_redirect_map| XDP
XDP -->|DMA| NIC
APP -.->|submit/completion| IOU[io_uring SQ/CQ]
AF_XDP Zero-Copy Sockets
An AF_XDP socket is bound to a specific (interface, queue ID) pair. In zero-copy mode, the NIC driver DMAs packets directly into your registered UMEM—a contiguous userspace buffer chopped into fixed-size frames (typically 2048 or 4096 bytes). The kernel never copies a byte; it just moves descriptors (frame addresses) between rings.
eBPF XDP Programs for Packet Steering
An XDP program runs in the driver’s NAPI poll context before any socket allocation. It inspects the packet and returns an action. To route to AF_XDP, you use a redirect map keyed by queue:
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
struct {
__uint(type, BPF_MAP_TYPE_XSKMAP);
__uint(max_entries, 64);
__type(key, __u32);
__type(value, __u32);
} xsks_map SEC(".maps");
SEC("xdp")
int xdp_steer(struct xdp_md *ctx) {
void *data = (void *)(long)ctx->data;
void *data_end = (void *)(long)ctx->data_end;
if (data + sizeof(struct ethhdr) > data_end)
return XDP_PASS;
/* Example: send UDP port 9000 to the AF_XDP socket on this queue */
struct ethhdr *eth = data;
if (eth->h_proto == __builtin_bswap16(0x0800)) {
struct iphdr *ip = data + sizeof(*eth);
if ((void *)(ip + 1) <= data_end && ip->protocol == IPPROTO_UDP) {
struct udphdr *udp = (void *)ip + sizeof(*ip);
if ((void *)(udp + 1) <= data_end &&
udp->dest == __builtin_bswap16(9000))
return bpf_redirect_map(&xsks_map, ctx->rx_queue_index, XDP_PASS);
}
}
return XDP_PASS;
}
Everything not redirected continues to the normal kernel stack—so SSH, monitoring, and DNS keep working on the same interface.
io_uring for Efficient Submission and Completion
AF_XDP’s rings are polled, so you can spin on them directly. But io_uring adds batching and a uniform completion model. Using IORING_OP_POLL_ADD (or the newer socket ops) against the AF_XDP file descriptor lets you:
- Submit many RX/TX operations in one
io_uring_enter()syscall. - Use
IORING_SETUP_SQPOLLto offload submission to a kernel thread. - Combine with
IORING_SETUP_IOPOLLfor zero-interrupt completion.
For a pure AF_XDP data plane, the idiomatic pattern is busy-poll on the rings with io_uring handling control-plane and ancillary I/O (logs, metrics, config). Hybrid designs use io_uring to batch sendmsg() on the AF_XDP fd for TX bursts.
Step 1: Configure UMEM and AF_XDP Socket
UMEM Registration
UMEM must be page-aligned, hugepage-backed for best TLB behavior, and registered once:
struct xdp_umem_reg mr = {
.addr = (uint64_t)umem_area,
.len = NUM_FRAMES * FRAME_SIZE,
.chunk_size = FRAME_SIZE,
};
setsockopt(xsk_fd, SOL_XDP, XDP_UMEM_REG, &mr, sizeof(mr));
setsockopt(xsk_fd, SOL_XDP, XDP_UMEM_FILL_RING, &fill_entries, sizeof(int));
setsockopt(xsk_fd, SOL_XDP, XDP_UMEM_COMPLETION_RING, &comp_entries, sizeof(int));
Practical sizing: 4096 frames × 2048 bytes = 8 MB. Round the ring sizes to powers of two (2048 or 4096 entries is typical).
Ring Setup
struct xdp_mmap_offsets off;
socklen_t optlen = sizeof(off);
getsockopt(xsk_fd, SOL_XDP, XDP_MMAP_OFFSETS, &off, &optlen);
void *fill = mmap(NULL, off.fr.desc + fill_entries * sizeof(__u64),
PROT_READ|PROT_WRITE, MAP_SHARED|MAP_POPULATE,
xsk_fd, XDP_UMEM_PGOFF_FILL_RING);
void *comp = mmap(NULL, off.cr.desc + comp_entries * sizeof(__u64),
PROT_READ|PROT_WRITE, MAP_SHARED|MAP_POPULATE,
xsk_fd, XDP_UMEM_PGOFF_COMPLETION_RING);
Then pre-fill the FILL ring with all frame addresses so the kernel has descriptors to hand you.
Binding to a Queue
struct sockaddr_xdp sxdp = {
.sxdp_family = AF_XDP,
.sxdp_ifindex = if_nametoindex("eth0"),
.sxdp_queue_id = 2,
.sxdp_flags = XDP_ZEROCOPY | XDP_COPY, /* prefer zero-copy, fall back */
};
bind(xsk_fd, (struct sockaddr *)&sxdp, sizeof(sxdp));
Pin your process to the same NUMA node as the NIC and, ideally, the same CPU handling that queue’s IRQ.
Step 2: Load and Attach XDP Program
Using libxdp (recommended over raw bpf() calls for multi-program support):
ip link set dev eth0 xdp off
xdp-loader load -m skb eth0 xdp_steer.o # skb mode for testing
xdp-loader load -m native eth0 xdp_steer.o # native mode for production
Populate the xsks_map from userspace with the socket’s fd and queue index:
__u32 key = queue_id;
__u32 val = xsk_fd;
bpf_map_update_elem(map_fd, &key, &val, BPF_ANY);
Attach in native mode only after confirming the driver supports it (xdp-loader status).
Step 3: Implement Packet Processing Loop with io_uring
The hot loop is deceptively simple—the complexity lives in ring bookkeeping:
for (;;) {
/* 1. Reap completed TX frames */
while (xsk_ring_cons__peek(&tx_cq, BATCH, &idx))
xsk_ring_cons__release(&tx_cq, BATCH);
/* 2. Refill FILL ring with free frames */
unsigned int free_frames = xsk_prod_nb_free(&fill_ring, BATCH);
if (free_frames) {
for (unsigned int i = 0; i < free_frames; i++)
*xsk_ring_prod__fill_addr(&fill_ring, idx + i) = free_stack[--sp];
xsk_ring_prod__submit(&fill_ring, free_frames);
}
/* 3. Process RX */
unsigned int rcvd = xsk_ring_cons__peek(&rx_ring, BATCH, &idx);
for (unsigned int i = 0; i < rcvd; i++) {
struct xdp_desc *d = xsk_ring_cons__rx_desc(&rx_ring, idx + i);
uint8_t *pkt = xsk_umem__get_data(umem_area, d->addr);
handle_packet(pkt, d->len);
/* Return frame to free stack, or queue for TX */
}
xsk_ring_cons__release(&rx_ring, rcvd);
/* 4. Submit TX */
unsigned int tx_avail = xsk_prod_nb_free(&tx_ring, BATCH);
if (tx_avail && pending_tx) {
unsigned int n = enqueue_tx(&tx_ring, tx_avail);
xsk_ring_prod__submit(&tx_ring, n);
sendto(xsk_fd, NULL, 0, MSG_DONTWAIT, NULL, 0); /* kick kernel */
}
}
Wrap the loop with io_uring for control operations—periodic stats flush, config reloads, or forwarding decisions that need to read a socket:
struct io_uring_sqe *sqe = io_uring_get_sqe(&ring);
io_uring_prep_poll_add(sqe, xsk_fd, POLLIN);
io_uring_sqe_set_data(sqe, &xsk_ctx);
io_uring_submit(&ring);
For high-rate workloads, IORING_SETUP_SQPOLL combined with IORING_SETUP_IOPOLL moves submission to a kernel thread and eliminates the syscall entirely from the hot path.
Step 4: Busy-Polling vs. Interrupt-Driven Tradeoffs
This is the single biggest decision affecting your P99 latency.
| Mode | Latency | CPU Cost | Best For |
|---|---|---|---|
| Interrupt-driven | 30–100 µs | Low | General servers, mixed workloads |
| Busy-poll (single core) | 5–15 µs | 100% of one core | Trading, DDoS, telco UPF |
| Busy-poll + io_uring SQPOLL | 3–8 µs | 1 core + kernel thread | Absolute minimum latency |
| Adaptive (idle → poll) | 8–20 µs | Variable | Bursty traffic |
Configure busy-polling via the socket:
int busy_poll_us = 64; /* microseconds of spin after wakeup */
setsockopt(xsk_fd, SOL_SOCKET, SO_BUSY_POLL, &busy_poll_us, sizeof(int));
int busy_poll = 1;
setsockopt(xsk_fd, SOL_SOCKET, SO_PREFER_BUSY_POLL, &busy_poll, sizeof(int));
Or run the loop unconditionally spinning—accept that the core is gone. Always dedicate a core (isolcpus, taskset, cgroup cpuset) so the scheduler doesn’t preempt your poll loop.
Step 5: Integration with Existing DPDK Alternatives
You do not have to choose one framework for the whole system. A common production pattern:
- Data plane on AF_XDP for the fast path (per-packet processing).
- Control plane on the normal kernel stack (SSH, Prometheus, config APIs) on the same interface.
- DPDK only on ports that need the absolute minimum latency and can be fully dedicated.
For migration, keep your packet-processing logic framework-agnostic by abstracting the ring API behind an interface. Then a single binary can run either AF_XDP or DPDK based on a config flag.
Performance Tuning and Benchmarking
Baseline checklist:
# Pin NIC IRQs to CPUs on the same NUMA node
for irq in $(grep eth0 /proc/interrupts | awk -F: '{print $1}'); do
echo 2 > /proc/irq/$irq/smp_affinity_list
done
# Disable C-states on the polling core (add to kernel cmdline)
# processor.max_cstate=1 intel_idle.max_cstate=0
# Increase ring buffers
ethtool -G eth0 rx 4096 tx 4096
# Use hugepages for UMEM
echo 8 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
Benchmark with xdp-bench for raw forwarding rate and a custom cyclesoak-style harness for latency:
xdp-bench redirect -m native eth0 xsk_steer.o --rx-queue 2
# Expected: 10–25 Mpps on a 25G NIC with zero-copy
Measure P50/P99/P999 latency with wrk2 or trafgen and watch for the tell-tale sign of ring starvation: rising FILL-ring empty events correlate directly with dropped packets.
Comparison: AF_XDP vs. DPDK vs. Kernel Bypass
| Dimension | AF_XDP | DPDK | Kernel stack |
|---|---|---|---|
| Latency (P99) | 5–15 µs | 3–8 µs | 50–200 µs |
| Throughput (25G NIC) | ~20 Mpps | ~30 Mpps | ~3 Mpps |
| CPU model | 1 core per queue | 1 core per queue + mgmt | Shared |
| NIC ownership | Kernel | Exclusive (vfio-pci) | Kernel |
| Coexists with kernel networking | ✅ Yes | ❌ No | ✅ Yes |
| Hugepages required | Recommended | Required | No |
| Operational complexity | Medium | High | Low |
| Debuggability | bpftool, xdp-*, ss | Custom tooling | Excellent |
| Production maturity | Mature (6.1+) | Very mature | Very mature |
Conclusion
AF_XDP with eBPF steering and io_uring batching gives you a production-grade, self-hosted kernel-bypass data plane without the operational weight of DPDK. You keep the kernel’s management, security, and observability for everything that isn’t on the hot path, while achieving sub-10-microsecond packet processing on commodity hardware.
Start small: prototype in copy mode on a test VLAN, verify your XDP redirect map works, then graduate to zero-copy with dedicated cores. Measure relentlessly—latency is a property of the whole system, not just the ring API. Once you have the loop running, the biggest wins come from CPU isolation, IRQ affinity, and hugepage-backed UMEM, not from micro-optimizing the code.
FAQ
What is the difference between AF_XDP and DPDK? AF_XDP is a Linux socket family that enables zero-copy packet processing while the kernel still manages the NIC. DPDK is a full kernel-bypass framework that takes exclusive NIC control, requiring dedicated cores and hugepages. AF_XDP integrates more easily with existing kernel networking and is lighter on overhead for mixed workloads; DPDK can achieve slightly lower latency in pure packet-processing scenarios.
Can I use AF_XDP with any network card?
AF_XDP zero-copy mode requires driver support. Most modern 10G/25G/40G NICs from Intel (i40e, ice), Mellanox (mlx5), and Broadcom (bnxt) support XDP zero-copy. Check the driver’s XDP capabilities with xdp-loader status. If unsupported, AF_XDP falls back to copy mode, which has higher overhead but still bypasses the TCP/IP stack.
How does io_uring improve AF_XDP performance?
io_uring provides a unified asynchronous I/O interface that batches submissions and completions, reducing syscall overhead. With AF_XDP, io_uring can manage TX/RX ring operations more efficiently at high packet rates—especially with IORING_SETUP_SQPOLL and IORING_SETUP_IOPOLL—by minimizing context switches and eliminating the per-packet syscall.
What are the tradeoffs of busy-polling? Busy-polling eliminates interrupt latency and can achieve sub-10-microsecond processing, but it consumes 100% of the polling core. It is ideal for dedicated low-latency workloads but wasteful for general-purpose servers. Use adaptive polling or dedicated isolated cores to prevent impact on other applications.
Is AF_XDP suitable for production use? Yes. AF_XDP is production-ready and deployed in high-performance networking applications including load balancers, DDoS mitigation, and financial trading systems. It has been available since Linux 4.18 and matured significantly in 6.x kernels. It requires careful tuning, monitoring, and a clear separation between fast-path and control-path responsibilities.
How do I choose between AF_XDP and DPDK? Choose AF_XDP when you need low latency but want to retain kernel networking for management, security, or mixed workloads. Choose DPDK when you need the absolute lowest latency, can dedicate entire cores and NIC ports to the application, and are willing to manage the NIC exclusively. Many teams run both—AF_XDP for most ports, DPDK for the few that demand it.