Linux Performance Analysis
- Apply the USE method to find the saturated resource instead of guessing
- Run and interpret the 60-second checklist (
uptimethroughtop) on an unfamiliar host - Produce and read CPU flame graphs with
perfand Go'spprof, and know when you need off-CPU analysis instead - Pick the right low-overhead tool (eBPF/bcc,
perf trace) over risky ones (straceon a hot process) - Lead an investigation for high CPU, high latency with low CPU, memory leaks and disk saturation in a Go service
TL;DR
- Start with a method, not a tool. USE: for every resource, check Utilisation, Saturation and Errors. For request-serving services, pair it with RED (Rate, Errors, Duration).
- The 60-second checklist —
uptime,dmesg | tail,vmstat 1,mpstat -P ALL 1,pidstat 1,iostat -xz 1,free -m,sar -n DEV 1,sar -n TCP,ETCP 1,top— localises most problems to CPU, memory, disk or network quickly. - On-CPU problems (CPU is busy): sample stacks with
perf record -F 99 -gor Go's CPU profile and read a flame graph — width is time, find the widest frames. - Off-CPU problems (latency high, CPU low): the time is spent waiting — CFS throttling, run-queue delay, locks, connection pools, disk, network, DNS. Use
cpu.stat,runqlat,offcputime, Go block/mutex profiles andgo tool trace. straceis a last resort in production — ptrace can slow the target dramatically. Preferperf traceand eBPF tools (biolatency,tcpretrans,execsnoop,opensnoop,runqlat).- In containers, read cgroup files (
cpu.stat,memory.events,memory.stat,io.stat,*.pressure) — host-wide tools show the node, not your pod.
Why it matters
During a flash sale, checkout p99 goes from 80 ms to 2 s. The war room has 15 people and a dozen dashboards. One engineer restarts pods, another bumps replicas, a third suggests rolling back — all guesses. The architect who can say "CPU is at 30% but nr_throttled is climbing on every checkout pod and run-queue latency is 40 ms — we are being CFS-throttled; raise the limit or GOMAXPROCS is wrong" ends the incident in ten minutes.
Banks have the same need with stricter constraints: production access is audited, tools must be safe on systems processing payments, and the post-incident report must show evidence, not hunches. Interviewers probe this with "the service is slow — what do you do?" and expect a structured method, specific commands and a hypothesis-driven drill-down.
Core concepts
Methodologies
- USE method (Brendan Gregg): for every resource — CPUs, memory, disks, network interfaces, controllers, and software resources such as locks, thread pools and connection pools — check:
- Utilisation: the fraction of time busy (or capacity used).
- Saturation: extra work queued that can't be serviced (run queue, swap, disk queue, pool wait count).
- Errors: error counts (dropped packets, I/O errors, OOM kills, throttling events).
- RED method (Tom Wilkie) for services: request Rate, Errors, Duration distribution. RED tells you which service hurts; USE tells you which resource inside it.
- Anti-methods to avoid: the streetlight method (use the tools you know and look where it's easy), random changes ("let's tune the GC"), and blaming someone else's component without evidence.
- Drill-down: start broad (system), narrow to a process, a thread, a code path; at each step form a hypothesis and test it.
USE checklist for Linux
| Resource | Utilisation | Saturation | Errors |
|---|---|---|---|
| CPU | mpstat -P ALL 1 (%usr + %sys), pidstat 1 | vmstat 1 r > CPU count; /proc/pressure/cpu; runqlat | dmesg (machine checks); in containers cpu.stat nr_throttled |
| Memory | free -m (available), memory.current | vmstat si/so (swapping), /proc/pressure/memory, sar -B (pgscan) | dmesg OOM-killer messages, memory.events oom_kill |
| Disk | iostat -xz 1 (%util — HDD only meaningful) | aqu-sz, r_await/w_await, /proc/pressure/io | dmesg I/O errors, smartctl -a |
| Network | sar -n DEV 1 (rx/tx kB/s vs link speed) | ss -tn Recv-Q/Send-Q, nstat drops/overflows, netstat -s listen overflows | sar -n EDEV 1, ip -s link, sar -n ETCP 1 retransmits |
| File descriptors | ls /proc/PID/fd | wc -l vs limit | — | "too many open files" in logs |
| Connection pools (software) | In-use / max (sql.DBStats.InUse) | WaitCount, WaitDuration | Timeouts acquiring a connection |
The 60-second checklist
Brendan Gregg's list from the Netflix Tech Blog post "Linux Performance Analysis in 60,000 Milliseconds" (2015):
| Command | What you learn | Red flags |
|---|---|---|
uptime | Load averages 1/5/15 min — rising or falling? | Load far above CPU count (remember it includes D-state tasks) |
dmesg -T | tail | Kernel messages | OOM kills, TCP SYN floods/drops, I/O errors, hung tasks |
vmstat 1 | Run queue r, blocked b, swap si/so, us/sy/id/wa/st | r > CPUs (saturation), swapping, high sy, st (steal on VMs) |
mpstat -P ALL 1 | Per-CPU breakdown | One hot CPU (single-threaded bottleneck or IRQ affinity), high %soft |
pidstat 1 | Per-process CPU over time (rolling, unlike top) | Which process; %usr vs %system |
iostat -xz 1 | Per-device IOPS, throughput, latency, queue | High await, aqu-sz > 1 sustained, IOPS at a round-number cap |
free -m | Memory and page cache | Low available, swap in use |
sar -n DEV 1 | NIC throughput | Near link or instance bandwidth limit |
sar -n TCP,ETCP 1 | Active/passive connections per second, retransmits | Retransmits (network or overloaded peer) |
top | Overall sanity check | Anything that contradicts what you saw above |
Annotated vmstat example (illustrative numbers):
$ vmstat 1
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
14 0 0 812340 20480 22026112 0 0 0 120 9120 41000 82 12 6 0 0
13 0 0 811904 20480 22026240 0 0 0 96 9054 40210 84 11 5 0 0
# r=14 on an 8-vCPU VM: CPU saturation. us=82: application code, not the kernel.
# si/so=0: no swapping. wa=0: not waiting on disk. Next step: pidstat, then profile.
perf and flame graphs
perf (linux-tools) uses hardware counters and kernel sampling.
perf stat -a -- sleep 10 # cycles, instructions, IPC, context switches
perf top -g # live hottest functions
perf record -F 99 -a -g -- sleep 30 # sample all CPUs at 99 Hz with call stacks
perf script > out.perf # dump samples
./stackcollapse-perf.pl out.perf | ./flamegraph.pl > cpu.svg # Gregg's FlameGraph scripts
perf record -F 99 -g -p "$(pgrep -n checkout)" -- sleep 30 # one process
perf sched record -- sleep 5 && perf sched latency # scheduler delays
- 99 Hz (not 100) avoids sampling in lockstep with timer-driven activity.
- IPC (instructions per cycle) from
perf stat: values well below 1 usually mean memory stalls (cache/TLB misses); higher values mean instruction-bound work. It tells you whether to optimise algorithms or data layout. - Go and perf: Go binaries keep frame pointers on amd64 (and on arm64 in recent releases), so
perfcall stacks work without extra flags; symbols resolve if the binary isn't stripped (or keep an unstripped copy for symbolisation). In containers, run perf from the node and point it at the binary via/proc/PID/root.
Reading a flame graph: the y-axis is stack depth (callers below, callees above); the x-axis is the population of samples sorted alphabetically — not time. Width is proportional to time on-CPU. Look for wide frames at the top (functions burning CPU themselves) and wide "towers" (code paths); colours are usually not meaningful. A differential flame graph compares before/after a release.
Off-CPU flame graphs (bcc offcputime, or Go block profiles) show where threads wait — the complement you need when CPU is low but latency is high.
strace and friends
strace -c -f -p "$(pgrep -n checkout)" # syscall counts and time; Ctrl-C to stop
strace -f -tt -T -e trace=network -p PID # timestamps and duration per call
strace -f -e trace=%file -o /tmp/trace.txt ./app # file-related syscalls of a new process
perf trace -p PID --duration 10 # lower-overhead syscall tracing (ms threshold)
strace uses ptrace: the target stops on every syscall entry and exit and the tracer copies arguments. On a syscall-heavy service this can slow the process by an order of magnitude or more — enough to trigger timeouts and failovers. Use it in staging, on low-rate processes, or briefly with -e filters; prefer perf trace or eBPF in production.
eBPF and bcc at a glance
eBPF runs verified, sandboxed programs inside the kernel on events (tracepoints, kprobes, uprobes, perf events), aggregating in kernel memory so overhead stays low. bcc ships ready-made tools (on Ubuntu named like biolatency-bpfcc); bpftrace is a one-liner language.
| Question | Tool | Notes |
|---|---|---|
| What short-lived processes are spawning? | execsnoop | Crash-looping sidecars, scripts shelling out |
| Which files are opened, and failing? | opensnoop | Missing config, wrong paths, fd churn |
| Which file system operations are slow? | ext4slower, xfsslower | Latency above a threshold, by process |
| What is the disk I/O latency distribution? | biolatency | Histogram; bimodal = cache vs device, or two workloads |
| Which process issues which disk I/O? | biosnoop, biotop | Per-I/O, with latency |
| How effective is the page cache? | cachestat | Hits/misses per second |
| Which TCP connections are made / accepted? | tcpconnect, tcpaccept, tcplife | Connection churn, unexpected destinations |
| Where are TCP retransmits? | tcpretrans | Per-connection, low overhead (only on retransmit events) |
| How long do tasks wait to run? | runqlat, runqlen | Scheduler saturation, throttling side effects |
| Where do threads block? | offcputime | Off-CPU stacks — locks, I/O, sleeps |
| What is sampling the CPU? | profile | eBPF-based CPU profiler |
| Who triggered the OOM killer? | oomkill | Victim and triggering process |
| Where is native memory allocated and not freed? | memleak | For cgo/native leaks; higher overhead |
| How slow is DNS resolution? | gethostlatency | libc resolver calls; Go's pure-Go resolver isn't traced by it |
# Count syscalls by process name for 10 s
bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); } interval:s:10 { exit(); }'
# Histogram of read() sizes for one process
bpftrace -e 'tracepoint:syscalls:sys_exit_read /pid == 4242/ { @bytes = hist(args->ret); }'
eBPF needs root (or CAP_BPF/CAP_PERFMON on newer kernels) and kernel BTF/headers; on managed Kubernetes, run it from a privileged debug pod on the node, with change approval in regulated environments.
Where each tool looks
Go's built-in observability
import _ "net/http/pprof"on an internal-only port exposes/debug/pprof/— CPU (profile?seconds=30),heap,allocs,goroutine,block,mutex,threadcreate,trace.go tool pprof -http=:8081 URLgives an interactive flame graph;-base old.pb.gz new.pb.gzdiffs two profiles (ideal for leaks and regressions).- Block and mutex profiles are off by default: enable with
runtime.SetBlockProfileRateandruntime.SetMutexProfileFraction. GODEBUG=gctrace=1prints one line per GC (heap sizes, pause and CPU percentage);GODEBUG=schedtrace=1000prints scheduler state every second.runtime/metricsexposes/sched/latencies:seconds(time goroutines wait runnable — Go's own run-queue latency), GC CPU classes and memory classes; export them to Prometheus.go tool traceshows per-goroutine scheduling, syscalls, GC and network blocking on a timeline — the best tool for "why did this request take 300 ms with idle CPU".- Continuous profiling (Pyroscope, Parca, cloud profilers) keeps low-rate profiles all the time, so you can look at the incident window after the fact. Details in Profiling & Performance.
Trade-offs
| Tool class | Overhead (rough) | Production safety | Choose when |
|---|---|---|---|
Counters and metrics (vmstat, sar, /proc, cgroup files, Prometheus) | Negligible | Always safe | First look, trends, alerting |
Sampling profilers (perf -F 99, Go CPU profile) | Low, typically a few percent while running | Safe for short windows; continuous at low rates | Where CPU time goes |
| eBPF tools (bcc, bpftrace) | Low to moderate — depends on event frequency | Safe with care; needs privileges and approval | Per-event latency (disk, run queue, TCP) without restarts |
| Go execution trace | Moderate during capture | Short captures (seconds) | Scheduling, GC and blocking analysis of tail latency |
strace (ptrace) | High — can slow the target many times | Risky on hot services | Staging, low-rate processes, last resort |
tcpdump | Moderate; disk-heavy at high rates | OK with filters and snap length | Packet-level protocol issues |
Core dump / gcore | Pauses the process | Disruptive | Post-mortem of crashes or hangs |
In practice
Investigation 1 — high CPU after a release
Symptom: checkout API CPU from 40% to 90% after deploy; p99 up 3×; HPA scaling out.
uptime→ load 14 on 8 vCPUs;mpstat -P ALL 1→ all CPUs ~85%%usr,%syslow → application code.pidstat 1→ thecheckoutprocess at ~780% CPU. Inside the pod,cpu.statshows throttling as well (a consequence, not the cause).- CPU profile:
go tool pprof -http=:8081 'http://pod:6060/debug/pprof/profile?seconds=30'. The flame graph shows ~35% underregexp.Compilecalled from the promo-code validator, and ~20% inencoding/jsonreflection. - Diff against the previous release's profile (
-base) → the regex compile is new: the release movedregexp.MustCompilefrom a package-level variable into the handler. - Fix: compile once at init; consider a cheaper validator. Verify: CPU back to 40%, flame graph plateau gone.
Variants: if %sys dominated, check the syscall mix (perf trace -s, strace -c briefly) — often unbuffered small writes or excessive futex wakeups; if GC dominated (gctrace shows GC CPU ≥ 25%, runtime.mallocgc wide in the profile), reduce allocations or tune GOGC/GOMEMLIMIT (see Memory Management).
Investigation 2 — high latency with low CPU
Symptom: payment-status API p99 900 ms (normally 60 ms); CPU 25%; no errors.
- Rule out the cheap explanations:
cpu.statshows no throttling;runqlatis fine. - Enable the block profile briefly;
/debug/pprof/blockshows most waiting indatabase/sql.(*DB).conn— goroutines waiting for a connection. db.Stats()(exported as metrics) confirms:InUse=MaxOpenConns= 20,WaitCountrising fast,WaitDurationlarge.- Why are connections held? The DB slow-query log shows a new report query holding connections for 2 s each. Little's law: 300 req/s × 0.06 s ≈ 18 connections normally — any slow query exhausts a pool of 20.
- Fix: index the query and move reports to a replica; set per-query timeouts via
context; size the pool from Little's law with headroom; alert on pool wait time.
Other common off-CPU culprits: TCP retransmits to a dependency (tcpretrans, sar -n ETCP), DNS latency (Kubernetes ndots:5 turning each external lookup into several queries), lock contention (mutex profile, offcputime), and synchronous logging to a slow disk.
Investigation 3 — memory leak
Symptom: notification worker OOMKilled every ~6 hours; memory grows linearly.
kubectl describe pod→Last State: Terminated, Reason: OOMKilled, Exit Code: 137.memory.eventsconfirmsoom_killincrements.memory.stat→ growth is inanon, notfile: it is process memory, not page cache.- Compare with Go's view (
runtime/metricstotal vs heap). Go total tracks RSS → a Go-level leak (if RSS ≫ Go total, suspect cgo/native memory and use bccmemleak). - Take two heap profiles 30 minutes apart and diff:
go tool pprof -base heap1.pb.gz heap2.pb.gz→ growth in goroutine stacks and in amapinside the dedupe cache. /debug/pprof/goroutine?debug=1→ 180,000 goroutines parked on the same channel send. Each request starts a goroutine that sends its result on an unbuffered channel; when the caller times out and returns, nobody receives, and the goroutine (plus everything it references) lives forever.- Fix: buffered channel of size 1 or
selectonctx.Done(); add a size bound and TTL to the dedupe cache; alert on goroutine count. Verify with a 12-hour soak test showing flat memory and goroutines.
Investigation 4 — disk saturation
Symptom: ledger database commit latency spikes from 2 ms to 50 ms every night between 02:00 and 02:30; transfer API timeouts.
iostat -xz 1during the window →w_await≈ 45 ms,aqu-sz≈ 28,w/sflat at exactly 3,000 — a suspiciously round number: the cloud volume's provisioned IOPS cap.pidstat -d 1andbiotop→ a backup agent and a log-compression job are issuing most of the I/O;biolatencyshows a bimodal distribution (fast WAL writes queued behind large backup reads)./proc/pressure/io"some" > 40% during the window confirms tasks stalled on I/O.- Fix: take backups from a replica or via storage snapshots; throttle batch jobs with cgroup
io.max(or move them to a separate volume); put the WAL on its own low-latency volume; provision IOPS for peak plus headroom. Alert onawaitand IOPS-vs-cap, not%util.
Common pitfalls
- Jumping to tools without a hypothesis. Hours of
topand dashboards; no conclusion. Use USE/RED to decide what to look at next. - Reading load average as CPU usage. D-state tasks inflate it; confirm with
mpstatandvmstatb. - Running host-wide tools in a container and drawing pod conclusions.
topin a pod shows node CPU; use cgroup files and per-process tools. straceon a hot production process. The tool causes the incident. Preferperf traceor eBPF.- Trusting
%utilon SSD/NVMe and RAID. It reports "busy at least one I/O", not saturation. Use latency and queue depth. - Profiling for too short or at the wrong time. A 5-second profile outside the spike shows nothing. Use continuous profiling or trigger profiles on alert.
- Exposing
/debug/pprofpublicly. It leaks internals and can be used for DoS. Bind it to an internal port or behind auth. - Ignoring steal time on VMs.
%stinvmstat/mpstatmeans the hypervisor gave your vCPU to someone else; no code change will fix it. - Fixing the symptom. Adding replicas for a connection-pool problem multiplies connections to the database and makes it worse.
Interview angle
- "A service is slow. What do you do?" — describe the method (RED to find the service, USE to find the resource), the first commands you run, on-CPU vs off-CPU branches, and how you confirm a hypothesis before changing anything. Mention containers (cgroup throttling, memory events).
- "CPU is low but latency is high" is the most common follow-up. Expect to list: throttling, run-queue delay, locks, pool exhaustion, I/O, network retransmits, DNS, GC pauses, downstream latency — and the tool for each.
- "How do you find a memory leak in Go?" — heap profile diff, goroutine count,
memory.statanon vs file, cgo leaks viamemleak. - Bonus points: Little's law for pools and queues; knowing the 60-second checklist; mentioning safe-in-production tooling and audit constraints in banks.
- Red flags: "I'd add more pods"; "I'd restart it" as the first step without capturing evidence; not knowing what a flame graph's x-axis means; using
stracecasually in production.
Self-check
1. Explain the USE method and apply it to a database connection pool.
For each resource, check utilisation, saturation and errors. For a connection pool: utilisation = connections in use / max open; saturation = goroutines waiting for a connection (WaitCount, WaitDuration); errors = timeouts or failures acquiring a connection. High saturation with full utilisation means the pool (or the database behind it) is the bottleneck.
2. In vmstat 1 you see r = 3, b = 25, wa = 40 on an 8-CPU host. What is happening and what do you run next?
Few tasks are runnable but 25 are blocked in uninterruptible sleep, and CPUs spend 40% of their time idle waiting for I/O: storage is the bottleneck. Next: iostat -xz 1 for device latency and queue depth, pidstat -d 1 or biotop for which processes issue I/O, dmesg for I/O errors, and /proc/pressure/io.
3. How do you read the x-axis and width of a CPU flame graph?
The x-axis is not time: stacks are sorted alphabetically and merged, so adjacent boxes are unrelated in time. Width is proportional to the number of samples containing that frame — i.e. share of on-CPU time. Wide frames at the top of a tower are where CPU is spent directly; wide frames lower down are code paths whose callees consume the time.
4. Why is strace risky in production, and what do you use instead?
strace relies on ptrace, which stops the target on every syscall entry and exit and copies data to the tracer, slowing syscall-heavy processes dramatically and potentially causing timeouts or failovers. Prefer perf trace (kernel-side buffering) or eBPF tools (bpftrace, bcc syscount, opensnoop), which aggregate in the kernel with far lower overhead.
5. p99 latency is high, CPU is 20%, and there are no errors. List four hypotheses and the evidence that confirms each.
CFS throttling — cpu.stat nr_throttled/throttled_usec rising. Connection-pool exhaustion — Go block profile in database/sql, WaitCount rising. Lock contention — mutex profile or offcputime stacks in sync.(*Mutex).Lock. Network problems — tcpretrans/sar -n ETCP retransmits, or DNS latency. Also possible: GC pauses (gctrace, go tool trace), slow disk for synchronous logging (biolatency), downstream latency (traces).
6. Scenario: a Go service's RSS grows steadily but heap profiles show a stable live heap. What could it be?
Memory outside the Go heap: cgo/native allocations (C libraries, some drivers) — use memleak; growing goroutine stacks (check goroutine count); memory the runtime freed but hasn't returned to the OS yet (compare runtime/metrics released vs heap); mmap'd files counted in RSS; or kernel-side memory (socket buffers) charged to the cgroup. Compare memory.stat anon/file/sock with Go's runtime/metrics classes to separate them.
Exercise
Run a mini incident drill on a Linux VM (2–4 vCPU).
- Write a Go HTTP service with three endpoints and
net/http/pprofon port 6060:/cpu(hashes a buffer for 20 ms),/db(acquires a slot from a buffered channel of size 4 — a fake pool — and sleeps 50 ms), and/leak(starts a goroutine that sends on an unbuffered channel nobody reads). - Generate load with
heyor a small Go client (e.g. 200 concurrent requests) against each endpoint in turn. - For each, run the 60-second checklist and record what each command shows. Then:
/cpu: capture a CPU profile and aperf record -F 99 -gflame graph; compare them./db: show that CPU is low; capture block profile andgo tool trace; compute the expected throughput with Little's law (4 slots / 50 ms = 80 req/s) and compare with what you measure./leak: watch goroutine count and RSS; diff two heap/goroutine profiles.
- Generate disk load with
fioin the background and captureiostat -xz 1andbiolatencyoutput. - Write a one-page "incident report" for one scenario: timeline, evidence, root cause, fix, prevention (alert you would add).
Done looks like: saved command outputs and profiles for all three endpoints, the flame graph SVG, and the incident report.
Further reading
- Brendan Gregg, Systems Performance: Enterprise and the Cloud (2nd ed., 2020) — methodologies, CPU, memory, file systems, disks, network
- Brendan Gregg, BPF Performance Tools (2019) — the bcc/bpftrace tool catalogue in depth
- Brendan Gregg, "The USE Method": https://www.brendangregg.com/usemethod.html
- Brendan Gregg, "Flame Graphs": https://www.brendangregg.com/flamegraphs.html
- Netflix Tech Blog, "Linux Performance Analysis in 60,000 Milliseconds" (2015)
- Go documentation, "Diagnostics": https://go.dev/doc/diagnostics
- bcc tools repository: https://github.com/iovisor/bcc
Related
- Profiling & Performance — pprof, benchmarks and optimisation in Go
- Observability & SLOs — metrics, traces and alerting that point you to the right host
- Network Troubleshooting —
ss,tcpdumpand network-side diagnosis - CPU Scheduling — throttling, run queues and load average explained
- Memory Management — OOM kills, page cache and GOMEMLIMIT
- File Systems & Durable Storage — IOPS, latency and fsync behaviour behind disk symptoms
- Query Optimization — when the investigation ends at a slow query
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).