advanced
Profiling
Use CPU profiles, heap snapshots, flamegraphs, traces, and production-safe sampling to prove where time and memory go.
Profiling proves where CPU time and memory go instead of guessing. For Node.js use CPU profiles (flamegraphs), heap snapshots, async hooks/traces, and APM transaction traces—with production-safe sampling where possible.
| Tool | Answers | |------|---------| | CPU profile | Hot functions, sync JSON, regex catastrophes | | Heap snapshot | Retained objects, closure leaks | | Clinic.js / 0x | Event-loop delay, GC pressure | | APM trace | Slow spans per request |
node --cpu-prof server.js
# or: clinic flame -- node server.js
Profile under **representative load**, not idle localhost. Compare before/after deploy. Red bars in flamegraphs are cumulative time—follow widest frames down to root cause.
On interviews: sampling vs instrumentation overhead; how to profile production safely; reading flamegraphs; when logging beats profiling.
Common pitfalls: profiling dev machine only; optimizing micro-benchmarks; ignoring GC pauses; never correlating profiles with traces.
The trade-off is observability overhead versus confidence in optimization targets.
Checklist:
- Reproduce slowness under load first.
- Capture CPU + trace for same request.
- Fix widest frame, not random micro-opts.
- Validate with percentiles after deploy.