Platform Engineering · Lesson 06

Linux Performance Profiling: perf, Flame Graphs, and Off-CPU Time

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

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: on-CPU or off-CPU?

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

2%on CPU
706ms off CPU
off-CPUprofile first

Mostly asleep: make an off-CPU flame graph

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

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.

Basic — Where can a request's time go?

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.

  • CPU: mpstat for utilization, vmstat's r column for saturation.
  • Memory: free -m, and si/so in vmstat for swapping.
  • Disk: 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.

Intermediate — perf and a CPU flame graph

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.
  • 99 Hz rather than 100 avoids sampling in step with timers that fire every 10 ms.
  • 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.

Advanced — Off-CPU time, symbols, and containers

At the advanced level you profile what CPU profilers cannot see, and you get symbols right.

  • Off-CPU: bcc's 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.
  • Language runtimes: perf maps for JIT code (Java, Node), 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.
  • Containers: perf runs on the host and sees container processes; symbol files live inside the container image, so use --symfs or a profiler that resolves symbols from the container's mount namespace.
  • Kubernetes: CPU throttling from limits is off-CPU time too; check 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.

Master — Continuous profiling and performance budgets

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.

  • Differential flame graphs: compare a release with the previous one; the frames that grew are the regression.
  • Performance budgets: CPU per request and p99 latency per endpoint as tracked numbers, with alerts when a release moves them.
  • Overhead: sampling at 19 to 99 Hz costs around a percent; tracing every event costs far more. Choose the cheapest tool that answers the question.
  • Capacity: CPU per request × peak requests a second sets cores; a 20 percent CPU-per-request regression is a 20 percent bigger bill.

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.

Go deeper

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.

From samples to a flame graph's widths

# 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.

Record a CPU and an off-CPU flame graph

# 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.

One time it broke

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.

Timeline

  • Day 1The team takes a CPU flame graph. It looks the same as before the release, so they spend two days optimising JSON encoding, the widest frame, with no effect.
  • Day 3Someone compares wall time with CPU time per request: 1.5 s against 25 ms. The time is not on a CPU at all.
  • Day 3An off-CPU flame graph shows most of the width in futex_wait under a new metrics library that took a global lock on every counter increment. The library is configured to use per-thread counters and p99 returns to 80 ms.

What changed after

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.

If you remember nothing else

Design exercise

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.

Clarifying questions to ask

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?

Rough sizing

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.

Shape of the answer

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.

Trade-offs to name

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.

Saved on this device, in this browser.
Next in this series · Lesson 07
Git

Git is a save system for code. You change a file, you save a snapshot of that change with a short note, and Git remembers every snapshot forever. If a deploy breaks at 2 AM, you can look back through the snapshots, find the exact…

Go to Lesson 07 →

Or browse the full course from the Lessons index.