FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Performance Profiling & Flamegraphs

CPU flamegraphs, off-CPU profiling, stack sampling, and bottleneck identification.

Freshness: current•15 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Generate and analyze CPU flamegraphs using perf
  • ✓Identify off-CPU blocking latency bottlenecks
Full Technical Reference Document

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!

Sample IP + stack frames at 99Hz (perf)
Wait path trace via sched_switch (Off-CPU)
Collapse identical stack paths & counts
Render SVG Flamegraph (Width=Time, Y=Depth)
Optimize wide plateaus (not tall narrow spikes)
Conceptual teaching model synthesized from:Linux Kernel Kernel.org Official Architecture & Systems DocumentationSite Reliability Engineering

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-pointer compilation or --call-graph dwarf,16384 unwinding 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 DimensionWhat Kernel Event Triggers SampleWide Flamegraph Plateau MeansCommon 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 durationThread 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 FlamegraphPage-fault (page_fault_user) or malloc/JIT hooksHigh GC churn / excessive temporary buffer allocations triggering PyMalloc/jemalloc overheadSample 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 bash
set -euo pipefail
​
TARGET_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 30
perf 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 eBPF
offcputime-bpfcc -p "$TARGET_PID" -df 30 > offcpu.folded
flamegraph.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 Chrome flamechart or OpenTelemetry trace instead cleanly!
  • Evaluating Binaries Compiled With -fomit-frame-pointer: Shipping -O3 builds without -fno-omit-frame-pointer collapses 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_switch time!
  • Averaging Idle Epoll Sleep Wait in Off-CPU Profiles: Profiling an idle server logs 99.9% epoll_wait cleanly 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.

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next