Skip to main content

Linux Performance Analysis

Learning objectives
  • Apply the USE method to find the saturated resource instead of guessing
  • Run and interpret the 60-second checklist (uptime through top) on an unfamiliar host
  • Produce and read CPU flame graphs with perf and Go's pprof, and know when you need off-CPU analysis instead
  • Pick the right low-overhead tool (eBPF/bcc, perf trace) over risky ones (strace on 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 -g or 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 and go tool trace.
  • strace is a last resort in production — ptrace can slow the target dramatically. Prefer perf trace and 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​

ResourceUtilisationSaturationErrors
CPUmpstat -P ALL 1 (%usr + %sys), pidstat 1vmstat 1 r > CPU count; /proc/pressure/cpu; runqlatdmesg (machine checks); in containers cpu.stat nr_throttled
Memoryfree -m (available), memory.currentvmstat si/so (swapping), /proc/pressure/memory, sar -B (pgscan)dmesg OOM-killer messages, memory.events oom_kill
Diskiostat -xz 1 (%util — HDD only meaningful)aqu-sz, r_await/w_await, /proc/pressure/iodmesg I/O errors, smartctl -a
Networksar -n DEV 1 (rx/tx kB/s vs link speed)ss -tn Recv-Q/Send-Q, nstat drops/overflows, netstat -s listen overflowssar -n EDEV 1, ip -s link, sar -n ETCP 1 retransmits
File descriptorsls /proc/PID/fd | wc -l vs limit—"too many open files" in logs
Connection pools (software)In-use / max (sql.DBStats.InUse)WaitCount, WaitDurationTimeouts 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):

CommandWhat you learnRed flags
uptimeLoad averages 1/5/15 min — rising or falling?Load far above CPU count (remember it includes D-state tasks)
dmesg -T | tailKernel messagesOOM kills, TCP SYN floods/drops, I/O errors, hung tasks
vmstat 1Run queue r, blocked b, swap si/so, us/sy/id/wa/str > CPUs (saturation), swapping, high sy, st (steal on VMs)
mpstat -P ALL 1Per-CPU breakdownOne hot CPU (single-threaded bottleneck or IRQ affinity), high %soft
pidstat 1Per-process CPU over time (rolling, unlike top)Which process; %usr vs %system
iostat -xz 1Per-device IOPS, throughput, latency, queueHigh await, aqu-sz > 1 sustained, IOPS at a round-number cap
free -mMemory and page cacheLow available, swap in use
sar -n DEV 1NIC throughputNear link or instance bandwidth limit
sar -n TCP,ETCP 1Active/passive connections per second, retransmitsRetransmits (network or overloaded peer)
topOverall sanity checkAnything 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 perf call 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.

QuestionToolNotes
What short-lived processes are spawning?execsnoopCrash-looping sidecars, scripts shelling out
Which files are opened, and failing?opensnoopMissing config, wrong paths, fd churn
Which file system operations are slow?ext4slower, xfsslowerLatency above a threshold, by process
What is the disk I/O latency distribution?biolatencyHistogram; bimodal = cache vs device, or two workloads
Which process issues which disk I/O?biosnoop, biotopPer-I/O, with latency
How effective is the page cache?cachestatHits/misses per second
Which TCP connections are made / accepted?tcpconnect, tcpaccept, tcplifeConnection churn, unexpected destinations
Where are TCP retransmits?tcpretransPer-connection, low overhead (only on retransmit events)
How long do tasks wait to run?runqlat, runqlenScheduler saturation, throttling side effects
Where do threads block?offcputimeOff-CPU stacks — locks, I/O, sleeps
What is sampling the CPU?profileeBPF-based CPU profiler
Who triggered the OOM killer?oomkillVictim and triggering process
Where is native memory allocated and not freed?memleakFor cgo/native leaks; higher overhead
How slow is DNS resolution?gethostlatencylibc 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 URL gives an interactive flame graph; -base old.pb.gz new.pb.gz diffs two profiles (ideal for leaks and regressions).
  • Block and mutex profiles are off by default: enable with runtime.SetBlockProfileRate and runtime.SetMutexProfileFraction.
  • GODEBUG=gctrace=1 prints one line per GC (heap sizes, pause and CPU percentage); GODEBUG=schedtrace=1000 prints scheduler state every second.
  • runtime/metrics exposes /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 trace shows 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 classOverhead (rough)Production safetyChoose when
