Kernel tuning for latency: isolcpus, affinity, NUMA, huge pages, and what actually moves the number

Latency tuning is interference removal, not speed addition: you are taking the scheduler, the interrupts, the memory manager and the power governor off the critical path, then proving it with percentiles.

Read the briefing
About 5 min to read 7 drills

What to remember

  1. Pin the thread, the interrupt and the memory to the same NUMA node — or you have moved the problem, not fixed it. A thread on socket 0 serving a NIC whose IRQs land on socket 1 pays cross-socket latency on every packet. All three must agree.
  2. isolcpus stops the scheduler; nohz_full stops the tick; rcu_nocbs moves the callbacks. Three separate sources of interruption, three separate switches. Setting one and expecting silence is the usual mistake.
  3. Averages are marketing. Compare distributions, and quote a percentile at a load and a payload. p99.9 under 40 µs at 200k msg/s with 200-byte payloads is a claim someone can falsify. '40 microseconds' is not.
  4. Deep C-states cost microseconds to wake. Determinism beats peak clock. Governor to performance, C-states capped, and a /dev/cpu_dma_latency hold if the box must never nap.
  5. Disable transparent huge pages on latency boxes; reserve hugetlbfs pages instead. THP helps throughput but compaction stalls land in your tail. Explicit reservation gives you the TLB win without the surprise.

The big picture

Kernel tuning for latency is a discipline of subtraction. The machine is full of mechanisms that trade a microsecond of your critical path for efficiency somewhere else — the scheduler tick, interrupt coalescing, page reclaim, frequency scaling — and the work is identifying which ones touch your path, removing them, and proving the removal with a measurement that could have said no.

The mental model

Your hot thread wants a core nobody else touches, memory on that core's socket, interrupts handled next door, and a clock that never slows down. Every knob is one of those four things. If a change does not remove an interruption or a remote access, it is not a latency change.

In depth

Isolation: getting everything else off the core

isolcpus= (or, better, a cpuset/cgroup partition, which is dynamic and does not need a reboot) removes cores from the scheduler's general-purpose pool so nothing lands there unless you put it there. nohz_full= stops the periodic scheduler tick on those cores while a single task runs — worth tens of microseconds of jitter per second, and it only takes effect with one runnable task. rcu_nocbs= moves RCU callback processing off them, and irqaffinity= keeps the general IRQ load on the housekeeping cores.

None of it helps if the application then blocks, sleeps, migrates, or spawns threads that inherit the wrong affinity. Verify rather than assume: taskset -pc <pid>, /proc/<pid>/status Cpus_allowed_list, cat /proc/interrupts to see which cores are actually taking IRQs, and perf sched or a scheduler trace to catch preemptions you did not expect. cyclictest gives you the floor the kernel itself can hold.

Locality: threads, memory and NICs on the same socket

On a two-socket box a remote memory access costs roughly 1.5–2× a local one, and the interconnect is shared with every other socket-crossing access. Locality has three parts that must agree: the thread (sched_setaffinity, numactl --cpunodebind), its memory (--membind, first-touch allocation on the right core, or an allocator that is NUMA-aware), and the device — a NIC sits on one socket's PCIe root complex, and /sys/class/net/<if>/device/numa_node tells you which. Pin the NIC's receive-queue IRQs to cores on that node (/proc/irq/<n>/smp_affinity_list), and pin the thread that reads that queue to a core on the same node.

numastat -p <pid> shows how much of the process's memory sits on each node, and plain numastat shows the system-wide numa_miss and other_node counters: a hot process whose memory is mostly on the far node is reaching across the interconnect whatever your pinning script claims.

Memory: huge pages, faults and reclaim

Every page fault on the hot path is a stall you did not budget for. Pre-fault and lock what matters (mlockall, or allocate and touch at start-up), size the working set so reclaim never runs, and keep swap off. Huge pages reduce TLB pressure — a 2 MB page covers what 512 4 KB entries would — but transparent huge pages introduce khugepaged and compaction, whose stalls land squarely in your tail. The usual latency configuration is THP never or madvise, with explicitly reserved hugetlbfs pages for the processes that want them. Watch /proc/vmstat for compact_stall and thp_fault_fallback when you suspect this.

Power, clocks and the things that vary

A core in a deep C-state takes microseconds to come back; a core whose frequency just dropped runs your code slower than the benchmark did. For determinism: cpupower frequency-set -g performance, cap idle states (intel_idle.max_cstate=1 or idle=poll if you accept the power cost), or hold /dev/cpu_dma_latency open at 0 from a small daemon, which asks the kernel for the lowest-latency idle behaviour without kernel command line changes. Turbo makes peak faster and timing less predictable, which is a real trade rather than an obvious win. Also disable anything that periodically walks the whole machine: SMI-heavy BIOS settings, aggressive monitoring agents, and updatedb-style cron work on a trading host.

