Skip to content
$ lynuxpro
← Linux

LESSON 24 OF 26 · EXPERT · 21 MIN

Performance analysis with perf and eBPF

In one minute

  • Expert tools that find exactly why something is slow: which function uses the CPU, which file causes disk work, which request waits inside the kernel.
  • Basic tools tell you that the CPU or disk is busy. These tools tell you why. They are the same toolkit performance engineers at large tech companies use.
  • First, the USE method finds which resource is the bottleneck. Then perf takes thousands of quick snapshots of what the CPU is doing, and a flame graph turns them into one picture. eBPF tools run tiny, safe programs inside the kernel to watch events with very little slowdown.
  • 👉 When the basic checklist shows a resource is busy, but not what is causing it, and for slowness that comes and goes.

Think of it like: a doctor. The basic checks (temperature, pulse) say you are sick. A scan (perf, eBPF) shows exactly which part is the problem.

The USE method

A simple checklist: for every resource, check three things. (It comes from Brendan Gregg, a well-known performance engineer.)

MeaningCPU exampleDisk example
UtilizationHow busy is it?%CPU in top, mpstat%util in iostat
SaturationIs work waiting in a queue?Run queue (r in vmstat)aqu-sz in iostat
ErrorsIs anything failing?RareIO errors in dmesg

Go through CPU, memory, disk and network, and check U, S and E for each. You will rarely miss the bottleneck.

Think of it like: a motorway. Utilization = how many lanes are full. Saturation = how long the traffic jam is. Errors = crashes.

Tools for each resource

mpstat -P ALL 1          # per-CPU utilization: one core at 100% means a single-threaded bottleneckpidstat 1                # per-process CPU over timeiostat -xz 1             # per-disk util, await (latency), queue sizesar -n DEV 1             # network throughput per interfacesar -q 1                 # run queue and load history
OUTPUTterminalutf-8 · 5L

These come from the sysstat package. sar can also record history, so you can see what happened at 3 a.m. while you were asleep.

Reading iostat -xz

ColumnHealthyWorry when
r/s, w/s (reads/writes per second)AnyClose to the disk's IOPS limit
r_await, w_await (wait time)A few ms on SSDTens of ms or more
aqu-sz (queue size)Below 1Always above what the disk can handle at once
%utilUnder 70%Near 100% on HDDs (less meaningful on NVMe)

On AWS: gp3 disks have a set IOPS and throughput allowance. Hitting it looks like high wait time and queue size, while %util looks only moderate.

CPU profiling with perf

perf takes many snapshots per second of what the CPU is running.

👉 You know a process uses lots of CPU and want to know which part of its code.

sudo perf top                                  # live view of the hottest functionssudo perf stat -p 2211 sleep 10                # counters: cycles, instructions, context switchessudo perf record -F 99 -g -p 2211 -- sleep 30  # sample stacks at 99 Hz for 30 ssudo perf report                               # browse the recorded profile
OUTPUTterminalutf-8 · 4L
FlagMeaning
-F 99Snapshots per second (99, not 100, so it does not line up with timers)
-gAlso record which function called which (the call stack)
-p PID / -aOne process / the whole system

For Java, Node.js and Python: these languages compile code while running, which hides function names. Turn on symbol maps (for Java, -XX:+PreserveFramePointer with perf-map-agent, or use async-profiler) to get readable names.

Flame graphs

A flame graph turns thousands of perf snapshots into one picture.

You see in seconds where the time goes, instead of reading thousands of lines.

sudo perf record -F 99 -a -g -- sleep 30sudo perf script | stackcollapse-perf.pl | flamegraph.pl > cpu.svg
OUTPUTterminalutf-8 · 2L

How to read it:

  • Each box is a function. Width = share of CPU time. Wider = more time.
  • Stacks grow upward. The top edge is what was actually running.
  • Look for wide flat tops. Those functions are where the time goes.
  • Colours are usually random and mean nothing.

Remember it: Wide = slow. Height = just how deep the calls go.

One flame graph often finds in minutes what days of guessing could not: a slow JSON converter, logging inside a busy loop, a lock, or a slow regex.

