When a request is slow, its time went somewhere: running on a CPU, waiting for a CPU, inside a system call, faulting in memory, or asleep waiting for a disk or a lock. Profiling is finding out which. A CPU profiler such as perf samples what is running, and a flame graph turns thousands of those samples into one picture where width is time. But a CPU profile only sees time spent on a CPU, so a request stuck behind a lock looks perfectly healthy in it. This lesson follows one request through a Linux box, shows where perf and flame graphs find a CPU hog, and where you need off-CPU analysis instead.
Difficulty: Advanced · Know this first: Lesson 05, Lesson 04, Lesson 03
This bar splits one request on the box, in milliseconds. It is a worked example, not a measurement. The user-code hop is the only one a CPU profiler sees directly; the disk and lock hops are off-CPU time.
Enter a request's wall time and the CPU time it used. The difference is time spent asleep. That split decides which flame graph to make first.
off-CPU = wall − CPU · on-CPU share = CPU ÷ wall · above about 70 percent on-CPU, start with a CPU flame graph; below about 30 percent, start off-CPU
Mostly asleep: make an off-CPU flame graph
Three questions. No score is saved anywhere — this is just you against the material.
Profiling grows in four levels: first the USE method and where time goes, then perf and flame graphs, then off-CPU analysis and symbols, and finally continuous profiling and performance budgets.
At the basic level you can list where time goes: running on a CPU, waiting for a CPU, inside the kernel, and asleep waiting for disk, network, or a lock. You can run the USE method: for each resource, utilization (how busy), saturation (how much work is queued), and errors.
mpstat for utilization, vmstat's r column for saturation.free -m, and si/so in vmstat for swapping.iostat -xz 1: %util, await, aqu-sz.Where it breaks: reading 100 percent %util on a modern SSD or RAID volume as "full"; such devices serve many I/Os at once, so look at await and queue size instead.
Try it: Basic
vmstat shows r = 24 on an 8-core box. What does that tell you?
Now do it: Run the 60-second pass from the first hop on a box you use and write one line per resource: utilization, saturation, errors.
At the intermediate level you record a CPU profile and read it.
perf top for a live view; perf record -F 99 -a -g -- sleep 30 for a recording of all CPUs with stacks.perf report --stdio for text; perf script through Brendan Gregg's FlameGraph scripts for an SVG.Reading it: the x-axis is the share of samples, sorted alphabetically, not time order; find the widest plateaus at the top; a tall narrow tower is deep but cheap.
Troubleshooting: [unknown] frames mean missing symbols or broken stack walking: install debug symbols, compile with frame pointers, or use --call-graph dwarf.
Try it: Intermediate
Why does perf commonly sample at 99 Hz rather than 100 Hz?
Now do it: Run fold_stacks.py in Go deeper, then read the self and total columns and say which frame you would fix first.
At the advanced level you profile what CPU profilers cannot see, and you get symbols right.
offcputime records every blocking event with its stack and duration; flame graph it the same way. Combine with biolatency for disk and tcpconnlat for network waits.python -X perf on Python 3.12+, and runtime profilers such as async-profiler for the JVM and py-spy for Python, which read the interpreter's own stacks.--symfs or a profiler that resolves symbols from the container's mount namespace.nr_throttled in the container's cpu.stat before profiling code.Security: perf and eBPF need privileges (CAP_PERFMON, CAP_BPF, or root, and kernel.perf_event_paranoid); keep them to the profiling session.
Try it: Advanced
A container's p99 latency doubles; its CPU flame graph looks the same as last week and CPU is only at its limit for short bursts. What do you check?
Now do it: Read /sys/fs/cgroup/cpu.stat inside a container you run (cgroup v2) and compare nr_throttled across a busy minute.
At the master level profiling is a standing practice, not an emergency tool. A continuous profiler (Parca, Pyroscope, or a cloud profiler) samples production all the time at low overhead, so the flame graph from before a regression is already there to compare against.
Trade-off: always-on profiling costs a little everywhere and saves days in incidents; ad hoc profiling is free until the problem is gone by the time you start.
Try it: Master
After a release, CPU per request rose 15 percent and nobody knows why. What finds it fastest?
Now do it: Pick one service and write down its CPU per request and p99 for the last release. That is the start of a performance budget.
A flame graph is a picture of counted stacks. This script builds the input that flamegraph.pl reads, from 100 sampled stacks, and computes each function's self and total share, which are a frame's width with and without its children. Standard library only; python3 fold_stacks.py.
# fold_stacks.py - what a flame graph is made of: sampled stacks, folded and counted
from collections import Counter
# perf samples every CPU at a fixed rate (here 99 Hz) and records the stack each time.
# Each line is one sample, outermost frame first, like `perf script | stackcollapse-perf.pl`.
samples = (
["main;serve;handle_order;validate;re_match"] * 61
+ ["main;serve;handle_order;price_cart"] * 12
+ ["main;serve;handle_order;json_dumps"] * 9
+ ["main;serve;read_request;sys_read"] * 6
+ ["main;serve;write_response;sys_write"] * 5
+ ["main;gc_collect"] * 7
)
folded = Counter(samples)
print("folded stacks (the input to flamegraph.pl):")
for stack, n in folded.most_common():
print(f" {stack} {n}")
total, leaf, incl = len(samples), Counter(), Counter()
for stack, n in folded.items():
frames = stack.split(";")
leaf[frames[-1]] += n # self time: the function on top of the stack
for f in dict.fromkeys(frames): # each function once per sample
incl[f] += n # total time: anywhere on the stack
print(f"\n{total} samples; width in the flame graph = share of samples")
print("function self total")
for f, _ in incl.most_common():
print(f" {f:<15} {leaf[f] / total:5.0%} {incl[f] / total:5.0%}")
hz, seconds, cpus = 99, 30, 8
print(f"\n{hz} Hz for {seconds} s on {cpus} CPUs = up to {hz * seconds * cpus:,} samples;"
f" a function using 1% of one CPU gets about {hz * seconds // 100} of them")
$ python3 fold_stacks.py folded stacks (the input to flamegraph.pl): main;serve;handle_order;validate;re_match 61 main;serve;handle_order;price_cart 12 main;serve;handle_order;json_dumps 9 main;gc_collect 7 main;serve;read_request;sys_read 6 main;serve;write_response;sys_write 5 100 samples; width in the flame graph = share of samples function self total main 0% 100% serve 0% 93% handle_order 0% 82% validate 0% 61% re_match 61% 61% price_cart 12% 12% json_dumps 9% 9% gc_collect 7% 7% read_request 0% 6% sys_read 6% 6% write_response 0% 5% sys_write 5% 5% 99 Hz for 30 s on 8 CPUs = up to 23,760 samples; a function using 1% of one CPU gets about 29 of them
Read it like this: validate is 61 percent wide but has no self time; the work is in re_match on top of it, so that is what to fix. And 30 seconds at 99 Hz gives a function that uses 1 percent of one CPU only about 29 samples: enough to see it, not enough to measure small changes.
# On a Linux test box with perf, bcc tools, and https://github.com/brendangregg/FlameGraph cloned. # Needs root or CAP_PERFMON / CAP_BPF. Sampling at 99 Hz costs about a percent of CPU. # CPU: what is running perf record -F 99 -a -g -- sleep 30 perf script | ./FlameGraph/stackcollapse-perf.pl > cpu.folded ./FlameGraph/flamegraph.pl cpu.folded > cpu.svg # Off-CPU: where threads sleep, for one process offcputime-bpfcc -df -p "$(pgrep -n orders)" 30 > off.folded ./FlameGraph/flamegraph.pl --color=io --countname=us off.folded > off.svg # Counters for the same process perf stat -e task-clock,context-switches,cpu-migrations,page-faults -p "$(pgrep -n orders)" -- sleep 10
The commands follow perf and bcc as packaged on Ubuntu and Debian (bcc tools carry a -bpfcc suffix there; on other distributions they live in /usr/share/bcc/tools/). Run them on a test box first: perf and eBPF need elevated privileges, and the recording writes files the size of the samples.
This is a composite of a failure pattern that keeps repeating; the numbers are illustrative. An order service's p99 went from 80 ms to 1.5 seconds after a release.
The performance runbook now starts with one line: compare CPU time with wall time, then choose the profile. And the release checklist includes a differential flame graph, on CPU and off CPU, against the previous version under the same load test.
Plan how to find the cause of a 3x p99 regression in a Java checkout service on Kubernetes, without access to change the code until you know the cause.
What changed: the release, the traffic, the node type, the limits? What is CPU time per request against wall time? Is the pod being throttled? Do you have a profile from before the change? What privileges do you have on the nodes?
Say 40 pods with 2-CPU limits, p99 from 120 ms to 360 ms, CPU per request up 5 percent, and wall time up 200 percent.
USE pass per pod and node; cpu.stat for throttling; per-request CPU against wall time showing the regression is off-CPU; an off-CPU flame graph of one pod with offcputime from a privileged debug pod on its node, symbols from async-profiler or a perf map; a differential comparison with the previous release from the continuous profiler; then the fix and a load test to confirm.
Privileged profiling on a production node finds the cause fastest and needs careful access control and a time limit. Async-profiler inside the JVM needs no node privileges and sees only that JVM. Continuous profiling would have made this a five-minute comparison and costs a percent of CPU everywhere, all the time.