Proving it

A tuning change is a hypothesis. The protocol: fix the workload and the load generator (on a separate host), take a baseline of enough samples to see p99.9, change exactly one thing, re-measure, and compare distributions rather than means. Record the kernel version, the command line, the governor, the NIC firmware and driver, and the BIOS profile alongside the numbers, because those are the variables that silently change under you. If a change cannot be shown to move a percentile you care about, it is not a tuning, it is a belief — and beliefs accumulate into configurations nobody can explain two years later.

Myths and facts

Myth: More tuning is better; apply every flag from the vendor guide.

Fact: Each flag has a cost somewhere, and unmeasured flags become unexplainable configuration. Change one thing, measure, keep what earns its place.

Myth: isolcpus alone gives you a quiet core.

Fact: It removes the scheduler's general pool; the tick, RCU callbacks and IRQs still arrive unless nohz_full, rcu_nocbs and IRQ affinity are set too.

Myth: Transparent huge pages are a free win.

Fact: They help throughput and can add compaction stalls to your tail; latency configurations usually reserve huge pages explicitly instead.

Myth: Pinning the application thread is what matters.

Fact: Thread, memory and the NIC's interrupt must be on the same node. Pinning one of the three can make latency worse.

Myth: Turbo boost is always good for latency.

Fact: It raises peak clock and adds variability; where determinism matters more than peak, operators cap it deliberately.

How pros do it

  • Partition cores with cpusets (or isolcpus) plus nohz_full and rcu_nocbs, and verify with /proc/interrupts and a scheduler trace.
  • Make thread, memory and NIC-interrupt locality agree, and check numastat rather than trusting the script.
  • Disable THP, pre-fault and lock the working set, and keep swap off on latency hosts.
  • Pin the governor to performance and cap C-states; treat turbo as a deliberate trade.
  • Record kernel, driver, firmware and BIOS with every benchmark, and keep tunings in configuration management with the measurement that justified them.

Questions people ask

isolcpus or cpusets?

Cpusets, unless the box is single-purpose and never changes. A cgroup partition fences the cores the same way without a reboot, and upstream has been steering people away from isolcpus for years; say it is still common on fixed trading hosts, and that either way you add nohz_full and rcu_nocbs on top, because the partition alone does not silence the core.

How do I know which core my NIC's interrupts land on, and where should they go?

cat /proc/interrupts and watch which column moves for each queue; /proc/irq/<n>/smp_affinity_list puts it where you want. The right place is a core on the NIC's own NUMA node — /sys/class/net/<if>/device/numa_node — beside the thread that drains that queue. The caveat is irqbalance: switch it off or ban those IRQs, or it will move them back.

How many samples do I need for p99.9?

Tens of thousands as a floor, more if you want it stable release to release, and quote the count with the number. One in a thousand means a thousand samples give you one observation in the tail. Samples do not fix a closed-loop generator, though — coordinated omission gives you a confidently wrong tail however long you run.

Does idle=poll make sense?

On a dedicated trading host, often yes; on anything shared, no. It removes idle-exit latency entirely by never letting the core idle, and the price is a core burning power all day. What most fleets actually run is the gentler version — C-states capped at C1, or a /dev/cpu_dma_latency hold from a small daemon.

Is any of this useful outside trading?

Yes, and say so: validators, RPC nodes, real-time media and any path with a tail-latency SLO use the same subtraction discipline. The difference is how many of the extreme knobs earn their place, which you decide by measurement rather than by copying the trading profile.

Further reading

Drills · 7

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

You pinned a market-data thread to core 4 on socket 0. The NIC reports numa_node: 1, and its receive-queue IRQs sit on cores 2 and 3 — also socket 0. p99 got worse after the pinning. Why?

  1. The NIC is attached to socket 1 while both the IRQ handlers and the consumer thread are on socket 0, so every packet's DMA and every interrupt cross the interconnect; move the IRQs and the thread to socket 1 cores, or move the NIC. Locality must include the device: the packet lands in memory near the NIC's socket.
  2. Two IRQ cores is too many; one is always better. Queue count and IRQ spread are separate from the NUMA problem shown here.
  3. Core 4 is too low a core number; use a higher-numbered core. Core numbering has no latency meaning by itself.
  4. Pinning always hurts unless hyperthreading is disabled. Sibling threads matter, but the cross-socket path is the dominant effect here.
