CPU Profiling & --inspect
Node.js provides a built-in V8 inspector accessible via `node --inspect` or `node --inspect-brk`. Connect Chrome DevTools to profile CPU usage, take heap snapshots, and debug breakpoints.
CPU profiling is like a sports replay camera that snapshots the call stack every microsecond. The flame graph is a totem pole of function calls—wider blocks ate more CPU time. --inspect opens the VIP skybox (Chrome DevTools), but watching the game from the skybox changes how the players perform (observer effect).
CPU profiling records which functions consume CPU time using V8's sampling profiler (samples the call stack at ~100μs intervals). The flame graph view shows call hierarchies with width proportional to CPU time consumed. Common bottlenecks: hot JSON.parse/stringify, synchronous regex in request handlers, ORM query building overhead. Clinic.js (node-clinic) provides higher-level profiling tools: clinic doctor (detects event loop lag, I/O issues), clinic flame (flame graphs), clinic bubbleprof (async operation visualization).
V8's profiler operates in two modes: (1) tick-based sampling (--prof flag generates a v8.log file, processed with node --prof-process) for minimal overhead profiling; (2) inspector protocol-based profiling (used by Chrome DevTools) with more overhead but better developer experience. The --prof output identifies 'unoptimized' and 'deopted' functions—functions V8 couldn't optimize, often due to inconsistent hidden classes or eval usage. For production profiling without stopping the process, Node.js 16+ supports --cpu-prof flag that writes a .cpuprofile on exit. PerformanceObserver API monitors GC events, HTTP timing, and event loop lag without external tools.
Use `node --inspect` to open the V8 inspector, then connect Chrome DevTools to take CPU profiles and heap snapshots. The CPU flame graph shows time spent per function. For production, --prof generates low-overhead V8 tick logs, and clinic.js provides higher-level diagnostics. PerformanceObserver enables in-process event loop lag monitoring without external tooling.
The V8 inspector protocol has non-trivial overhead—attaching Chrome DevTools to a production process can change its performance characteristics. Functions that were JIT-compiled may deoptimize when the debugger attaches. For production profiling, prefer --prof (sampling profiler) or clinic flame (which uses --prof under the hood) over live DevTools attachment.