Taming the host
The scan-to-divert hot path run against a reproducible background noise load inside a throwaway KVM guest, measured on a stock boot against CPU isolation, pinning, SCHED_FIFO scheduling, and memory locking applied individually and combined, alongside a cyclictest before/after of the guest's own scheduling latency.
Learning objectives
By the end of this chapter you can:
- Name the four OS-level sources of jitter on a latency-critical thread: timer-driven scheduler preemption, context switches from other runnable tasks, IRQs, and demand-paging page faults.
- Match each source to the technique that removes it: CPU isolation to
clear a core of other work, CPU pinning to keep the hot path on that
core,
SCHED_FIFOreal-time scheduling so nothing preempts it, and memory locking so no page fault stalls it. - Read a tuning wrapper that reports
appliedornot applied, with a reasoninstead of throwing, aborting, or silently doing nothing. - Explain why this chapter’s measurements run inside a disposable KVM guest instead of the development host, and what that guest boundary costs the magnitudes it produces.
- Read a cyclictest before/after table and say what it measures that the hot path’s own scan-to-divert distribution cannot.
Diagram
Why this matters
Every chapter from “Zero-copy data layout” through “Asynchronous processing” measured on the same unprivileged development host, no pinning, no isolation, powersave governor, because the technique each one taught lived entirely in userspace: a layout change, a lock removed, a write moved off the hot path. None of them asked the host for anything.
This chapter asks the host directly. However well the scan-to-divert decision is written, it still runs as one thread among many on a kernel that is free to preempt it, move it, interrupt it, or stall it on a page fault, and a general-purpose scheduler has no idea that one particular thread’s lateness has a physical deadline attached. Fixing that is not a code change to the hot path at all; it is a set of host-level guarantees requested around it. This guide never makes those changes to the machine it is written on, for exactly this reason: isolating a core, raising a thread to real-time priority, and locking memory are privileged, system-wide changes. Everything in this chapter instead runs inside a disposable KVM guest built for nothing else.
Where the jitter comes from, and what removes it
A thread waiting to sense, decide, and act on one parcel can lose time to four distinct interruptions, each with its own fix.
Timer-driven preemption. The kernel’s periodic scheduling-clock tick
is what lets it reconsider, on a fixed cadence, whether some other
runnable task should run instead. A core with nohz_full set stops that
tick once only one task is runnable on it, so the scheduler no longer has
a clock-driven reason to interrupt a thread that has the core to itself.
Context switches from other runnable tasks. Ordinarily any core can
run any task the load balancer assigns it. isolcpus removes a core from
that general scheduling domain entirely, so the balancer stops placing
anything else there in the first place; a thread pinned to an isolated
core is not fighting the balancer for the core, it is the only thing the
balancer considers eligible to run there.
IRQs. Hardware interrupts land on whichever core the kernel’s IRQ
affinity happens to route them to, and a network card or a timer
interrupt firing on the hot path’s core is a jitter source the hot path’s
own code never sees. Isolating a core is what makes that core an unusual
destination for interrupt routing in the first place; this chapter’s lab
targets the thread-level techniques, isolation, pinning, SCHED_FIFO, and
memory locking, and leaves IRQ affinity itself named rather than tuned
further.
Demand paging. The first touch of a page the kernel has not yet
backed with physical memory takes a page fault, a trap into the kernel
that a latency-critical loop cannot afford mid-iteration. mlockall locks
a process’s current and future pages into physical memory so the kernel
can never reclaim them, and prefaulting, touching every page once before
the measured loop starts, forces the first-touch cost to happen during
setup instead of during a scan-to-divert pass.
Four sources, four fixes: isolation clears the core, pinning keeps the
thread on it, SCHED_FIFO keeps anything else from preempting it once
it is there, and memory locking keeps a page fault from stalling it
regardless of which core it runs on.
How the code works
The tuning wrappers. examples/10-taming-the-host/cpp/include/ch10/tuning.hpp
gives every host-level request the same shape, a status instead of an
exception:
struct TuningResult {
bool applied = false;
std::string detail; // "ok", or the syscall + reason
};
[[nodiscard]] TuningResult apply_cpu_affinity(std::span<const int> cpus); // #A
[[nodiscard]] TuningResult apply_realtime_scheduling(int priority); // #B
[[nodiscard]] TuningResult apply_memory_locking(std::size_t prefault_bytes); // #C
#A apply_cpu_affinity wraps pthread_setaffinity_np. An empty CPU
list is a deliberate, successful no-op, "not applied: no CPUs
requested", not an error: the caller asked for no pinning, and the
wrapper says so rather than guessing. #B apply_realtime_scheduling
calls sched_setscheduler(0, SCHED_FIFO, ¶m) directly; without
CAP_SYS_NICE or root it comes back EPERM, and the wrapper turns that
into a detail string naming the syscall and the reason instead of
leaving the thread’s scheduling class in doubt. #C
apply_memory_locking calls mlockall(MCL_CURRENT | MCL_FUTURE) and then
prefaults the requested byte count regardless of whether the lock itself
succeeded, one write per page, so the touch always happens even when the
lock is denied; the detail string says which of the two actually took
effect. Every wrapper degrades to a labelled “not applied” on this book’s
own unprivileged development host, which is the expected, testable result
there; the guest run inside lowlat-* is the only place these are
expected to read applied=1.
The lane runner. ch10::Lane names five runtime-selectable
combinations, untuned, pin, rt, mlock, and all-tamed, and
run_jitter_trial (jitter_trial.cpp) decides what each lane asks for
before running it:
NoiseLoad noise(noise_config);
noise.start(); // #A
HotPath hot_path;
result.tuning_status = apply_lane_tuning(lane, config); // #B
for (std::size_t i = 0; i < config.iteration_count; ++i) {
result.recorder.record(hot_path.run_iteration()); // #C
}
#A The background noise load starts first, a fixed number of
std::jthread workers churning cache and memory-bus traffic on whatever
CPUs are not reserved for the hot path, the same jitter source every lane
runs against regardless of what that lane tunes. #B Tuning is applied
last, after every allocation this trial needs: a successful
mlockall(MCL_FUTURE) locks every later allocation against
RLIMIT_MEMLOCK, so applying it before the noise load’s own thread
stacks exist would risk that startup failing instead of this lane
degrading the way tuning.hpp intends. #C The measured loop itself
calls hot_path.run_iteration() in a tight loop with no expected_interval:
back-to-back iterations have no fixed schedule to fall behind, so there is
no coordinated-omission correction to apply here, the same reasoning
“The running example and the harness” used for the baseline run before
that correction existed.
Reusing the scan-to-divert probe, measured as a burst. ch10::HotPath
is not a new workload; it drives the frozen line simulator’s single-parcel
pass through the same ScanToDivertProbe interface “The running example
and the harness” measures its baseline against. What differs here is the
unit of measurement. A single pass is sub-microsecond, far shorter than a
scheduler tick, so host jitter almost never lands inside one and a per-pass
number stays flat no matter what tuning is applied. So run_iteration()
times the wall-clock span to clear a burst of a thousand passes back to
back. A burst is long enough, hundreds of microseconds, that a timer tick,
an IRQ, or a context switch can land inside the measured window, which is
where host taming shows. A burst is also the realistic unit on a sortation
line: parcels arrive in bursts, not one at a time. What changes in this
chapter is never the work; it is only what the host is asked to guarantee
around the burst while it runs.
Measure
These numbers are VM-shaped. They show the method and the direction of each taming technique as a before/after inside one KVM guest; the magnitudes are not comparable to bare metal or to a tuned host, because the guest cannot isolate its vCPU threads from the host scheduler.
demo.sh tune isolates one vCPU (isolcpus, nohz_full, rcu_nocbs,
preempt=full)
and reboots; demo.sh after then runs every lane in one pass on that boot,
as sudo, each sample timing a burst of a thousand scan-to-divert passes.
The untuned lane requests no pinning, so the scheduler leaves its burst on
the shared vCPU alongside the two background noise workers; pin and
all-tamed pin their burst to the isolated vCPU; rt raises it to
SCHED_FIFO; mlock locks its memory. All values are microseconds.
| Lane | p50 | p99 | p99.9 |
|---|---|---|---|
| untuned (shares the noise-loaded vCPU) | 5399 | 8477 | 11905 |
| pin (isolated vCPU) | 1391 | 1526 | 4195 |
| rt (SCHED_FIFO) | 1389 | 1488 | 1880 |
| mlock | 1394 | 2377 | 4247 |
| all-tamed | 1394 | 1904 | 4250 |
The untuned burst runs 5399 microseconds at the median and stretches to
11905 at p99.9, because it shares one vCPU with two noise workers and waits
its turn among them. Giving the burst a core to itself, whether by pinning
it to the isolated vCPU or by raising it to SCHED_FIFO so nothing at a
lower priority preempts it, drops the median to about 1390, near a fourth
of untuned. The rt lane holds the tightest tail, 1880 at p99.9, roughly a
sixth of untuned’s, because preemption is what this burst was actually
losing time to and SCHED_FIFO addresses it head on. mlock alone matches
the median but not the tail: it removes page-fault stalls, which were not
this workload’s bottleneck. At p99.9 only the real-time lane’s tail pulls
clearly ahead, about two milliseconds below the other tamed lanes, which
sit within tens of microseconds of each other, a spread around the
resolution of twenty samples at that quantile, so
the result to read is the shared roughly fourfold median drop and the
collapse of the untuned tail, not the fine ordering among the tamed lanes.
cyclictest measures the guest’s own scheduling latency directly,
independent of this chapter’s hot path, the standard instrument the
realtime Linux community built for exactly this question. The before run is
unaffined on the stock boot; the after run is pinned to the isolated vCPU
with --policy=fifo:
| Run | p50 | p99 | p99.9 | max |
|---|---|---|---|---|
| before (stock boot, unaffined) | 5 | 866 | 2796 | 5481 |
| after (isolated vCPU, SCHED_FIFO) | 19 | 487 | 2798 | 4630 |
Isolating the vCPU pulls cyclictest’s p99 from 866 microseconds to 487 and its max from 5481 to 4630. The deep tail barely moves, though: p99.9 holds near 2797 either way, and the median rises from 5 to 19. Inside a VM the guest cannot isolate its own vCPU threads from the host’s scheduler, so the far tail is set by the host, not by anything the guest does to itself. That is the ceiling the opening caveat names, visible in one number: the method and its direction are real, the magnitude is VM-shaped.
Every number above comes from Fedora Cloud’s own stock kernel, not a
swapped-in real-time one: isolcpus and nohz_full are boot parameters a
stock kernel already understands, and SCHED_FIFO and mlockall are
syscalls a stock kernel already answers once the caller holds
CAP_SYS_NICE or CAP_IPC_LOCK. Fedora’s stock kernel already boots with
dynamic preemption set to full, the closest a non-real-time kernel gets to
preempting itself promptly on its own. A full PREEMPT_RT kernel, which
replaces most spinlocks with preemptible mutexes and moves interrupt
handling into schedulable threads, is the further step past what this
chapter measures; tune-vm.sh attempts one opportunistically through
Fedora’s @kernel-vanilla/stable COPR, since Fedora ships no kernel-rt
package in its own base or updates repositories.
Trade-offs
None of this chapter’s fixes is free, and every one of them is a cost paid somewhere else on the box.
Isolating a core removes it from the pool of CPUs the kernel can schedule
general work onto; a host with one core isolated for a hot path has one
fewer core for everything else it still needs to run. SCHED_FIFO is a
sharper version of the same trade: a real-time thread preempts anything
at a lower priority and is never time-sliced away on its own, so a hot
path that misbehaves, an unbounded loop, a wait on something that never
arrives, can starve every other thread on that priority level or below
it; a deployment that raises a thread to SCHED_FIFO needs a watchdog or
some other bound on how long it is allowed to run, not just the priority
change itself. Memory locking pins physical pages against reclaim, which
is a capacity cost measured in bytes a host permanently gives up to one
process, not a cost that shows up in a latency number at all.
All four techniques are host or VM-level configuration, not something a
portable service can assume about wherever it happens to run next. A
service tuned this way on one box carries none of that tuning with it to
a different box, a different VM flavor, or a container scheduler that has
never heard of isolcpus; the tuning lives with the host, and a service
that depends on it has to ask for it again, explicitly, everywhere it is
deployed.
What you learned
- A latency-critical thread loses time to four distinct host sources: timer-driven preemption, context switches from other runnable tasks, IRQs, and page faults, each with its own named fix.
- CPU isolation clears a core of other scheduled work; pinning keeps a
thread on that core;
SCHED_FIFOkeeps anything else from preempting it once it is there; memory locking keeps a page fault from stalling it regardless of which core it runs on. - Every tuning wrapper in this chapter reports
appliedornot applied, with a reason, never an exception and never a silent no-op, so a run on an unprivileged host degrades in a way the report still tells the truth about. - This chapter’s numbers come from a disposable KVM guest, not the development host and not bare metal; the guest’s own scheduler sits between every vCPU and the real CPU underneath it, which is why the magnitudes here do not travel past this one guest.
cyclictestmeasures the host’s own scheduling latency directly, independent of any application workload, the same before/after shape this chapter’s own hot path measures for one specific thread.
The next step in this guide zooms out: a catalog mapping every pattern measured so far to its own scan-to-divert budget line, when to reach for it, host or VM, and its measured effect, not a new technique of its own.
For deeper coverage
- Pekka Enberg, Latency: Reduce Delay in Software Systems (Manning, 2025): this guide’s reference work for chapter arc and coverage; see the bibliography.
- “No-op Scheduling-Clock Interrupts” /
nohz_full(kernel.org,Documentation/timers/no_hz.rst): the kernel’s own explanation of what isolating a CPU’s timer tick removes, and what it still cannot remove on its own. - “cyclictest” (Linux Foundation Real-Time wiki, wiki.linuxfoundation.org/realtime): the tool and the before/after measurement methodology this chapter’s guest boot comparison follows, from the realtime Linux community that built it.