Where the microseconds go
The objective of this lesson: explain, step by step, what the kernel does between a packet arriving at the network card and your recv() returning, which of those steps kernel bypass removes, and what it costs you in exchange.
A UDP market-data packet arriving through a normal Linux socket goes through roughly this path:
- The NIC writes the frame into a ring buffer in host memory by DMA and raises an interrupt (or the kernel is already polling it under NAPI).
- The driver builds a socket buffer (
sk_buff), and the kernel runs the IP and UDP layers, filtering and routing rules. - The data is queued on the socket and the sleeping application thread is woken up: the scheduler must pick it and switch to it, possibly on another core with cold caches.
recv()returns across the user/kernel boundary and copies the bytes into the application's buffer.
Sending is the mirror: a system call, a copy, queuing disciplines, the driver, and a doorbell write to the NIC. Each step is small, but together, and especially the wake-up, they cost several microseconds, with a long tail when the scheduler or an interrupt gets in the way.
A measurement on this machine
This program bounces a 64-byte UDP datagram between two sockets over loopback, first with blocking recv and then spinning on non-blocking recv. Loopback involves no NIC or wire, so it measures only the kernel's software path.
#include <algorithm>
#include <arpa/inet.h>
#include <chrono>
#include <cstdio>
#include <netinet/in.h>
#include <sys/socket.h>
#include <thread>
#include <unistd.h>
#include <vector>
// Ping-pong 64-byte UDP datagrams over loopback through the kernel stack.
// No NIC is involved, so this is a lower bound on the kernel's software cost.
int bound_socket(sockaddr_in& addr) {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
addr = {};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = 0; // let the kernel pick a port
bind(fd, (sockaddr*)&addr, sizeof addr);
socklen_t len = sizeof addr;
getsockname(fd, (sockaddr*)&addr, &len);
return fd;
}
// Blocking recv sleeps until a packet arrives; spinning recv polls with
// MSG_DONTWAIT and never gives up the core.
void get(int fd, char* p, bool spin) {
if (!spin) { recv(fd, p, 64, 0); return; }
while (recv(fd, p, 64, MSG_DONTWAIT) < 0) {}
}
void run(bool spin) {
sockaddr_in a, b;
int fa = bound_socket(a), fb = bound_socket(b);
const int N = 50000;
char buf[64] = {};
std::thread echo([&] { // echo server: receive on b, reply to a
for (int i = 0; i < N; ++i) {
get(fb, buf, spin);
sendto(fb, buf, sizeof buf, 0, (sockaddr*)&a, sizeof a);
}
});
std::vector<double> rtt_us;
char msg[64] = {};
for (int i = 0; i < N; ++i) {
auto t0 = std::chrono::steady_clock::now();
sendto(fa, msg, sizeof msg, 0, (sockaddr*)&b, sizeof b);
get(fa, msg, spin);
auto t1 = std::chrono::steady_clock::now();
rtt_us.push_back(std::chrono::duration<double, std::micro>(t1 - t0).count());
}
echo.join();
std::sort(rtt_us.begin(), rtt_us.end());
auto pct = [&](double q) { return rtt_us[size_t(q * (rtt_us.size() - 1))]; };
std::printf("%s round trip (us): p50 %.1f p99 %.1f p99.9 %.1f max %.1f\n",
spin ? "spinning" : "blocking", pct(0.5), pct(0.99), pct(0.999), rtt_us.back());
close(fa);
close(fb);
}
int main() {
run(false);
run(true);
}
One run on the Apple M1 laptop (macOS, c++ -std=c++20 -O2 -pthread; machine-specific):
blocking round trip (us): p50 15.7 p99 73.5 p99.9 117.1 max 231.8
spinning round trip (us): p50 25.7 p99 93.2 p99.9 141.2 max 706.2
Two lessons. First, even with no hardware involved, a kernel round trip here has a median around 16 µs and a 99.9th percentile above 100 µs: the tail is several times the median. Second, spinning on the system call made it worse. Every failed recv is still a trip into the kernel that takes the socket's locks, competing with the thread delivering the packet. Busy polling pays off when the poll is an ordinary memory read of a ring the NIC writes into, which is what kernel bypass provides. (A tuned Linux server with pinned cores does much better than a laptop, but the structure of the costs is the same.)
Kernel bypass
The idea: map the NIC's receive and transmit descriptor rings and packet buffers directly into the application's address space. The application polls the ring in a loop. No interrupt, no system call, no wake-up, no copy, and the packet is processed on the core that is already hot.
- DPDK (Data Plane Development Kit): user-space poll-mode drivers for many NICs. The NIC is detached from the kernel (bound to
vfio-pci), packet buffers live in huge pages, and the application callsrte_eth_rx_burstto collect a batch of packets (often 32) per poll. There is no TCP/IP stack included: you handle Ethernet/IP/UDP yourself or add a user-space stack. Very common for high packet rates. - OpenOnload (AMD Solarflare NICs): a user-space TCP/UDP stack behind the ordinary sockets API. Run an unmodified binary as
onload ./appand its socket calls are intercepted and served from user space. Least code change; the usual first step. - ef_vi (same NICs): the low-level layer below Onload. The application gets a virtual interface and works with raw Ethernet frames and descriptor rings directly. More code, lowest software latency, typical for market-data handlers that only need UDP multicast in and a small number of order connections out.
- Others in the same family: AF_XDP (a fast path to user space built into Linux), and RDMA / ibverbs for host-to-host messaging.
What you give up: the kernel's protections and tools (tcpdump, firewall rules, standard sockets for DPDK), portability across NICs, and a CPU core per polling thread.
Busy polling and core isolation
A polling thread runs at 100% CPU even when nothing arrives, by design. To make that worthwhile:
- Pin it to a core (
taskset,pthread_setaffinity_np) and isolate that core from the scheduler (isolcpus,nohz_fullto stop the timer tick, interrupts routed elsewhere), so nothing preempts it. - Keep the core on the same NUMA node as the NIC, so DMA'd packets land in local memory and cache.
- Do not allocate, take locks or make system calls on that thread; hand slow work to another core over a lock-free queue.
Linux also offers a middle ground, SO_BUSY_POLL, where the kernel itself polls the device queue for a short time inside recv: lower latency than interrupts while keeping the socket API.
NIC hardware timestamping
A timestamp taken in your program after recv() returns includes every delay you are trying to measure: interrupt handling, queueing, the wake-up. Many NICs can stamp each packet in hardware as it crosses the MAC, and Linux exposes this through SO_TIMESTAMPING. Clocks on different NICs and hosts are kept aligned with PTP (IEEE 1588). Firms measure tick-to-trade (market-data packet in, order packet out) by capturing both packets with hardware timestamps on a switch or network tap, outside the trading host, so the measurement does not disturb the thing measured.
FPGAs, briefly
An FPGA on the NIC can parse the feed, update a book and send an order without the packet ever reaching the CPU. Wire-to-wire times are tens to a few hundred nanoseconds. The cost is development effort (hardware description languages, long build times), limited logic, and slow iteration, so firms use FPGAs for simple, stable, latency-decisive logic (feed filtering, pre-computed responses, risk checks) and keep strategy logic in software.
Typical orders of magnitude
These are indicative ranges for well-tuned servers, quoted to set scale, not measurements and not guarantees: vendor figures and real deployments vary widely.
| Path | One-way software or wire-to-wire latency |
|---|---|
| Kernel socket stack, tuned server | a few µs to around 10 µs, with a much longer tail |
| Kernel bypass (Onload, DPDK), software | around 1 µs or below |
| ef_vi-style raw frames, minimal handler | hundreds of ns |
| FPGA wire-to-wire | tens to a few hundred ns |
| Fibre propagation | about 4.9 ns per metre |
| Serialising a 64-byte frame at 10 Gb/s | 67.2 ns including preamble and gap |
The last two rows are physics: light in glass travels at about , and a minimum Ethernet frame occupies bytes on the wire.
Worked example
the per-packet budget at line rate
A 10 Gb/s market-data link carries minimum-size 64-byte frames back to back during a burst. How many packets per second is that, and how much time does one core have per packet? Could a stack costing about 1 µs per packet keep up on one core?
Show solutionHide solution
On the wire each frame also has an 8-byte preamble and a 12-byte inter-frame gap, so it occupies bytes bits.
A stack costing about 1 µs per packet handles about packets per second on one core, roughly 15 times too slow. Packets queue in the NIC ring until it overflows and they are dropped. This is why DPDK-style designs poll in batches (one ring check returns many packets, spreading fixed costs) and why real feeds are split across many multicast groups and receive queues handled by different cores. Real feeds rarely run at line rate with minimum frames for long, but bursts at the open and on news are exactly when latency matters.
Worked example
what a burst does to latency
Messages normally arrive at 100,000 per second, but on a news event they arrive at 2,000,000 per second for 1 ms. Compare a handler that costs 1 µs per message (kernel path) with one that costs 0.2 µs (kernel bypass). What latency does the last message of the burst see?
Show solutionHide solution
The burst brings messages in 1 ms.
1 µs per message. Capacity is per second, half the arrival rate (utilisation 2). During the 1 ms the handler clears 1,000 messages, so 1,000 are queued when the last one arrives. It waits for those 1,000, about 1 ms, and is processed at about ms: about 1 ms of latency, from a handler whose cost is 1 µs. Every message in the burst sees a delay growing linearly from 0 to 1 ms.
0.2 µs per message. Capacity is per second, so utilisation in the burst is . No backlog builds; each message waits at most a little for the previous one: under 1 µs.
The per-message saving is 0.8 µs, but in the burst, when trading opportunities cluster, the difference is three orders of magnitude. Interviewers like this framing: latency under load is governed by utilisation, and kernel bypass matters most because it keeps utilisation below 1 when the feed spikes.
Knowledge check
Which costs does kernel bypass (for example ef_vi or a DPDK poll-mode driver) remove from the receive path?
Knowledge check
On a laptop, spinning on recv() with MSG_DONTWAIT gave a higher median round trip than blocking recv(). Why does busy polling still help with kernel bypass?
Knowledge check
Your strategy logs a timestamp right after recv() returns and reports its latency from that point. What does this miss?
Key takeaways
- The kernel receive path adds an interrupt, protocol processing, a scheduler wake-up and a copy; together they cost microseconds and produce a long tail. Loopback on a laptop measured about 16 µs median and over 100 µs at the 99.9th percentile.
- Kernel bypass maps NIC rings into user space: DPDK (poll-mode drivers, batches), Onload (sockets API, no code change), ef_vi (raw frames, lowest latency).
- Busy polling needs a pinned, isolated core on the NIC's NUMA node and a hot loop free of system calls, locks and allocation. Spinning on a system call is not the same thing.
- Measure with NIC hardware timestamps and PTP-synchronised captures, not with software timestamps after
recv. - At 10 Gb/s, minimum frames leave 67.2 ns per packet; under bursts, per-message cost decides whether utilisation stays below 1, and so whether latency stays in microseconds or jumps to milliseconds.
- FPGAs reach tens to hundreds of nanoseconds for simple, stable logic; strategy stays in software. Latency figures for vendor products are orders of magnitude, not guarantees.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).