In short

The NIC is on socket 1 while the thread and its interrupts are on socket 0, so move the thread and the interrupts to socket 1 cores.

Why

Locality has three parts: thread, memory and device. /sys/class/net/<if>/device/numa_node tells you where the NIC lives; numastat -p confirms whether the process is reaching across. Pinning that ignores the device usually makes things worse than no pinning at all.

The common mistake

Pinning the thread and the IRQs to the same socket and calling it done. The socket that matters is the one the NIC's PCIe root complex hangs off.

Read the docs

2 Pick the strongest answer

You booted with isolcpus=8-15 and pinned the hot thread to core 10, yet a scheduler trace still shows periodic interruptions on that core. What did you miss?

  1. Nothing — isolcpus cannot be verified from user space. It is verifiable: /proc/interrupts, scheduler tracing and cyclictest all show what still lands there.
  2. A real-time scheduling policy; isolcpus does nothing without SCHED_FIFO. A real-time policy helps against other runnable tasks but does not stop the tick or RCU work.
  3. nohz_full=8-15 to stop the periodic tick on those cores and rcu_nocbs=8-15 to move RCU callbacks off them, plus IRQ affinity keeping device interrupts on the housekeeping cores. isolcpus only removes the cores from the general scheduling pool; the tick, RCU and IRQs are separate mechanisms.
  4. Hyperthreading disabled in BIOS. Sibling interference is real but is not the periodic interruption described.
In short

Add nohz_full and rcu_nocbs for those cores and keep device interrupts on the other cores; isolcpus alone does not stop the tick.

Why

Quiet cores are the sum of four settings. Even then, nohz_full only silences the tick while exactly one task is runnable on the core, so a stray kernel thread or a second application thread brings it back.

The common mistake

Reaching for SCHED_FIFO. A real-time priority beats other tasks; it does nothing about the tick, RCU work or interrupts, which are what is still landing on the core.

Read the docs

3 Answer out loud

Walk me through how you tune a bare-metal host for a latency-critical process — what you change, in what order, and how you prove each knob earned its place. Five to seven sentences.

In short

A strong answer takes a baseline first, changes one thing at a time, and keeps only the changes that move a percentile.

What a strong answer does
  • correctness: Baseline first; then core partitioning with nohz_full/rcu_nocbs, IRQ and NIC locality, memory pre-fault and THP off, governor and C-states; each verified, one change at a time.
  • measurement: Fixed-rate load from a separate host, sample counts sufficient for p99.9, distributions compared, environment recorded (kernel, driver, firmware, BIOS).
  • judgment: Names the cost of each knob, refuses unmeasured changes, and says what would make them revert one.
  • communication: Baseline → subtraction in order of expected effect → verification → configuration management, stated crisply.
Why

The rubric rewards the ordering and the refusal to keep unmeasured changes; the flag list is the least interesting part of the answer.

The common mistake

Reciting the vendor guide: every flag, no order, no measurement. An interviewer hears that as someone who copied a profile and cannot say which knobs are doing the work.

4 Read the output

Read me this. Is the process local, and if not, what do you do?

$ numastat -p 24117
Per-node process memory usage (in MBs) for PID 24117 (strategy)
                         Node 0          Node 1           Total
Huge                       0.00            0.00            0.00
Heap                    1024.31         3820.55         4844.86
Stack                      0.12            0.00            0.12
Private                   96.44          412.19          508.63
-----------------  --------------- --------------- ---------------
Total                   1120.87         4232.74         5353.61

$ taskset -pc 24117
pid 24117's current affinity list: 8-11
$ numactl --hardware | grep -E 'available|cpus'
available: 2 nodes (0-1)
node 0 cpus: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
node 1 cpus: 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
  1. The process needs huge pages — the Huge row is zero. Worth considering separately, but it does not explain the remote memory.
  2. Affinity is wrong because it spans four cores. Four cores on one node is fine; the memory placement is the problem.
  3. The process runs on node 0 cores (8-11) but 79% of its memory is on node 1, so most accesses cross the interconnect. Restart it under numactl --cpunodebind=0 --membind=0 (or bind to node 1 cores) so CPU and memory agree. Cores 8-11 are node 0; the heap is overwhelmingly on node 1.
  4. Memory is balanced across nodes, which is optimal. Interleaving is for throughput; a latency-sensitive process wants locality, not balance.
In short

The process runs on node 0 cores but most of its memory is on node 1; bind the CPU and the memory to the same node with numactl.

Why

First-touch allocation puts a page on the node of whichever core touched it first, so a process that allocates during start-up on one node and later runs elsewhere ends up exactly like this. Bind both CPU and memory, or allocate after pinning.

