Userspace Beats the Kernel Dataplane: What an IPsec Mesh Actually Costs
A single TCP flow on a 10 GbE link has one bottleneck the moment it enters a kernel dataplane: it lands on one receive queue, and every packet on that path shar...
A single TCP flow on a 10 GbE link has one bottleneck the moment it enters a kernel dataplane: it lands on one receive queue, and every packet on that path shares one lock, one reorder window, and one context switch. Measured on two PowerEdge C6420 hosts with X710 NICs and Debian 13, kernel WireGuard carried 5.1 to 5.4 Gbit/s one way and kernel IPsec 4.0 to 4.7 Gbit/s, because neither can steer one flow across receive queues. A userspace datapath with the same protocol moved 8.39 of a theoretical 8.84 Gbit/s payload limit.
That number is not an argument for rewriting your VPN in Go for fun. It is an argument about where ownership sits. A kernel dataplane owns the receive path and you inherit its concurrency model. A purpose-built forwarder owns both ends of the pipeline, so it can batch, reorder, and schedule without a per-packet synchronization point it did not choose.
Userspace wins when the kernel's sharing model becomes the floor
The kernel is optimized for many flows from many tenants, not one flow at line rate. Every packet costs an sk_buff allocation, a spinlock acquisition on the anti-replay window, and a traversal of the socket receive path. Those costs amortize across ten thousand flows and dominate when you have one.
WireGuard's own maintainers ran into this at 100 GbE: packet size barely moved the packets-per-second ceiling, which is the signature of a fixed per-packet cost rather than a bandwidth limit. A single goroutine feeding the crypto workers, RoutineReadFromTUN, serialized the whole pipeline. Giving the TUN multi-queue support and one reader per queue took stock wireguard-go from roughly 350 kpps to 1.5 Mpps without touching the protocol. Batching the replay-window lock across 64 packets and widening the window from 8,128 to 131,008 counters (1 KB to 16 KB of bitmap per session) took it to 29.9 Mpps clean.
Those are small-packet numbers, and they required kernel bypass: DPDK or AF_XDP hands the NIC to the process, which means tcpdump stops seeing transit traffic and nftables stops filtering it. An SD-WAN overlay that expects to coexist with a host firewall cannot pay that price. The middle path is ordinary UDP sockets with a batched egress loop, which is where the 8.39 Gbit/s figure lives.
func (d *Dataplane) egress(ctx context.Context) error {
batch := make([]*ipv4.Header, 0, d.batchSize)
frames := make([][]byte, 0, d.batchSize)
for {
n, err := d.tun.ReadBatch(frames[:0], 64)
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
continue
}
return fmt.Errorf("tun read batch: %w", err)
}
batch = batch[:0]
for i := 0; i < n; i++ {
pkt := frames[i]
flow, ok := d.flowTable.Lookup(pkt)
if !ok {
d.counters.Unroutable.Add(1)
continue
}
if err := flow.sa.SealInPlace(pkt, d.seq.Next()); err != nil {
return fmt.Errorf("seal packet from %s: %w", flow.peer, err)
}
batch = append(batch, pkt)
}
if err := d.udp.WriteBatch(batch); err != nil {
d.counters.TxErrors.Add(1)
}
}
}
Two details carry the performance. ReadBatch turns sixty-four fixed costs into one, and SealInPlace encrypts into the frame the TUN already allocated, so the datapath has no copy between decapsulation and transmission. Batching costs up to one batch of added latency, which is why the batch size has to be tuned against the tail, not the median. A mutex around flowTable would put the serialization point right back where the kernel had it.
ranet3's design isolates the same conclusion with a different mechanism: keep the socket path, avoid per-packet locking, and let the kernel's own NIC queue distribution handle fan-out, because the offered load is Gbit/s rather than Mpps. Different point on the same curve, same root constraint.
The mesh control plane is a measurement loop with hysteresis, not a topology graph
A mesh has incomplete information by construction: each node knows its neighbors and what they report, nothing about the interior of a path three hops away. The only honest input is something you measured yourself, and RTT is the cheapest signal both endpoints agree on.
Babel's delay extension, RFC 9616, defines the measurement and then spends most of its length on why the raw value cannot be used directly. Two problems are named explicitly. First, RTT feeds back into itself: the lowest-latency route attracts traffic, congestion raises its RTT, traffic moves away, the route recovers, traffic returns. Without hysteresis you get synchronized oscillation, and route oscillation means packet reordering, which destroys TCP throughput far more effectively than a stable but suboptimal path. Second, RTT is noisy even on an idle link.
The spec's answer is a mapping from a sequence of RTT samples to a link cost, with a floor and a ceiling and a smoothing law in between. The practical consequence for anyone building an overlay: route selection compares computed costs, not samples, and a cost change has to clear a threshold before it changes forwarding.
The case that makes this concrete: node A reaches C directly at 265 ms RTT and through B at 80 ms. Two equal-cost hops beat one high-latency one, so the mesh relays. Now the link quality shifts and the direct path drops to 60 ms. A threshold-free selector flips immediately, and if it flips back the next sample interval, every flow on that prefix gets reordered twice. The selector needs memory of the previous decision, and it needs to treat loss and outage as cost rather than as a binary up/down state.
type Link struct {
Peer netip.Addr
RTT time.Duration
Loss float64
Updated time.Time
}
const (
rttFloor = 2 * time.Millisecond
hysteresis = 0.10
)
func cost(l Link, now time.Time) float64 {
if now.Sub(l.Updated) > 3*staleAfter {
return outageCost
}
base := float64(max(l.RTT, rttFloor)) / float64(time.Millisecond)
return base * (1 + 8*l.Loss)
}
func (r *Router) selectPath(dst netip.Addr, now time.Time) (nexthop netip.Addr, changed bool) {
best, bestCost := r.current[dst], math.Inf(1)
for _, cand := range r.candidates(dst) {
if c := cost(cand, now); c < bestCost {
best, bestCost = cand.Peer, c
}
}
current := cost(r.linkTo(dst, best), now)
if best != r.current[dst] && bestCost < current*(1-hysteresis) {
r.current[dst] = best
return best, true
}
return r.current[dst], false
}
The hysteresis constant is the whole control loop. Ten percent stops a selector from chasing noise, and the staleAfter rule keeps a silent peer in the table as an expensive path instead of deleting it, because a node that stops responding for thirty seconds is more likely to be congested than decommissioned. Deleting it makes the mesh forget how to fail back.
There is a failure mode worth naming because it is invisible in dashboards: a routing policy that compares administrative identifiers instead of measured cost. Hop count, AS-path length, and preference values are topology facts, and a policy built on them will silently prefer the geographically closer path over the faster one for every flow, forever, without ever showing a spike. That is a priority bug, not a performance bug, and no latency graph will surface it.
Policy compiles into a path the dataplane already knows how to execute
Segment routing inverts the usual relationship between policy and configuration. Instead of every node along a route holding a share of the policy, the ingress node writes the entire path into the packet header. IPv6 makes that literal: the segment list is a stack of 128-bit addresses, and each waypoint decrements the segment-left pointer and forwards to the next address.
The property that makes SRv6 deployable is that it degrades into plain IPv6. A router that has never heard of segment routing forwards on the destination address and ignores the routing header, at line rate, without dropping the packet. You can therefore run policy paths across a network where only the ingress and the exit understand the header, which is exactly the situation a mesh overlay is in when it crosses a provider edge.
The kernel-side pieces exist and are old enough to trust: seg6 handles encapsulation with a static segment list bound to a route, seg6local handles the behaviors on the receiving side, and both have been in mainline since 4.10 and 4.14. The limitation is structural rather than a bug: seg6 binds one list per route, evaluated at routing time, and the choice of which list to use is not a routing lookup at all. It is a policy decision that depends on telemetry, and the kernel dataplane has nowhere to keep feedback state.
That is where userspace earns its keep. If the datapath already owns the packet, the segment list can be selected per packet from a state machine the process controls, and the same code runs on an OS whose XNU kernel has no segment routing at all. The policy itself is one line of intent: source prefix, destination prefix, ordered waypoints, exit.
type Policy struct {
Src netip.Prefix
Dst netip.Prefix
Waypoints []netip.Addr
Exit netip.Addr
}
type Selector struct {
compiled atomic.Pointer[routeTable]
}
func (s *Selector) Compile(policies []Policy, sidTable map[netip.Addr]Behavior) error {
tbl := make(routeTable, len(policies))
for _, p := range policies {
segs := make([]netip.Addr, 0, len(p.Waypoints)+1)
for _, w := range p.Waypoints {
if _, ok := sidTable[w]; !ok {
return fmt.Errorf("policy %s->%s: waypoint %s has no local SID", p.Src, p.Dst, w)
}
segs = append(segs, w)
}
tbl[p.Src] = append(tbl[p.Src], compiledPolicy{
dst: p.Dst,
segs: append(segs, p.Exit),
})
}
s.compiled.Store(&tbl)
return nil
}
Compiling at configuration time rather than per packet is the difference between 8 Gbit/s and a stack trace. The segment list is validated once against the local SID table, and a missing waypoint fails at load time instead of blackholing traffic later. Waypoints can repeat, so A -> B -> C -> B -> D is a legal list, which is how service chaining works when the same inspection node has to see traffic twice.
The costs are concrete. Every waypoint is 16 bytes of header, so a three-waypoint path adds 64 bytes to a packet that already lost 80 to ESP and UDP framing, and the inner MTU has to absorb it or the tunnel has to fragment. Peers must agree on the outer MTU before the first packet, not after the first PMTUD black hole. And the ingress decides: once the packet leaves with a list, the path is frozen. A waypoint that dies mid-list is not repairable in flight, so the recovery loop has to notice a dead SID and rewrite the list for the next packet.
What the benchmark actually measures, and where userspace loses
The 8.39 Gbit/s figure is 95% of the payload limit on a two-host direct link with no switch hops in the measured path aside from one S5296F-ON. Read the relative numbers with that topology in mind: 1.2 to 1.5 times wireguard-go, 1.6 to 2.1 times kernel WireGuard, 1.8 to 3.9 times kernel IPsec, all median of three runs with the dataplanes interleaved so that thermal drift does not favor whichever ran last.
The figure that constrains deployment is 0.9 busy cores per Gbit/s at 3 Gbit/s offered, summed across both hosts. A 4 Gbit/s endpoint spends roughly four cores on transport before routing, logging, or anything else. Sizing follows from that number, and the appealing single-socket 10G router with a small core count is not in the cards unless the workload fits in one flow.
The tail latency is where userspace loses outright: 1.91 to 4.96 ms p99 under saturation against 0.85 to 2.51 ms for the kernel dataplanes. Batching buys throughput with queueing delay, and on a link held at 90% utilization the interactive flows feel it. If your traffic is bulk replication, that trade is free. If it is terminal sessions or RPC fan-out, it is not.
The last 5% of the payload limit is per-packet work that no cipher change touches: session lookup, replay check, buffer accounting, and the syscall boundary. Instrument those counters, not the cryptographic throughput, because that is where the next percent lives.