Oct 25, 2026
Getting WireGuard DDS round-trips to adhere to a one-millisecond deadline
1. The Setup
Let us begin with two machines and a modestly challenging obligation. Every millisecond, the first machine publishes a message with a 4 KiB application body. The second receives it and sends an echo. We require the echo to return within one millisecond of the intended publication time. A single late message over a 30 min. time-frame counts as a failure.
The machines are physical x86-64 hosts running PREEMPT_RT Linux, connected by a 1 Gb/s wired LAN. Tin DDS C++ supplies reliable delivery with history depth 256. The encrypted path is a dedicated WireGuard tunnel with MTU 1420.
The setup uses the following thread and CPU placement.
| Responsibility | Placement and policy |
|---|---|
| Application progress | CPU 16, FIFO priority 20; 100 µs polling budget, then a requested 10 µs blocking pause |
| DDS receive service | CPU 17, FIFO priority 30 |
| Capture and Tin Box | CPU 18, ordinary scheduling |
| NIC interrupts | CPU 19 |
| WireGuard NAPI receive delivery | CPU 19, FIFO priority 40 |
| Selected RCU, timer, IRQ-work and backlog-NAPI threads | FIFO priority 40 on CPUs 16–19 |
| Benchmark control and monitoring | CPU 0 |
| WireGuard per-peer transmit worker | Discover its CPU on the live tunnel; reserve its core and SMT siblings |
| CPU idle policy | Temporary 1 µs CPU latency QoS request |
The CPU numbers describe this experiment, not a portable recipe. In particular, the transmit-worker CPU must be discovered again after tunnel or peer recreation. A remembered affinity can be quite precise and quite wrong.
We will interleave the explanation with a small program for reading the retained diagnostic summaries. The Python fragments below, in order, form the executable companion. Its input is the anonymized diagnostic data. It checks the summaries' consistency; it does not repeat the independent payload verification against the MCAP recordings. C++ fragments are excerpts from the benchmark implementation, rather than parts of that Python program.
2. The Measurements
For message i, let sᵢ be its scheduled publication time, pᵢ its actual production time, and eᵢ the time its echo reaches the publishing application. We measure:
Lᵢ = eᵢ − sᵢ
= (eᵢ − pᵢ) + (pᵢ − sᵢ)
The first term is the observed round trip after production; the second is production lateness. Both belong in the deadline calculation. Otherwise a publisher could begin half a millisecond late and quietly ask the network to be judged against a fresh deadline.
All three timestamps use the publisher's monotonic clock. No cross-host clock synchronization is needed for this calculation. It measures the full round trip, including the subscriber's processing; it is neither a measured one-way latency nor RTT divided by two.
Our little program first names the units. A nanosecond count is a convenient integer; it becomes less convenient when a reader has to count its zeroes repeatedly.
import argparse
import json
from pathlib import Path
DEADLINE_NS = 1_000_000
NS_PER_MS = 1_000_000
def milliseconds(nanoseconds):
return nanoseconds / NS_PER_MS
There are two questions to answer for a run. Did every expected message and echo survive verification? If so, did every measured round trip meet the deadline? A percentile cannot answer the second question, and a latency array containing only the messages that arrived cannot answer the first.
3. Keep the observations: Tin Box
Tin Box gives us a record against which to ask those questions. An owned recorder process runs on each host, separately from the application and receive threads. The endpoints send original payloads, message IDs and endpoint timestamps through a bounded binary capture stream into Tin Box MCAP.
The division of responsibility is deliberate. The endpoint knows when an event occurred. Tin Box owns storage and segment rotation. The recorder's ingest time is not substituted for the endpoint's event time.
Application-side capture admission uses preallocated queues and does not wait for recorder capacity. That choice requires an explicit failure case: if a queue fills, rejected records are counted and the recording fails validation. A recorder that silently discarded an inconvenient observation would make the experiment easier to pass and harder to believe.
After the run, verification reconciles both endpoints' captures with the benchmark's timing arrays. It checks IDs, ordering, payloads and original timestamps. A complete recording may show a late message; an incomplete recording cannot establish complete delivery. Capture is at the application boundary, after tunnel decryption. WireGuard encryption on the network does not make the resulting MCAP encrypted storage.
Now we can write the part of our companion that interprets a verified summary. The counts are indexed by receiving endpoint and originating endpoint: endpoint 0 receives echoes from endpoint 1, and endpoint 1 receives publications from endpoint 0.
def inspect_summary(run, rate_hz):
expected = run["seconds"] * rate_hz
integrity = run["integrity"]
counts = integrity["counts"]
timing = run["scheduled_rtt_ns"]
delivery_complete = (
integrity["status"] == "pass"
and integrity["full_payload_verified"]
and integrity["exact_timings_verified"]
and integrity["scheduled_timings_verified"]
and counts["0"]["1"] == expected
and counts["1"]["0"] == expected
and timing["samples"] == expected
)
if not delivery_complete:
return "UNQUALIFIED"
within_deadline = (
run["over_1ms"] == 0
and timing["max"] <= DEADLINE_NS
)
return "PASS" if within_deadline else "DEADLINE FAIL"
Notice the order. We establish completeness before considering speed. The program relies on the recorded verifier result for completeness; recomputing that result requires the original captures. This is a summary reader, not an alternative verifier.
4. A thread can be too eager
The initial main loop repeatedly polled DDS on a CPU assigned to a FIFO thread. The receive service had its own CPU and higher FIFO priority. This seemed a reasonable way to keep application work moving.
During a failing long run, however, the receiver reported RCU stalls involving WireGuard decryption workers. Several waited on a lock, while another was runnable on the same CPU as the FIFO application thread. The evidence was consistent with a dependency being starved by the application that needed it.
The threads formed a dependency chain: the application submitted work to WireGuard; kernel workers encrypted and transmitted it; workers on the receiving host decrypted it; NAPI delivered it to the socket; the DDS receive service made it available to the application. The echo traversed the chain again in the opposite direction. Giving the application a high priority accelerated only the portions it could execute itself. While it polled for a reply, a lower-priority worker on the same CPU could be waiting to produce that reply.
We had optimized the application's opportunity to run without first accounting for all the work on which its progress depended. Linux's FIFO scheduling rules make the difficulty concrete: calling sched_yield() does not give an ordinary-priority worker a service budget beneath a continuously runnable FIFO task.
The benchmark therefore gained a small polling budget. These are the relevant members of broadcast_poll_budget in tools/broadcast_poll_budget.h; the class uses std::chrono::steady_clock and owns the next pause time, next_.
static constexpr auto budget = std::chrono::microseconds{100};
static constexpr auto pause = std::chrono::microseconds{10};
[[nodiscard]] bool due(clock::time_point now) const noexcept {
return enabled_ && now >= next_;
}
void resumed(clock::time_point now) noexcept {
next_ = now + budget;
}
void pause_if_due() {
if (!due(clock::now())) return;
std::this_thread::sleep_for(pause);
resumed(clock::now());
}
The loop calls pause_if_due() at each iteration, including retries. The significant operation is the blocking sleep. It permits lower-priority work to run. There is also a small but useful detail in resumed: the next budget begins at the actual wakeup time. A delayed wakeup does not create a debt of missed pauses that the loop must immediately repay.
This is a scheduling opportunity, not a timing proof. An individual DDS operation may exceed the polling budget, and a requested 10 µs sleep may take longer. Every such delay remains in Lᵢ. The separate receive service already blocks on socket readiness; this change concerns the continuously runnable application loop. We retained FIFO scheduling rather than introducing deadline scheduling.
5. Follow the packet, not merely the worker
The next short runs delivered every message, but some round trips still exceeded one millisecond. We turned to eBPF workqueue and scheduler tracepoints, packet captures on both the tunnel and physical interfaces, and the application timestamps retained by Tin Box.
At first, a workqueue event appeared to offer a pleasantly direct explanation. A crypto worker waited a long time to run; surely its packet had waited just as long. But that conclusion gives the worker too much individuality. WireGuard's crypto workers share a packet queue. While one worker is awaiting CPU time, another may already have consumed the packet we are interested in.
We therefore had to ask a more careful question: did the delayed worker coincide with a packet that was actually delayed? Matching workqueue events with packet captures and application timestamps separated a late worker from a late packet. The distinction matters whenever several workers can perform the same pending work.
One correlated trace supplied the following sequence. Times are relative to the subscriber application's receipt of the message:
| Observation | Approximate elapsed time |
|---|---|
| Echo submitted to the tunnel | 10 µs |
| First encrypted packet reaches physical egress | 1,425 µs |
Within that interval, the WireGuard transmit worker spent roughly 1.40 ms queued. Most of the delay had accumulated before the first encrypted packet was sent over the physical network.
A later scheduler trace supplied the missing explanation for another long wait: a transmit worker waited 1.109 ms while a desktop application occupied its selected CPU at the same ordinary scheduling priority. Our Python and ps monitoring processes also appeared among the competitors. Measuring the system had added work to the system.
WireGuard's Linux implementation uses per-CPU crypto workqueues and selects online CPUs; the per-peer transmit worker also has a selected CPU. Excluding application CPUs from the global unbound workqueue mask does not constrain all of these per-CPU queues. The distinction is visible in Linux v7.0's workqueue allocation and queue selection.
Our policy discovers the live tunnel's transmit-worker CPU, reserves its core and SMT siblings, and moves benchmark control and monitoring to CPU 0. A cgroup partition keeps ordinary desktop work off the reserved cores. The configuration is bound to the interface instance and must be rediscovered after interface or peer recreation; peer configuration must remain unchanged between discovery and measurement.
This policy does not pin every parallel crypto worker or change the workers' scheduling class. It removes a measured source of contention from the selected transmit-worker cores. The diagnostic traces themselves add overhead, so their timings are kept separate from the untraced validation results.
6. An idle processor is not immediately available
A worker need not lose a scheduling contest to start late. Its CPU may be asleep.
We observed workers being woken promptly, followed by delays around 200 µs before execution. Enabled idle states on these hosts advertised exit latencies reaching hundreds of microseconds; one advertised 1,048 µs. A one-millisecond experiment has little room for such a wakeup.
We tested a temporary 1 µs CPU latency QoS request through /dev/cpu_dma_latency. The mechanism is scoped by an open file descriptor: write the requested latency, retain the descriptor for the experiment, and close it afterward. The Linux PM QoS documentation describes this lifetime and the signed 32-bit request value.
The request constrains idle-state selection. It does not promise that a thread will execute within one microsecond. Increased power consumption and potentially heat are part of the tradeoff; we did not measure them in this experiment. Our harness releases the request on owner-pipe closure or timeout and restores its saved scheduling, IRQ and workqueue settings.
Two consecutive 20-second runs used the same live tunnel and executable:
| Idle policy | Samples | p99 scheduled RTT | Maximum | Over 1 ms |
|---|---|---|---|---|
| Default | 20,000 | 0.816 ms | 1.074 ms | 2 |
| Shallow idle request | 20,000 | 0.432 ms | 1.396 ms | 1 |
Figure 1. The idle request improved p99 in this pair of observations. The maximum still exceeded the deadline. These short runs are separate from the 30-minute measurements below.
The second row is instructive. The p99 improved substantially, yet the maximum became worse. Every message was verified in both runs, but neither met the all-samples deadline. We had reduced one source of delay while leaving another source of contention. These short consecutive observations were not randomized trials that isolated a causal effect size.
7. The WireGuard receive thread
We needed to observe the work between decryption and application delivery. A 15-minute diagnostic run recorded packets on both hosts and traced individual WireGuard packets by their receiver index and counter. For each packet, we recorded entry into the receive path, completion of decryption, and the call that delivers the decrypted data. This gave us a packet's waiting time without assuming that a queued crypto worker still had work to do.
That run verified all 900,000 messages and echoes and reproduced seven deadline misses. During a three-echo burst, packets spent up to 2.57 ms waiting after decryption; the longest round trip was 3.099 ms. A later echo took 1.339 ms. Its scheduler trace showed the receive-delivery thread runnable but off CPU for 944 µs.
The thread was napi/wgdds-0. Linux's WireGuard receive path passes decrypted packets through NAPI before delivering them. On these hosts, that work runs in a dedicated kernel thread. Our scheduling policy had raised the priority of backlog_napi threads and reserved the transmit worker's core. It had omitted the tunnel's own NAPI thread, which remained at ordinary priority among desktop and control-plane work.
Five of the seven diagnostic misses coincided with measured post-decryption waits. Packet-specific probes were attached after the first two misses; their captures locate the delay within the receiving host's tunnel path but do not separate decryption from subsequent delivery.
The policy now includes the tunnel's NAPI threads. Its essential operations are:
saved['_napi'] = snapshot_napi(tunnel)
move_napi(saved['_napi'], group)
napi = apply_napi(saved['_napi'])
The snapshot retains each thread's identity, cgroup membership, CPU affinity, scheduling class and priority. Moving the thread into the benchmark cpuset permits it to use reserved CPU 19. The policy then pins it there at FIFO priority 40, alongside the network receive work and above the application threads. A host check caught this ordering requirement: applying affinity while the thread still belonged to the root cpuset failed because that cpuset excluded the isolated CPU.
The helper reads back the applied affinity and priority. The benchmark checks them throughout the run and again at completion. Cleanup returns the thread to its original cgroup, removes the temporary partition, and restores the saved scheduling settings and affinity. Thread identity includes its start time, so cleanup cannot mistake a reused PID for the original receiver.
The 30-minute NAPI follow-up verified 1.8 million messages and echoes. Its p99 scheduled round trip was 0.484 ms, and its maximum was 1.327 ms. 3 echoes exceeded 1 ms, so the run failed the deadline requirement. It used the same DDS executable, 4 KiB bodies, 1 kHz publication rate and Tin Box recording, with diagnostic tracing disabled. Both endpoints verified the NAPI receiver on CPU 19 at FIFO priority 40.
Figure 2. The latest run verified 1.8 million messages and echoes. Each bar is a recorded summary statistic; three echoes exceeded the deadline.
The changes addressed different parts of the dependency chain:
| Change | Interaction it addressed | What the observations establish |
|---|---|---|
| Application FIFO 20 and receive service FIFO 30 on separate CPUs | Gives application and socket processing precedence over ordinary tasks on their CPUs | This alone left kernel dependencies exposed; the continuously runnable application could starve ordinary crypto workers. |
| Block briefly after each polling budget | Lets lower-priority dependencies execute on the application's CPU | Subsequent runs completed delivery without the earlier RCU stalls; there is no isolated latency improvement measured for this change alone. |
| Reserve the live transmit worker's core and SMT siblings; move monitoring to CPU 0 | Removes desktop and observer competition from that worker's core | Tracing had measured a 1.109 ms runnable wait behind desktop work. The combined policy passed a short run but still missed deadlines over 30 minutes. |
| Request shallow idle | Reduces exposure to slow CPU wakeups | The paired short runs reduced p99 from 0.816 to 0.432 ms, but both had late echoes. |
| Move tunnel NAPI into the reserved cpuset, pin it to CPU 19 and apply FIFO 40 | Gives decrypted-packet delivery CPU access and precedence over ordinary work | The run recorded 3 misses and a 1.327 ms maximum. The causes of these misses remain unresolved. |
Higher FIFO numbers give precedence when threads compete on the same CPU. Separate CPU placement allows stages to make progress concurrently. Here the NAPI change combined placement, isolation and priority, so these runs cannot assign the improvement to priority alone. Repeated controlled trials would be needed to estimate the effect of each setting separately.
8. Interpreting the measurements
With cooperative polling, transmit-worker core isolation, monitoring affinity, shallow idle and NAPI placement applied, the 30-minute run verified 1.8 million messages and echoes. Three scheduled round trips exceeded one millisecond. The run therefore failed the deadline requirement.
| p50 | p99 | p99.9 | Maximum |
|---|---|---|---|
| 0.328 ms | 0.484 ms | 0.516 ms | 1.327 ms |
The last piece of the companion program prints one row per experiment. We include the maximum because our deadline applies to every echo; the p99 alone cannot tell us whether the run passed.
def main():
parser = argparse.ArgumentParser(description="Read verified DDS diagnostic summaries")
parser.add_argument(
"summary", nargs="?", type=Path,
default=Path(__file__).with_name("wireguard-diagnostics.json"),
)
document = json.loads(parser.parse_args().summary.read_text())
rate_hz = document["rate_hz"]
for run in document["runs"]:
timing = run["scheduled_rtt_ns"]
print(
f'{run["case"]}: {inspect_summary(run, rate_hz)}; '
f'{run["seconds"]} s; '
f'p99={milliseconds(timing["p99"]):.3f} ms; '
f'max={milliseconds(timing["max"]):.3f} ms; '
f'over 1 ms={run["over_1ms"]}'
)
if __name__ == "__main__":
main()
Save the companion beside the diagnostic JSON and run it with Python 3, or pass the JSON path explicitly. The two 20-second diagnostic runs fail the deadline check. The latest 30-minute run fails the deadline check.
All messages arrived with verified payloads and timestamps. Delivery was complete; timing did not meet the requirement. The latest run reached 1.327 ms with three late echoes. The application captures alone do not establish the kernel cause of each late echo. Other payload sizes, fanout, background loads and failure scenarios require their own measurements.
Earlier plain and DDS Security cohorts used different executables and recording or scheduling settings. Their timing differences from this WireGuard experiment do not isolate encryption overhead; that comparison requires matched conditions. The benchmark page keeps the setup and measurement qualifications beside the results.
We began by assigning a deadline to a message and priorities to two application threads. Following the message forced us to enlarge the description of the program: kernel workers, interrupt handling, idle-state transitions, and even the recorder's observers all participated. The useful unit of reasoning was the chain of work required to deliver the echo. Its collaborators needed CPU time as surely as the application did.
9. A packet waiting for attention
The next investigation began with a smaller message over plain UDP. On October 26, we sent 4 bytes of application data with an 8-byte sequence ID between two physical x86-64 PREEMPT_RT hosts on a 1 Gb/s wired LAN. Each request waited for its echo before the next request was sent. We excluded 500 warmup exchanges and retained every subsequent round-trip sample. Application progress ran on CPU 16 at FIFO priority 20, with the network IRQ on CPU 19. Kernel tracing remained enabled throughout the comparisons.
This changes the question slightly. The earlier experiment assigned a publication time every millisecond and charged a late start against the deadline. Here, requests were unpaced: the measurement begins with the request and ends with its echo. The smaller workload let us examine receive progress repeatedly, while tracing the packets responsible for the occasional long wait.
Some requests had already reached the receiving NIC's DMA ring but had not advanced into the kernel's packet-processing path. Once receive processing resumed, the application produced its echo within microseconds. Raising the application's priority could do little for a packet that had not yet become available to it.
We tried a socket-level intervention. A diagnostic interposer set SO_BUSY_POLL to 50 µs on the UDP sockets in both processes, leaving the DDS executable unchanged. This gives a receive operation an opportunity to poll the kernel's receive path for incoming work. The 50 µs value is a polling budget; a ready packet need not wait for that interval to expire. This mechanism acts at a different point from the application loop's 100 µs cooperative polling budget described earlier.
First we ran a normal-receive, busy-poll, normal-receive sequence, measuring one million exchanges in each case:
| Receive mode, in run order | p50 RTT | p99 RTT | Maximum RTT | Above 1 ms |
|---|---|---|---|---|
| Normal receive, before | 0.101 ms | 0.134 ms | 101.318 ms | 6 |
| Socket busy polling | 0.065 ms | 0.075 ms | 0.325 ms | 0 |
| Normal receive, after | 0.101 ms | 0.135 ms | 0.301 ms | 0 |
The final row deserves as much attention as the first. Removing busy polling did not immediately bring back the long waits. The fault was intermittent, and a million clean exchanges could occur under normal receive. The median and p99 shifted with the setting in this sequence; the absence of rare outliers was less decisive.
For the next pair, we kept a small background stream running in the request direction: one UDP datagram with a 24-byte body every 10 ms. A separate socket drained these datagrams without replying. Both benchmark runs used the same ports, binaries, scheduling and tracing, and the background sender remained active throughout. Each run measured 500,000 echoes.
| Receive mode | p50 RTT | p99 RTT | p99.9 RTT | Maximum RTT | Above 1 ms |
|---|---|---|---|---|---|
| Normal receive | 0.101 ms | 0.134 ms | 0.165 ms | 10.237 ms | 45 |
| Socket busy polling | 0.065 ms | 0.075 ms | 0.082 ms | 0.351 ms | 0 |
Figure 3. Plain UDP, 4-byte application payload plus an 8-byte sequence ID. The left panel shows the controlled background-traffic pair; the right shows the three sequential million-exchange controls. The vertical scale is logarithmic. Every measured message arrived in all five runs, with no duplicates or rejected writes.
In the normal-receive background run, tracing found data waiting in the receive ring during all 45 late echoes. In 43 of those cases, the ring drained within 50 µs of a background packet's kernel capture. That timing is consistent with fresh traffic prompting receive progress for an earlier packet. With socket busy polling enabled, the corresponding run recorded no prolonged pending-ring observations and no echo above one millisecond.
These observations narrow the problem to receive notification and progress. They do not yet identify the precise NIC, interrupt or driver transition responsible for leaving work pending. Busy polling supplied another opportunity to drain the ring, and the measured long waits disappeared in that run. The underlying notification fault remains under investigation.
Polling also spends CPU time looking for work. We have not quantified that cost in these comparisons, and the setting remains a diagnostic intervention rather than an integrated runtime default. These short C++ plain-UDP runs leave a further experiment to perform: repeat the 30-minute scheduled workload with busy polling, then measure larger payloads, Rust, DDS Security and WireGuard under matching conditions. The three late WireGuard echoes reported above remain part of that earlier result.
The benchmark page includes these comparisons, with exact statistics and method and a CSV download. The statistics were recomputed from the retained endpoint RTT arrays; hashes identify those source captures. This follow-up uses those arrays and kernel traces, separately from the Tin Box recording and companion program used for the earlier WireGuard experiment.