CPU Profiling and Flame Graphs for Hot Paths
Record CPU profiles and read flame graphs to locate the functions consuming the most time.
Why CPU Profiling Matters
When a Node.js backend feels slow, the cause is usually one of two things: the process is waiting (I/O, database, network) or it is computing (burning CPU on the single main thread). A CPU profile tells you exactly where the second kind of time goes.
- It samples the call stack at a fixed frequency (V8 uses ~1000 Hz, one sample per millisecond).
- Each sample records the function currently executing and its whole stack of callers.
- Functions that appear in many samples are your hot paths — the code worth optimizing.
Because Node.js runs JavaScript on one thread, a single hot function can block every incoming request. Profiling finds it instead of you guessing.
Self Time vs Total Time
Every profiler distinguishes two numbers per function, and confusing them is the most common profiling mistake.
- Self time (a.k.a. exclusive): time spent executing the function's own body, excluding the children it called.
- Total time (a.k.a. inclusive): self time plus all time spent inside callees.
A function high in total time may just be an orchestrator that calls expensive children. The function high in self time is where the CPU actually burns. Optimize by self time first.
All lessons in this course
- The V8 Heap, Generational GC, and Object Lifetimes
- Capturing and Comparing Heap Snapshots
- CPU Profiling and Flame Graphs for Hot Paths
- Detecting and Fixing Common Leak Patterns