eBPF: safe programs inside the kernel

eBPF lets you run tiny programs inside the kernel to watch events: system calls, disk reads, network packets, function calls.

Why it is safe for production: the kernel checks every eBPF program before running it, and the slowdown is very small.

Where you meet it: it powers modern tools such as Cilium (Kubernetes networking), Falco (security), Pixie and Parca (observability), and always-on profilers.

Think of it like: fitting tiny, harmless sensors inside an engine while it runs, instead of stopping the car to open the bonnet.

Ready-made eBPF tools

These come in the bpfcc-tools package on Ubuntu (their names end in -bpfcc):

ToolAnswers
execsnoopWhich programs are being started (even short ones top misses)
opensnoopWhich files are being opened, and which fail
biolatencyHow long disk reads and writes take
biosnoopEach disk read/write, with the program and how long it took
tcpconnect / tcpacceptNew outgoing / incoming TCP connections
tcpretransTCP packets sent again (a sign of network trouble)
runqlatHow long tasks wait for a CPU
profileLow-cost CPU sampling
oomkillDetails of each OOM kill
sudo execsnoop-bpfccsudo biolatency-bpfcc 10 1sudo tcpretrans-bpfcc
OUTPUTterminalutf-8 · 3L

A classic first step on a busy server: execsnoop. Often a cron job or health check is starting thousands of tiny programs per second, and top never shows them because they finish too fast.

bpftrace one-liners

sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat { printf("%s %s\n", comm, str(args->filename)); }'sudo bpftrace -e 'tracepoint:block:block_rq_issue { @bytes[comm] = sum(args->bytes); }'
OUTPUTterminalutf-8 · 2L
  1. Print every file opened, and by which program.
  2. Add up disk bytes per program, until you press Ctrl+C.

A performance investigation, step by step

  1. Define the problem: which number got worse, by how much, since when, and for whom?
  2. USE method on every resource, to find the one that is overloaded.
  3. Zoom in with per-process tools (pidstat, iostat, biosnoop).
  4. Profile the busy process (perf, flame graphs, eBPF).
  5. Fix one thing, measure again, and compare with before.

Real-world scenario: slow spikes every few minutes

The slowest requests (p99) jump every five minutes. Averages look fine.

vmstat 1 5iostat -xz 1 3
SHELLbashutf-8 · 2L
  • iostat shows disk write wait (w_await) spiking at the same times.
  • biosnoop shows a log-shipping agent writing big batches to disk every five minutes, fighting with the database's writes on the same disk.

Moving the agent's buffer to a separate disk (or changing how often it writes) removes the spikes.

The lesson: averages hid the problem. Percentiles and per-process disk tracing revealed it.

Common mistakes

  • Optimising without measuring, or without a "before" number to compare.
  • Looking only at averages. Users feel the slowest requests (p99), not the average.
  • Leaving heavy tracing running (strace, high-frequency perf) in production.
  • Guessing instead of profiling. The real slow spot is rarely where people expect.

Practice

  1. Apply the USE method to a disk: name one tool and one column for each of U, S and E.
  2. Explain how to read width and height in a flame graph.
  3. Which eBPF tool would find short-lived programs that top never shows?
  4. Write the perf command to record 30 seconds of call stacks for PID 2211.

Cheat sheet

CommandUse
mpstat -P ALL 1Use of each CPU core
pidstat 1CPU per process over time
iostat -xz 1Disk wait times and queues
perf topBusiest functions, live
perf record -F 99 -g -p PIDRecord CPU call stacks
execsnoop-bpfccNew programs being started
biolatency-bpfccDisk wait-time chart
tcpretrans-bpfccRe-sent TCP packets

Key takeaways

  • The USE method checks every resource for busyness, queues and errors.
  • perf takes snapshots of what the CPU is doing, and a flame graph turns them into a picture.
  • In a flame graph, wider boxes are where the time goes.
  • eBPF tools watch the kernel safely, even in production.
  • Look at the slowest requests (p99), not just averages, and measure before and after each fix.