Systems Performance Analysis & Tuning Questions
Deep, tool-driven diagnosis of a slow host or service once first-pass resource readings point somewhere: sampling with perf and reading flame graphs, continuous low-overhead profiling of production hosts, tracing system calls and library calls with strace and ltrace and their overhead, kernel tracing with ftrace, tracepoints, kprobes and eBPF / bpftrace, and the low-level causes these tools expose: page faults and page-cache behaviour, memory pressure and OOM-killer analysis (system-wide shortage versus a cgroup limit), per-process memory accounting from /proc, NUMA locality, scheduling and CPU-frequency effects, interrupt and softirq load, block-I/O latency, memory growth inside a process, and lock and futex contention. Covers choosing the right tool and its production safety, and isolating the bottleneck before tuning. First-pass resource-saturation readings (load average, utilization and iowait, the USE checklist), profiler theory and application-level instrumentation, kernel internals as concepts, general Linux administration and database tuning are covered elsewhere.
How do you take a 10-second CPU profile of one process on a live host and read the hot functions with call stacks? What goes wrong with stripped binaries or JIT-compiled code, and how do you handle it?
Sample Answer
The idea in plain words
A CPU profile answers "which code is running when the CPU is busy". perf is the Linux profiler: it samples the process by interrupting it at a fixed frequency and recording the instruction address and the call stack (the chain of function calls that led there). Count enough samples and the functions that appear most often are where the CPU time goes. A flame graph is a picture of those stacks: each box is a function, its width is the share of samples that included it, boxes stack from caller (bottom) to callee (top), and a wide box at the top edge is a hot function. The insight: perf shows only on-CPU time (a process waiting on a lock or disk draws nothing), and it can name functions only if it can turn addresses into symbols (a symbol is a function's name, and the symbol table inside a binary maps addresses to those names) and walk stacks, which stripped binaries, missing frame pointers and JIT-compiled code each break in a different way.
Method
perf record -F 99 -g -p PID -- sleep 10
perf report -n --stdio --no-children | head -30
perf script | stackcollapse-perf.pl | flamegraph.pl > cpu.svg
-F 99samples 99 times per second per CPU. A prime-like value avoids landing in lockstep with 100 Hz timers in the program.-grecords call stacks (by following frame pointers: each function keeps the address of its caller's stack frame in a CPU register, so the profiler can walk the chain of callers).-p PIDlimits to one process (add-t TIDfor a single thread), and-- sleep 10ends the capture after 10 seconds. At 99 Hz that is at most 990 samples per busy CPU.perf report -n --stdioprints a text table with sample counts;--no-childrenshows each function's own (self) time rather than self plus callees.- The last line uses Brendan Gregg's FlameGraph scripts (
stackcollapse-perf.pl,flamegraph.pl) to produce an SVG. - Permission: perf needs root or a relaxed
kernel.perf_event_paranoidsetting (a sysctl where higher numbers restrict what unprivileged users may profile). Sampling at this rate has low overhead compared with strace, but still measure it on the most latency-sensitive services.
Worked example: reading the hot functions
How stacks become boxes first. stackcollapse-perf.pl turns every sample into one line, caller;callee;callee count. The program below takes ten collapsed samples and adds each sample's count to every frame on its stack, which is exactly the width a flame graph box gets:
from collections import Counter
# one line per distinct stack: caller;...;callee samples
collapsed = """\
handle_request;read_body;parse_json 6
handle_request;read_body;memmove 2
handle_request;lookup;hash_lookup 1
handle_request;send;copy_to_kernel 1"""
width = Counter()
total = 0
for line in collapsed.splitlines():
stack, n = line.rsplit(" ", 1)
n = int(n)
total += n
frames = stack.split(";")
for depth in range(len(frames)):
width[";".join(frames[: depth + 1])] += n
for box, n in sorted(width.items()):
print(f"{box:42s} {n:2d} samples {100 * n / total:5.1f}%")
Output:
handle_request 10 samples 100.0%
handle_request;lookup 1 samples 10.0%
handle_request;lookup;hash_lookup 1 samples 10.0%
handle_request;read_body 8 samples 80.0%
handle_request;read_body;memmove 2 samples 20.0%
handle_request;read_body;parse_json 6 samples 60.0%
handle_request;send 1 samples 10.0%
handle_request;send;copy_to_kernel 1 samples 10.0%
parse_json is the widest top-edge box (60%), and read_body is wider (80%) only because it contains parse_json and memmove. Reading the report below uses the same idea: --no-children shows each function's self time (samples where it was the function on the CPU), while the children view adds the time of everything it called.
Assumption: a worker pinned at one core for the 10-second capture, so 10 x 99 = 990 samples.
Illustrative excerpt of perf report -n --stdio --no-children, not a real capture:
# Overhead Samples Command Shared Object Symbol
# ........ ....... ....... ............. ......................
60.00% 594 worker worker [.] parse_json
20.00% 198 worker libc.so.6 [.] __memmove_avx_unaligned_erms
10.00% 99 worker worker [.] hash_lookup
10.00% 99 worker [kernel] [k] copy_user_enhanced_fast_string
- Symbol column:
[.]marks a user-space function and[k]a kernel function.__memmove_avx_unaligned_ermsis a C library routine that copies memory; the suffix names the CPU-specific variant of the routine the library picked (here one using AVX vector instructions), so read it as "a memory copy". - Total samples: 594 + 198 + 99 + 99 = 990.
parse_jsonis 594 / 990 = 60.00%. - This bound is Amdahl's law: if a fraction p of the time is sped up by a factor s, the overall speedup is 1 / ((1 - p) + p / s). If you make
parse_json3 times faster, run time becomes 0.40 + 0.60 / 3 = 0.60 of the original, a speedup of 1 / 0.60 = 1.67 times. Even an infinitely fastparse_jsoncaps the gain at 1 / 0.40 = 2.5 times. Fix the widest boxes first and recompute. - The flame graph presents the same data with the call chain: if
parse_jsonsits underhandle_requestandread_body, the wide plateau tells you whether the cost is the parser or the amount of data it is fed.
What goes wrong, and the fix for each
- Stripped binaries (symbols removed). The report shows raw addresses such as
[.] 0x00000000000a3f10instead of names. Fix: install the matching debug-symbol package for the distribution, or point perf at an unstripped copy (stripped means the symbol table was removed to shrink the file) with the same build ID (a hash that identifies one exact build); build with-gand keep the symbols in a separate file for production. - No frame pointers. Most optimized x86-64 builds drop the frame-pointer register, so
-gproduces stacks that are one frame deep or garbled. Usual first fix: recompile with-fno-omit-frame-pointer(keep the frame-pointer register), since frame-pointer stacks are the cheapest to collect. Alternatives when you cannot rebuild:perf record --call-graph dwarf(copies a chunk of the stack with every sample and unwinds it afterwards using DWARF, the debug-information format that describes how each function lays out its stack, which is heavier on data size and overhead); or--call-graph lbron Intel hardware that has the last-branch-record (LBR) feature, a CPU buffer that remembers the most recent jumps and so lets the profiler rebuild a short call chain without frame pointers. - JIT-compiled code (just-in-time: compiled to machine code at runtime). The machine code lives in memory regions that belong to no file, so perf prints addresses. The runtime has to publish a symbol map, and the per-runtime switches below are alternatives, one per language: perf reads
/tmp/perf-PID.mapwhen it exists, one line per function (start address, size, name). Node.js writes it withnode --perf-basic-prof; Python 3.12 or newer supports it withpython -X perf; Java needs a perf-map agent and frame-pointer preservation (-XX:+PreserveFramePointer). The map must be written while the process runs, and the file must be readable by the user runningperf report. - Containers. The map file name uses the PID as the process sees it, and the binary's files may not exist on the host; run perf inside the container's mount namespace (the container's private view of the filesystem) or copy the symbols out.
- Off-CPU time is invisible. If the process is slow but the CPU is not busy, a CPU profile is the wrong tool; look at locks, I/O or scheduling instead.
Judgment
Commit to a capture that is short (10 seconds), repeated once to confirm the hot function is stable, and taken at the time of the problem. Compare a good period and a bad period rather than reading one profile in isolation. Common mistakes: profiling with no symbols and then guessing, reading a flame graph's x axis as time (it is alphabetical stack order, not a timeline), and tuning a function that is wide only because its callers call it too often.
After a networking library upgrade, a microservice shows more system CPU time. How would you confirm whether syscall frequency went up or the kernel is doing more work per call, and how would you compare syscall counts per process before and after a change with low overhead and a defensible threshold?
Sample Answer
The idea in plain words
A system call (syscall) is a request from a program to the kernel: sendmsg, epoll_wait, futex and so on. System CPU time is spent inside those calls, so it is the product of two things that can change independently:
After the library upgrade, either the program makes more calls (for example it now splits one write into several, or polls more often) or each call costs more (bigger copies, different socket options, more lock contention). The two have different fixes, so the first move is to measure the call rate and the cost per call separately, then decompose the change.
Step 1: measure call rate cheaply
perf stat -e raw_syscalls:sys_enter -p <pid> -- sleep 30
perf stat counts events; raw_syscalls:sys_enter is the tracepoint (a fixed kernel instrumentation point) hit at the start of every syscall; -p selects the process; -- sleep 30 sets a 30-second window. Divide the count by 30 for calls per second. Counting costs very little because nothing is recorded per event. To see which syscalls changed:
bpftrace -e 'tracepoint:syscalls:sys_enter_* /pid == <pid>/ { @calls[probe] = count(); } interval:s:30 { exit(); }'
bpftrace (a scripting front end for eBPF, which runs small programs inside the kernel after a verifier has checked them for safety) attaches to every syscall entry tracepoint, counts per syscall for the matching process, and exits after 30 seconds; it prints the map on exit. Attaching hundreds of probes takes a moment but the per-event work is a counter increment. strace -c -p <pid> gives similar counts but stops the process at every syscall (it uses ptrace, the kernel's debugging interface, which pauses the traced process twice per call), which can slow a syscall-heavy service substantially, so it is for staging only. timeout -s INT 30 perf trace -s -p <pid> prints a per-syscall summary (count, total time, average, maximum) with lower overhead than strace, though not none.
Note that some "time" calls (clock_gettime) are served in user space by the vDSO (a small code page the kernel maps into every process so that cheap reads like the time need no kernel entry) and never appear as syscalls; if an upgrade changes the clock source, they can start appearing as real syscalls, which is itself a finding.
Step 2: measure cost per call
pidstat -u -p <pid> 30 1
pidstat -u reports CPU use per process; 30 1 means one 30-second sample; read %system (100% = one CPU, summed over threads). Then:
If the call rate is flat but %system rose, per-call cost changed: take kernel stacks with perf record -g -p <pid> -- sleep 10 before and after and compare where the extra time sits (copy routines, a lock, netfilter, the kernel's packet-filtering and firewall hooks, or TCP code).
Worked example (hypothetical numbers)
Same request rate, 500 requests per second, before and after the upgrade:
| Calls per second | %system | Kernel CPU per call | |
|---|---|---|---|
| Before | 40,000 | 12% | 0.12 / 40,000 = 3.000 us |
| After | 48,000 | 21% | 0.21 / 48,000 = 4.375 us |
System CPU rose by 21 / 12 = 1.75 times. Decompose: call rate grew 48,000 / 40,000 = 1.2 times, per-call cost grew 4.375 / 3.000 = 1.4583 times, and 1.2 x 1.4583 = 1.75, so the factors reproduce the total. Factors multiply, but shares should add up, and logarithms turn a product into a sum: ln 1.75 = ln 1.2 + ln 1.4583, that is 0.5596 = 0.1823 + 0.3773. Each term's fraction of the sum is its share of the regression: the call-rate share is 0.1823 / 0.5596, about 33%, and the per-call share is 0.3773 / 0.5596, about 67%. So most of this regression is per-call cost, not call count, which points to the kernel-stack comparison rather than to the library's calling pattern. If the shares had been reversed, the fix would be in the library's batching.
Step 3: compare before and after with a defensible threshold
Normalise by work done. Total calls rise with traffic, so compare calls per request (calls per second divided by requests per second from the application's own counter). Above: 40,000 / 500 = 80 and 48,000 / 500 = 96 calls per request.
Store a baseline. For each service (key by service name or cgroup, not by PID, which changes at every restart) and build version, record each 30-second window as a row: window start, requests, and calls per syscall name. Keep at least a day of windows that include peak and off-peak traffic.
Compare aggregated, per syscall. Illustrative baseline of 20 windows against 20 windows after the change, in calls per request:
| Syscall | Baseline mean | Baseline SD | After mean | Threshold | Flag |
|---|---|---|---|---|---|
sendmsg | 20.0 | 0.8 | 35.8 | 22.4 | yes |
recvmsg | 20.0 | 0.7 | 20.2 | 22.1 | no |
epoll_wait | 20.0 | 0.6 | 20.0 | 22.0 | no |
futex | 10.0 | 0.4 | 10.0 | 11.2 | no |
| all other | 10.0 | 0.3 | 10.0 | 11.0 | no |
The baseline means add up to 20.0 + 20.0 + 20.0 + 10.0 + 10.0 = 80.0 and the after means to 35.8 + 20.2 + 20.0 + 10.0 + 10.0 = 96.0, matching the 80 and 96 calls per request above. The standard deviation (SD) is the typical size of the window-to-window wobble of a figure that is not really changing; here it is taken from the 20 baseline windows. The illustrative rule is: flag a syscall when the after-mean exceeds the baseline mean plus the larger of three baseline SDs (the normal wobble) and a 10% effect floor (so a tiny but visible shift does not trigger work). For sendmsg: 3 x 0.8 = 2.4 and 10% of 20.0 = 2.0, the larger is 2.4, so threshold = 20.0 + 2.4 = 22.4, and 35.8 is above it. For recvmsg: 3 x 0.7 = 2.1 against a floor of 2.0, threshold 22.1, and 20.2 is below it. For epoll_wait: 3 x 0.6 = 1.8, the floor 2.0 is larger, threshold 22.0. For futex: 3 x 0.4 = 1.2, floor 1.0, threshold 11.2. For all other: 3 x 0.3 = 0.9, floor 1.0, threshold 11.0. Only sendmsg crosses its threshold, and it accounts for 35.8 - 20.0 = 15.8 of the 16 extra calls per request.
That rule covers only comparisons of mean calls per request at a similar request mix. A real process must also handle: a changed request mix (compare like with like or per endpoint), many syscalls tested at once (some will cross a threshold by chance, so rank by absolute extra calls per request first), non-stationary load (traffic level or mix drifting during the comparison, so the two sets of windows are not alike), warm-up after deploys, and a significance test (a statistical check of whether a difference this size could be chance) or repeated A/B runs when windows are few. Run the comparison on a canary (a new-build instance given a share of real traffic) next to a control instance on the old build for the cleanest read.
Judgment
Count with perf stat and bpftrace, compute CPU per call from pidstat, decompose, then go to stacks only for the half that moved. Keep strace for staging. If the extra time is per call, the answer lies in kernel stacks or socket options; if it is call count, the answer lies in the library's batching or polling settings.
Common mistakes
- Comparing absolute counts across different traffic levels.
- Keying the baseline by PID.
- Using
strace -con a hot production process. - Attributing the whole increase to call count without computing cost per call.
A process spends a lot of time in kernel mode (high system CPU). Give a diagnostic order to decide whether the cause is heavy syscall use, the network stack, filesystem contention or a kernel bug, and what evidence you would gather to support a kernel-bug report.
Sample Answer
The idea in plain words
CPU time is split into user time (the program's own code), system time (the kernel working on behalf of a process, mostly inside system calls), and interrupt time (the kernel handling hardware interrupts and softirqs, deferred kernel work, called softirqs, that the kernel runs right after a hardware interrupt, such as processing received network packets). High system CPU means the kernel is doing a lot of work, and the job is to say whose work and why. The core path is steps 1 to 3 below; the tools in step 4 are picked by what step 3 shows, so a beginner learns mpstat, pidstat and perf first. The insight: go from the cheapest, broadest signal to the narrowest. First separate system time that belongs to the process from interrupt time that merely landed on a CPU, then count syscalls, then sample where in the kernel the CPU actually is, and only then ask whether a kernel bug is plausible. A kernel-bug report needs reproducible evidence, and "high sys time" alone is not evidence.
Diagnostic order
1. Whose time is it?
mpstat -P ALL 1 5
pidstat -u -t 1 5
mpstat -P ALLprints each CPU's%usr,%sys,%iowait,%irq(hardware interrupts),%soft(softirqs) and%steal(time a virtual machine's CPU was taken by the hypervisor).1 5is a one-second interval, five samples.pidstat -u -tprints%usrand%systemper thread, so a hot thread stands out.- Illustrative excerpt of
mpstat -P ALL 1(three of its rows) andpidstat -u -t 1(one row), not real captures:
10:15:02 CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle
10:15:02 all 12.00 0.00 58.00 0.00 0.50 1.50 0.00 0.00 0.00 28.00
10:15:02 0 10.00 0.00 60.00 0.00 0.00 2.00 0.00 0.00 0.00 28.00
10:15:02 1 14.00 0.00 56.00 0.00 1.00 1.00 0.00 0.00 0.00 28.00
10:15:02 UID TGID TID %usr %system %guest %wait %CPU CPU Command
10:15:02 998 - 5120 8.00 52.00 0.00 0.50 60.00 0 |__proxy
Here %sys is 58% while %irq + %soft is only 0.5 + 1.5 = 2%, and thread 5120 of proxy alone has %system 52, so the kernel time is the process's own system calls. In contrast, %sys near 5 with %soft at 60 on two CPUs would mean packet processing.
- If
%softor%irqis high on a few CPUs and the process's own%systemis small, the load is network or device interrupt processing, not the process's syscalls. Check/proc/softirqs(counts per CPU forNET_RX,NET_TX,BLOCK,TIMERand others, sampled twice and subtracted) and/proc/interrupts.
2. Is it heavy syscall use? Count syscalls and measure how long each class takes, with the lightest tool you can:
timeout -s INT 10 perf trace -s -p PID
bpftrace -e 'tracepoint:raw_syscalls:sys_enter /pid == PID/ { @[args->id] = count(); }'
perf trace -sprints a per-syscall summary (calls, total and average time) using kernel tracepoints, with far less overhead than strace.strace -c -f -p PIDfor a few seconds is the heavier equivalent.- The bpftrace line counts syscalls by number; stop it with Ctrl-C to print the map.
- Many millions of cheap calls per second (
read,futex,epoll_wait,stat) mean the program should batch or cache. Few calls with huge kernel time each mean the time is inside one call, which step 3 locates. (writevis a system call that sends several buffers in one call, the usual cure for many small writes.) A tracepoint is a hook the kernel developers placed on purpose, andbpftraceis a tool that attaches small eBPF programs to such hooks.
3. Where inside the kernel? Sample the process with kernel stacks:
perf record -F 99 -g -p PID -- sleep 10
perf report -n --stdio --no-children --sort symbol | head -25
Symbols marked [k] are kernel functions. Their names place the time in a subsystem: TCP functions such as tcp_sendmsg and tcp_write_xmit, and net_rx_action, mean the network stack; filesystem functions such as ext4_*, xfs_*, d_lookup (directory lookup) and generic_file_read_iter mean the filesystem; native_queued_spin_lock_slowpath, mutex_spin_on_owner and rwsem_* mean lock contention (many threads waiting for the same lock) in whichever subsystem is above them in the call stack, which perf record -g shows by listing the callers of each function; clear_page_erms or handle_mm_fault mean memory management and page faults. If addresses show instead of names, kernel symbol access is restricted (kernel.kptr_restrict is a sysctl that hides kernel addresses from unprivileged users) or the symbols are missing.
4. Narrow by subsystem.
- Network:
ss -s(socket counts),nstat(kernel network protocol counters such as retransmits),sar -n DEV 1(packets per second),ethtool -S eth0(statistics kept by the network card's driver, including drops). Check whether interrupts are spread across CPUs. - Filesystem: bcc (a collection of eBPF-based tracing tools)
ext4slowerorxfsslower(filesystem operations slower than a threshold),opensnoop(every file open), and the perf call stacks above. Many threads hitting one directory or one file's lock shows as lock slowpath under filesystem functions. - Kernel bug: suspicious when time is concentrated in one kernel function or a kernel thread (
kworkerruns deferred kernel work items,ksoftirqdruns softirqs when they pile up,kswapdreclaims memory) at a rate the workload cannot explain, whendmesgshows a soft lockup (a CPU stuck in kernel code for many seconds without yielding) or an RCU stall warning (RCU, read-copy-update, is a kernel mechanism for lock-light reads, and the warning means a CPU held up its progress too long), or when the same workload is fine on another kernel version.
Worked example
Assumptions (hypothetical): a 2-CPU capture of a proxy process whose threads together kept about one CPU busy (the two CPUs above are 72% busy each, 1.44 CPUs in all, which leaves room for that), so the 10-second capture at 99 Hz took 1,000 samples, which is 1,000 / 990 = 1.01 CPUs' worth. pidstat showed %system high for the process and %soft low, so the time is the process's own kernel work, not interrupts.
Illustrative excerpt of perf report -n --stdio --no-children --sort symbol, not a real capture:
# Overhead Samples Symbol
30.00% 300 [k] copy_user_enhanced_fast_string
20.00% 200 [k] tcp_sendmsg_locked
15.00% 150 [k] _raw_spin_lock
10.00% 100 [k] tcp_write_xmit
25.00% 250 (other kernel and user-space functions)
Check: 300 + 200 + 150 + 100 + 250 = 1,000, and 300 / 1,000 = 30.00%. Reading: copy_user_enhanced_fast_string is the copy between user and kernel memory, and tcp_sendmsg_locked plus tcp_write_xmit are the TCP send path. Why a copy function belongs to it: send() must move the application's bytes from user memory into kernel socket buffers, and that copy is done by a generic user-to-kernel copy routine, so copy_user_* functions show up under tcp_sendmsg in the call stack; the name alone does not place it, the callers listed by perf record -g do. The 15% in _raw_spin_lock (the kernel's basic lock-acquire function, which a waiting CPU spins in, looping until the lock is free) is a second signal: some of those samples are waiting for a lock, and the callers show whose, so check that before calling the path clean. So 30 + 20 + 10 = 60.00% of samples are moving bytes out through the network stack. That is a process sending a lot of data, not a stuck kernel. The next question is whether it sends too many small buffers (many syscalls, fixable by batching or writev) or simply a lot of bytes (a capacity question). Step 2's syscall count separates those two.
Evidence for a kernel-bug report
Assemble these before writing to the distribution or the kernel mailing list:
- Exact kernel version and distribution package (
uname -r,uname -v) and whether the kernel is tainted (cat /proc/sys/kernel/tainted; a taint is a flag the kernel sets when something makes its state hard to trust, such as a proprietary or out-of-tree module, and a report on a tainted kernel is usually closed).0means untainted; a non-zero value is a bitmask, for example4096means an out-of-tree module was loaded. - A reproducer: the smallest workload that triggers it, hardware or virtual machine type, and the steps.
- Kernel-symbol call stacks from perf or a flame graph, plus
dmesgwith timestamps around the event, and/proc/PID/stacksamples (as root) for a stuck task. A soft lockup shows indmesgas a line like this illustrative one:
watchdog: BUG: soft lockup - CPU#3 stuck for 23s! [kworker/3:1:88]
- A regression bisection (a binary search over kernel versions or commits to find the one change that introduced the problem): the last kernel version that does not show it, and whether a current stable kernel still does.
- Counters showing the abnormal rate (syscalls per second, interrupts per second) next to a healthy baseline.
For follow-up work at function level, ftrace is the kernel's built-in function tracer, controlled through files under /sys/kernel/tracing: write function_graph to current_tracer, restrict it to the functions you care about by writing their names to set_ftrace_filter, write 1 to tracing_on, and read the result from trace. The filter is what limits the overhead, because tracing every kernel function is heavy.
Judgment
Assume the application or the configuration first: the overwhelming majority of high system time is a program making too many syscalls or moving a lot of data, and a kernel bug is the last hypothesis, claimed only with the evidence list above. Common mistakes: blaming the process for interrupt time it did not cause, running strace on a hot process and distorting the result, and reading %sys without the sample that names the kernel function.
A service burns CPU while threads seem to be stuck on a lock, and the profile is full of futex-related calls. How would you tell contended-lock behaviour from useful work using OS-level evidence, and find which lock is hot?
Sample Answer
The idea in plain words
A futex (fast userspace mutex) is the kernel primitive behind most thread locks and condition variables. An uncontended lock is taken with an atomic instruction (a single CPU instruction that reads and updates a memory word indivisibly, so no other thread can interleave) in user space and makes no system call at all. A thread only enters the kernel through futex(2) when it must sleep because someone holds the lock (FUTEX_WAIT) or when a releaser must wake a sleeper (FUTEX_WAKE). So many futex calls are a sign of contention, but they are also made by idle worker threads waiting for work, which is not a problem. The task is to separate those cases with evidence about CPU, context switches and wait time, then identify the lock by its address and call site.
Other terms: a context switch is the kernel switching a CPU from one thread to another (voluntary when the thread blocks, involuntary when it is preempted); lock contention is threads waiting for a lock that another holds (the code that runs while holding it is the critical section); a spinlock is a lock whose waiters loop on the CPU instead of sleeping; off-CPU time is time a thread spends sleeping rather than running.
Method
- Is throughput scaling with threads? Contention shows as flat throughput while threads and CPU rise. Check by comparing request rate at two thread counts.
- System-wide shape.
vmstat 1: highcs(context switches per second) and highsy(system CPU) with modestuspoint at lock handoff overhead instead of useful computation. - Per-thread switch rates.
pidstat -w -t -p <pid> 1(-wcontext switches,-tper thread) reportscswch/s(voluntary: the thread blocked, as on a lock) andnvcswch/s(involuntary: preempted). Many voluntary switches per second on worker threads = they sleep and wake constantly. - Where CPU time goes.
perf record -F 99 -g -p <pid> -- sleep 30thenperf report --no-children. Useful work shows application compute functions at the top. Contention shows lock functions in the user library (for example__lll_lock_wait,pthread_mutex_lock) and kernel futex and spinlock symbols (for examplefutex_wait,native_queued_spin_lock_slowpath, the kernel's spinlock routine for the case where the lock is already taken). Symbol names vary by library and kernel version. - Where threads sleep.
offcputime -p <pid> -f 30(bcc: aggregated stacks of blocked time,-ffolded output for a flame graph) shows which code paths spent time sleeping in futex waits. Idle pool threads show up in a pool-wait stack; contended workers show up in the request path. - Which lock. The first argument of
futexis the address of the lock word. Count waits by address:
bpftrace -e 'tracepoint:syscalls:sys_enter_futex { @[args->uaddr] = count(); }'
Read it piece by piece:bpftraceis a one-line scripting front end for eBPF (small programs run inside the kernel after a safety check);tracepoint:syscalls:sys_enter_futexis a tracepoint, a fixed kernel instrumentation point that fires each time any thread entersfutex, and exposes the call's arguments asargs->uaddr(the user-space address of the lock word),args->opandargs->val;@[...]is a map (a table that lives inside the kernel program) keyed by that address;count()adds 1 to the key's entry. When you press Ctrl-C the map is printed. Illustrative output for an 8-second window (keys are decimal addresses, the hot one is 0x7f8b2c001a40 in hex;printf '%x\n' <number>converts):
@[140235715385984]: 900
@[140235715385952]: 2900
@[140235715385920]: 396200
The three entries add up to the 400,000 calls, and one address takes 396,200 / 400,000 = 99.05% of them, so that is the hot lock. Add ustack to the key (@[args->uaddr, ustack] = count();; ustack is the user-space call stack of the calling thread) to see the code that took it. To measure wait time per lock, record nsecs at sys_enter_futex and sys_exit_futex per thread and sum the difference by address. First aggregate args->op to see which operations your library uses (plain waits, and wait-bitset variants, FUTEX_WAIT_BITSET, which take an absolute timeout and are common for timed waits and condition variables), and filter on the one you care about.
A static or global lock lives in the binary's data segment (the part of the program's memory that holds global variables), so match the address against /proc/<pid>/maps (the list of the process's memory regions and which file backs each) and nm output (nm lists the symbols and addresses inside a binary); a heap-allocated lock needs the call stack, or its allocation site.
7. Careful with strace. strace -f -T -e trace=futex -p <pid> prints each call with its duration and address, which is perfect for a staging box, but strace uses ptrace (the kernel's debugging interface for pausing and inspecting another process), stops the process at every syscall and can slow a hot production service by a large factor. In production prefer perf trace -s -p <pid> (summary) or the bpftrace probes above, with a short duration.
Worked example (assumed numbers, illustrative)
Assume a worker pool of 16 threads; each request takes 60 us outside a single global lock and 40 us holding it.
- The lock can serve at most one holder at a time, so its maximum rate is 1 / 40 us = 25,000 requests per second, whatever the thread count.
- One thread alone would complete 1 / 100 us = 10,000 requests per second. Three or more threads already exceed what the lock allows (100 / 40 = 2.5 threads saturate it).
- With 16 threads, assume the lock is saturated at 25,000 requests per second. Little's law says that in steady state the average number of items inside a system equals the rate at which they pass through times the average time each one stays (a café with 10 customers inside on average and 2 served per minute means each customer stays 5 minutes). Here the system is closed, a fixed 16 threads that are always either working or waiting for the lock, so the number inside is always 16, the rate is the throughput, and the time each request stays is its cycle time (time from starting a request to starting the next one): threads = throughput x cycle time, so cycle time = 16 / 25,000 = 0.00064 s = 640 us. A cycle is 60 us of work + 40 us holding + wait, so wait = 640 - 100 = 540 us per request. 84% of each request's cycle (540 of 640) is waiting.
- If each contended acquire costs one sleep (a
FUTEX_WAIT) and one wake (FUTEX_WAKE) from the releaser, that is about 2 x 25,000 = 50,000 futex calls per second, each with a context switch cost; this is where the system CPU goes. Over an 8-second capture window that is 25,000 x 8 = 200,000 requests and 400,000 futex calls, the figure in the next excerpt. Assume a sleeping call lasts the 540 us wait and a wake call about 5 us.
Illustrative excerpt from timeout -s INT 8 strace -c -w -f -p <pid> (-w makes the seconds column wall-clock time inside each call instead of kernel CPU time; the summary adds up all 16 threads, which have 16 x 8 = 128 thread-seconds available):
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
93.16 109.000000 272 400000 18400 futex
3.42 4.000000 20 200000 read
3.42 4.000000 20 200000 write
------ ----------- ----------- --------- --------- ----------------
100.00 117.000000 800000 18400 total
Reading it: the futex calls total 400,000 in the 8-second window, which is 400,000 / 8 = 50,000 per second, exactly the model's figure (200,000 waits plus 200,000 wakes). Their time is 200,000 x 540 us + 200,000 x 5 us = 108.0 + 1.0 = 109.0 s, which is 93.16% of the 117.0 s total and 109.0 / 400,000 = 272 us per call on average, the mean of long sleeps (540 us) and short wakes (5 us). This is wall time spent inside the call, including sleeping, so on its own it does not prove CPU is being burned; idle waiters add to it just the same. The 18,400 errors are futex calls that returned an error such as EAGAIN ("try again": the lock word had already changed by the time the thread asked to sleep, so it did not sleep), which is normal under contention.
Illustrative excerpt from pidstat -w -t -p <pid> 1 for three of the 16 workers (columns Time UID TGID TID cswch/s nvcswch/s Command; with -t the thread rows show - in the TGID column, and the process-wide row, omitted here, shows the TGID with - in TID):
14:03:08 1001 - 4130 1562.50 40.00 |__worker-0
14:03:08 1001 - 4131 1562.50 40.00 |__worker-1
14:03:08 1001 - 4132 1562.50 40.00 |__worker-2
1,562.5 voluntary switches per second per thread x 16 threads = 25,000 per second, one sleep per request, matching the model and the 200,000 waits above (25,000 x 8). nvcswch/s is 40 per thread per second, tiny next to 1,562.5: the scheduler almost never kicks these threads off the CPU, they leave it by themselves because they block on the lock. Workers that mostly do useful work would show a low cswch/s and high CPU in application functions in perf.
Decision
Contended lock: flat throughput when threads are added, high voluntary switches per worker, lock and futex symbols in the perf profile, and one or a few futex addresses dominating the wait count. Useful work: application functions dominate perf, throughput rises with threads until CPUs are full, and futex calls come from idle threads whose stacks are in the pool-wait path. Spinning locks add a third pattern: high user CPU in lock-acquire loops with few futex calls.
Fix order I would recommend: shorten the critical section (here, cutting the 40 us hold in half doubles the 25,000 per second ceiling to 50,000), then shard the lock (split it into several locks that each guard part of the data, so threads touching different parts do not collide), then replace it with a read-write lock or a lock-free structure (one built from atomic instructions so that no thread ever has to sleep waiting for another), and only after that add threads.
Common mistakes
- Treating "futex is 93% of strace time" as proof of contention.
- Running
strace -fon a hot production process. - Adding threads to a lock-bound service.
- Stopping at "a lock" without the address and call stack that name it.
What is the difference between kprobes and tracepoints? If you were chasing unexpected permission denials in a security-module hook on a live host, which would you use, what would you capture, and what stability risks come with dynamic probing?
Sample Answer
The idea in plain words
Both are ways to attach a small piece of tracing code to the running kernel without rebooting. A tracepoint is a hook the kernel developers placed deliberately in the source, with a name and a documented set of fields (for example sched:sched_switch). A kprobe is a probe you plant dynamically on almost any kernel function at run time (a kretprobe fires when that function returns and can read its return value). Rule of thumb: use a tracepoint when one exists for what you need, because it is cheaper and its name and fields change less between kernel versions; use a kprobe when no tracepoint covers the place you need, accepting that it can break when the kernel is updated.
The other dynamic probe types (fentry/fexit, which attach through a different mechanism, kernel-module probes, and raw kprobe_events) share the kprobe column's trade-offs in the table below: they attach to functions that were never meant as a stable interface.
Terms: a security module hook is a function the kernel calls at each security decision (opening a file, executing a program) so a Linux Security Module such as SELinux or AppArmor can allow or deny; eBPF runs small programs inside the kernel, which the kernel's verifier (a checker that rejects programs that could loop forever or touch invalid memory) must approve before they run; errno is the small number a failing system call returns, where EACCES (13) means permission denied and EPERM (1) means operation not permitted; an inode is the filesystem's record that identifies one file, so inode plus device names a file unambiguously; fentry/fexit are lower-overhead probe types on newer kernels with BTF (type information for the kernel), which attach to function entry and exit.
| Tracepoint | Kprobe / kretprobe | |
|---|---|---|
| Where it can attach | Only where the kernel source defines one | Nearly any kernel function entry, return or instruction offset, except blacklisted functions (see /sys/kernel/debug/kprobes/blacklist) |
| Stability across kernel versions | Names and fields are maintained deliberately, though not frozen forever | Function can be renamed, inlined away or change its arguments; your probe silently breaks or reads wrong arguments |
| Arguments | Named fields, already decoded | Raw registers; you must know the function signature and struct layouts |
| Overhead per hit | Low; a disabled tracepoint costs almost nothing | Higher; the probe traps or is patched in, plus your handler |
| Visibility of return value | Only if the tracepoint includes it | kretprobe gives the return value, which is the error code of a denial |
The permission-denial case
Step 1: use the facility built for denials before probing. Security modules write audit records for denials. Run ausearch -m avc -ts recent for SELinux, or read the kernel log for AppArmor denial lines. Each record names the process, the object, the permission and the security contexts. An AVC record (AVC stands for access vector cache, the SELinux component that caches and logs allow/deny decisions) looks like this illustrative example:
type=AVC msg=audit(1700000000.123:456): avc: denied { read } for pid=4127 comm="nginx" name="app.conf" dev="dm-0" ino=131075 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file permissive=0
It says process nginx (security context httpd_t) was denied read on a file labelled user_home_t. Some policies silence known-benign denials with dontaudit rules (rules that deny an access without writing a record), so a denial can happen without a record; semodule -DB rebuilds policy with dontaudit rules disabled (the D means disable them, B means rebuild) so those denials appear, and semodule -B restores it. Check whether a tracepoint exists too: SELinux ships an audited-denial tracepoint (avc:selinux_audited) on kernels that carry it, listed with bpftrace -l 'tracepoint:avc:*'.
Step 2: if records are missing or the reason is unclear, use a kretprobe. The LSM framework wrapper functions such as security_file_open return 0 to allow or a negative errno to deny (-13 is EACCES, -1 is EPERM). List what exists on this kernel with bpftrace -l 'kprobe:security_*'. A kretprobe on the wrapper that fired the denial sees every denial regardless of audit settings and also tells you which hook denied. Sketch (needs a kernel with BTF, so bpftrace knows the layout of struct file; adjust for your kernel):
bpftrace -e '
kprobe:security_file_open /comm == "nginx"/ { @f[tid] = arg0; }
kretprobe:security_file_open /@f[tid]/ {
if ((int32)retval < 0) {
printf("%s pid=%d uid=%d ret=%d file=%s\n", comm, pid, uid, (int32)retval,
str(((struct file *)@f[tid])->f_path.dentry->d_name.name));
}
delete(@f[tid]);
}'
How to read it. A function's arguments are only available when it is entered, not when it returns, so the first probe (a kprobe, at entry) saves the first argument, a pointer to the struct file being opened, in a map @f keyed by tid (thread ID; many threads run this function at once, so each needs its own slot). Its filter comm == "nginx" limits the saving to the suspect command; drop the filter to see every process, at the cost estimated below. The kretprobe fires at return and runs its body only when a saved pointer exists. The hook returns a 32-bit int, so the script casts retval to int32 before testing the sign or printing it. When the result is negative, it casts the saved number back to struct file * and follows f_path.dentry->d_name.name (the file's name as the kernel stores it) to print the file name. The delete sits outside the if so it runs on every return, not only denials, and sitting in the same block it cannot run before the print. Run it under timeout 60 so it cannot be forgotten. One printed line looks like this (illustrative):
nginx pid=4127 uid=998 ret=-13 file=app.conf
ret=-13 is EACCES, the denial the application saw.
What I would capture
- Process name, PID, UID, and the hook that denied (which wrapper function).
- The return value (errno).
- The object: file name, or inode and device for an unambiguous identity.
- The calling syscall path with
kstack(kernel stack) orustackfor the user side, to see why the program asked for that access. - A timestamp (
nsecs), so denials line up with the application's failures. - Counts by (process, hook, errno) aggregated in the kernel instead of one print per event.
Stability and safety risks of dynamic probing
- Overhead on hot hooks. File-access hooks are hot:
security_file_openruns on every open andsecurity_file_permissionon every read and write. Assume (illustrative) 400,000 hits per second, 0.5 us for the full handler (both probes plus the print path) and 0.1 us at each of the two probes for the entry plus the test that rejects an unwanted event. Unfiltered: 400,000 x 0.5 us = 200,000 us per second = 0.2 CPU, about 20% of one CPU. Filtered inside the probes to one process that causes 2,000 hits per second: every hit still enters both probes (the kernel arms the return probe on every call, whatever the entry filter decides), so the cost is 400,000 x 0.2 us = 80,000 us plus 2,000 x 0.5 us = 1,000 us, total 81,000 us per second = 0.081 CPU, about 8% of one CPU. The filter cuts the cost about 2.5 times here, not to near zero, because both probes and their tests are paid on every hit. Filter by PID or command inside the probe, not in user space, and attach to a narrower hook when one exists. - Silent wrongness across kernel versions. An inlined or renamed function means no events (looks like "no denials"); a changed argument order means garbage. Confirm the symbol and arguments on the exact kernel with a known-denial test.
- Missed return events. kretprobes keep a limited number of in-flight instances; heavy concurrency can drop returns. Check the miss count in
/sys/kernel/tracing/kprobe_profile(a file listing, per probe, how many times it hit and how many times it was missed). - Handler errors in custom kernel modules. A probe written as a kernel module runs with kernel privileges and can crash the host; eBPF programs are checked by the verifier and are the safer way to do it.
- Leftover probes. eBPF programs detach when the tool exits; probes created by hand through
kprobe_eventsstay until you remove them. - Policy restrictions. Kernel lockdown (a kernel mode that restricts even root's access to kernel internals) or secure boot (firmware only loads signed boot software, and often turns lockdown on) configurations can refuse the probe.
Recommendation
For the stated problem I would audit first, then a short, filtered kretprobe (or fentry/fexit) on the specific wrapper that the audit record points to, run for a bounded time on one affected host, and capture process, hook, errno, object and kernel stack. I would use a tracepoint instead if one covers the denial, because it is cheaper and survives kernel upgrades. Switch to the dynamic probe only when the audit trail is silent or lacks the reason.
Common mistakes
- Reaching for kprobes before reading the audit records.
- Probing a hot hook with no filter.
- Assuming "no events" means "no denials" after a kernel update.
- Putting
printfper event in a hot path. - Leaving probes attached.
Unlock Full Question Bank
Get access to all 11 Systems Performance Analysis & Tuning interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.