Read the docs

5 Find what's broken

This is a trading host as it was actually deployed. Four lines work against the latency goal — find them, and tell me which you would fix first.

# trading host build, as deployed
GRUB_CMDLINE_LINUX="isolcpus=8-15 nohz_full=8-15 rcu_nocbs=8-15"
GRUB_CMDLINE_EXTRA="intel_idle.max_cstate=6"
vm.swappiness = 10
vm.nr_hugepages = 0
transparent_hugepage = always
cpupower_governor = powersave
benchmark = "run the strategy for 60 seconds, report the mean latency"
In short

The four bad lines are deep C-states allowed, THP set to always, the powersave governor, and a benchmark that reports only the mean.

What's broken
  • Line 6: Transparent huge pages are set to always, so khugepaged and compaction can stall the hot path.
  • Line 7: The CPU governor is powersave, so cores run at reduced frequency and change frequency under load.
  • Line 8: The benchmark reports a mean over 60 seconds, which cannot see the tail the tuning exists to fix.
  • Line 3: Deep idle states are permitted, and their exit latency lands in the tail.
Why

The isolation flags (line 2) are right, swappiness 10 is harmless on a host with swap off, and nr_hugepages 0 only matters if a process wants them. The four that bite are deep C-states, THP, the governor, and — worst — a benchmark measuring the one statistic the work is not about.

Read the docs

6 Scenario: what do you do next?

A strategy's p99.9 order-entry latency doubled after a routine OS patch cycle. p50 is unchanged. The desk wants it back before tomorrow's open, and the platform team's change log lists a kernel upgrade, a NIC firmware update and a monitoring agent rollout on the same night.

Step 1. First move?

  1. Get a measurement you can trust before changing anything: replay a fixed-rate load against a canary host, confirm the regression reproduces, and record p50/p99/p99.9 so any fix can be judged. Three changes landed together; without a reproducible measurement you cannot attribute or verify.
  2. Roll back all three changes tonight. Possibly the outcome, but blind bulk rollback loses the attribution and may break something the patch fixed.
  3. Ask the venue whether their side changed. p50 unchanged with a worse tail points inward, not at the path.
  4. Re-apply the tuning script in case the patch reset it. Reasonable to check, but do it as a diff against the recorded baseline rather than by re-running a script.

Step 2. The regression reproduces. Diffing the host against the recorded baseline shows the kernel command line lost nohz_full (a new GRUB template), and the monitoring agent is running a per-second collector pinned to no core. What now?

  1. Remove the monitoring agent entirely from all trading hosts. Observability is not optional; confine it rather than delete it.
  2. Also revert the NIC firmware for good measure. Changing something you have not implicated makes the next regression harder to attribute.
  3. Roll back the kernel to the previous version. The kernel is not at fault — the boot template is; rolling back hides the real defect.
  4. Restore nohz_full and confine the agent to the housekeeping cores, then re-measure to confirm the tail returns; keep the NIC firmware, since nothing implicates it. Two identified interference sources, each removed, each verified by the same measurement.

Step 3. Systemic fix?

  1. Boot parameters and tunings in configuration management with a post-boot assertion job that fails the host out of the pool if the expected isolation is absent; agents pinned to housekeeping cores by policy; a nightly latency canary with percentile alerts. Turns 'someone changed a template' into a detectable, blocking condition, and gives the tail its own regression alarm.
  2. Freeze OS patching on trading hosts. Trades one risk for a worse one; make patching safe instead.
  3. Write a runbook step to check the kernel command line after patching. A manual check that will be skipped exactly when the night is busy.
In short

First reproduce the slow tail with a fixed-rate test on one host; then restore nohz_full, move the agent off the isolated cores, and add a boot-time check.

Why

Interviewers use this to see whether you measure before you act, attribute changes rather than bulk-reverting, and convert a one-off into an assertion. The detail that lands best is a post-boot check that fails the host out of the pool: tuning you cannot verify automatically will drift.

Read the docs

7 Quick recall

A latency host shows occasional multi-millisecond stalls and compact_stall is climbing in /proc/vmstat. What do you switch off?

In short

Transparent huge pages, also called THP.

Accepted

transparent huge pages · THP · transparent hugepages

Why

Transparent huge pages: the TLB benefit is real, but khugepaged and compaction add stalls, so latency configs use explicitly reserved huge pages instead.

Next lesson NIC path and time: kernel bypass, hardware timestamping, PTP, and why time sync is a correctness problem
Drill · Kernel tuning for latency
0:00

Loading…