Counters and metrics (vmstat, sar, /proc, cgroup files, Prometheus)NegligibleAlways safeFirst look, trends, alerting
Sampling profilers (perf -F 99, Go CPU profile)Low, typically a few percent while runningSafe for short windows; continuous at low ratesWhere CPU time goes
eBPF tools (bcc, bpftrace)Low to moderate — depends on event frequencySafe with care; needs privileges and approvalPer-event latency (disk, run queue, TCP) without restarts
Go execution traceModerate during captureShort captures (seconds)Scheduling, GC and blocking analysis of tail latency
strace (ptrace)High — can slow the target many timesRisky on hot servicesStaging, low-rate processes, last resort
tcpdumpModerate; disk-heavy at high ratesOK with filters and snap lengthPacket-level protocol issues
Core dump / gcorePauses the processDisruptivePost-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.

  1. uptime → load 14 on 8 vCPUs; mpstat -P ALL 1 → all CPUs ~85% %usr, %sys low → application code.
  2. pidstat 1 → the checkout process at ~780% CPU. Inside the pod, cpu.stat shows throttling as well (a consequence, not the cause).
  3. CPU profile: go tool pprof -http=:8081 'http://pod:6060/debug/pprof/profile?seconds=30'. The flame graph shows ~35% under regexp.Compile called from the promo-code validator, and ~20% in encoding/json reflection.
  4. Diff against the previous release's profile (-base) → the regex compile is new: the release moved regexp.MustCompile from a package-level variable into the handler.
  5. 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.

  1. Rule out the cheap explanations: cpu.stat shows no throttling; runqlat is fine.
  2. Enable the block profile briefly; /debug/pprof/block shows most waiting in database/sql.(*DB).conn — goroutines waiting for a connection.
  3. db.Stats() (exported as metrics) confirms: InUse = MaxOpenConns = 20, WaitCount rising fast, WaitDuration large.
  4. 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.
  5. 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.

  1. kubectl describe pod → Last State: Terminated, Reason: OOMKilled, Exit Code: 137. memory.events confirms oom_kill increments.
  2. memory.stat → growth is in anon, not file: it is process memory, not page cache.
  3. Compare with Go's view (runtime/metrics total vs heap). Go total tracks RSS → a Go-level leak (if RSS ≫ Go total, suspect cgo/native memory and use bcc memleak).
  4. 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 a map inside the dedupe cache.
  5. /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.
  6. Fix: buffered channel of size 1 or select on ctx.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.

  1. iostat -xz 1 during the window → w_await ≈ 45 ms, aqu-sz ≈ 28, w/s flat at exactly 3,000 — a suspiciously round number: the cloud volume's provisioned IOPS cap.
  2. pidstat -d 1 and biotop → a backup agent and a log-compression job are issuing most of the I/O; biolatency shows a bimodal distribution (fast WAL writes queued behind large backup reads).
  3. /proc/pressure/io "some" > 40% during the window confirms tasks stalled on I/O.
  4. 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 on await and IOPS-vs-cap, not %util.

Common pitfalls​

  • Jumping to tools without a hypothesis. Hours of top and 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 mpstat and vmstat b.
  • Running host-wide tools in a container and drawing pod conclusions. top in a pod shows node CPU; use cgroup files and per-process tools.
  • strace on a hot production process. The tool causes the incident. Prefer perf trace or eBPF.
  • Trusting %util on 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/pprof publicly. It leaks internals and can be used for DoS. Bind it to an internal port or behind auth.
  • Ignoring steal time on VMs. %st in vmstat/mpstat means 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.stat anon vs file, cgo leaks via memleak.
  • 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 strace casually 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.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Run a mini incident drill on a Linux VM (2–4 vCPU).

  1. Write a Go HTTP service with three endpoints and net/http/pprof on 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).
  2. Generate load with hey or a small Go client (e.g. 200 concurrent requests) against each endpoint in turn.
  3. For each, run the 60-second checklist and record what each command shows. Then:
    • /cpu: capture a CPU profile and a perf record -F 99 -g flame graph; compare them.
    • /db: show that CPU is low; capture block profile and go 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.
  4. Generate disk load with fio in the background and capture iostat -xz 1 and biolatency output.
  5. 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​

Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).