Mental model
Guessing performance bottlenecks cleanly from code inspection almost always optimizes the wrong loop. Sampling Flamegraphs capture actual runtime call stacks at low overhead (< 1–2% CPU at 99 Hz), visualizing two unmistakable axes cleanly: horizontal box width (total fraction of sampled time spent inside a function or its children) and vertical stack height (call hierarchy from runtime root upward). Combining On-CPU and Off-CPU views exposes both hot math loops and hidden lock/I/O sleeps!
Learning outcomes
- Read Flamegraph geometry accurately cleanly (
width = cumulative percentage on/off CPU,X-axis ordering is alphabetical NOT chronological time!). - Diagnose why empty
[unknown]flat stacks appear without-fno-omit-frame-pointercompilation or--call-graph dwarf,16384unwinding cleanly. - Pair On-CPU CPU-burn profiling (
perf record) with Off-CPU wait profiling (offcputime-bpfcc) to uncover mutex contention, disk stalls, and slow RPC waits cleanly.
Theory
A classic engineer mistake runs perf (CPU sampling), notices their slow 3-second endpoint uses only 4% CPU total, and stares helplessly at flat empty graphs cleanly! Why? perf samples solely threads running on CPU cores (TASK_RUNNING), staying completely invisible while threads block silently (TASK_INTERRUPTIBLE / TASK_UNINTERRUPTIBLE) waiting on Postgres locks, mutex contention, NVMe fsync(), or upstream LLM sockets! Contrasting both profiles makes bottlenecks unmistakable cleanly:
| Profiling Dimension | What Kernel Event Triggers Sample | Wide Flamegraph Plateau Means | Common Runtime Pitfall & Cure |
|---|---|---|---|
On-CPU Sampling (perf record -F 99) | Hardware PMU / timer tick at odd 99 Hz (avoids lockstep beat alias against 100 Hz ticks!) | Active CPU cycle hotspot (JSON serialize, BPE regex, GEMM, kernel copy) | Broken [unknown] stacks without -fno-omit-frame-pointer |
Off-CPU Blocking (offcputime) | Kernel context switches (sched:sched_switch) measuring sleep duration | Thread blocked waiting cleanly (futex mutex lock, slow DB read, disk I/O, DNS) | Tracking idle background worker pool wait calls unless filtering target PIDs & running active requests |
| Memory Allocation Flamegraph | Page-fault (page_fault_user) or malloc/JIT hooks | High GC churn / excessive temporary buffer allocations triggering PyMalloc/jemalloc overhead | Sample allocations above clean byte thresholds (e.g. ebpf malloc stacks) |
Interpreted / JIT Runtimes (Python / V8) | C stack + Python VM frames (perf --call-graph Python 3.12 -X perf / Node --perf-basic-prof) | Disambiguates PyEval_EvalFrame into actual chunk_docs() line names! | Seeing generic opaque libpython.so frames unless -X perf or py-spy is enabled |
Notice why 99 Hz (odd prime-like frequency) matters cleanly: sampling at round 100 Hz risks locking into synchronization beats cleanly with 10 ms periodic OS/scheduler loops (lockstep bias), hiding or magnifying costs artificially!
bash#!/usr/bin/env bashset -euo pipefailTARGET_PID="${1:?Usage: profile.sh <PID>}"# 1. On-CPU 30-second sampling cleanly at 99Hz with frame pointers (Python 3.12+ run with PYTHONPERFSUPPORT=1)perf record -F 99 -p "$TARGET_PID" -g --call-graph fp -- sleep 30perf script | stackcollapse-perf.pl | flamegraph.pl --title="On-CPU Profile" > oncpu.svg# 2. If endpoint is slow yet CPU idle -> Off-CPU kernel context-switch stall profile cleanly via eBPFoffcputime-bpfcc -p "$TARGET_PID" -df 30 > offcpu.foldedflamegraph.pl --color=io --title="Off-CPU Blocking Latency" offcpu.folded > offcpu.svg
Trade-offs
Production sampling (99 Hz perf, py-spy, eBPF offcputime) preserves clean 1–2% runtime impact while capturing genuine multi-language bottlenecks spanning Python/Node glue straight down into C/C++ libraries and Linux kernel networking/locks without rebuilding binaries around invasive instrumentation counters. Exact micro-benchmarks (pytest-benchmark, Criterion) uncover nanosecond L1 cache stalls cleanly inside tight loops yet distort real multi-threaded I/O blocking and scheduler lock contention completely unless paired with production flamegraphs cleanly.
Failure modes and misconceptions
- Reading X-Axis Left-to-Right as Chronological Timeline: Flamegraph stack frames group lexicographically alphabetically cleanly (
not over time!)—to trace timeline waterfalls cleanly use a Chromeflamechartor OpenTelemetry trace instead cleanly! - Evaluating Binaries Compiled With
-fomit-frame-pointer: Shipping-O3builds without-fno-omit-frame-pointercollapses call chains cleanly into flat[unknown]roots; modern Linux distros (Ubuntu 24.04+,Fedora) increasingly enable frame pointers system-wide cleanly for this exact reason. - Debugging Idle Async I/O Latencies Strictly With On-CPU Flamegraphs: Missing slow network fetches, threadpool queue waits, and PostgreSQL row locks completely until Off-CPU wait tracing inspects
sched_switchtime! - Averaging Idle Epoll Sleep Wait in Off-CPU Profiles: Profiling an idle server logs
99.9% epoll_waitcleanly unless profiling strictly under active test traffic or filtering non-blocking reactor idle waits cleanly.
Decision scenario
A Rust/Python hybrid embedding microservice averages 1.9s P95 latency cleanly while htop reports only 18% CPU usage! Standard CPU perf shows shallow tokenization ticks and 80% unknown frames inside a C++ PDF dependency. Recompile the extension cleanly with -fno-omit-frame-pointer, enable Python -X perf / py-spy, capture an Off-CPU Flamegraph (offcputime-bpfcc), and pinpoint the exact blocking disk fsync() mutex stall immediately cleanly.