Profiling Node.js Performance: CPU Profiles, Flame Graphs and Benchmarks

Measure first, then optimise

"The API is slow" could mean a slow database, a blocked event loop, or one expensive function called a million times. Guessing wastes days. Profiling shows you exactly where the time goes.

Step 1: Reproduce Under Load

Use a load-testing tool to create realistic traffic:

npx autocannon -c 50 -d 30 http://localhost:3000/api/products

Record requests per second and latency percentiles as your baseline.

Step 2: Capture a CPU Profile

node --cpu-prof server.js
# run the load test, then stop the server

Node writes a .cpuprofile file. Open it in Chrome DevTools (Performance or JavaScript Profiler panel) or VS Code.

Alternatively, attach live with node --inspect and record from chrome://inspect.

Step 3: Read the Flame Graph

  • Width = time spent in a function (including children)
  • Look for wide bars in your code, not just framework internals
  • Common culprits: JSON serialisation of huge objects, regex, sync crypto, deep cloning, logging in hot paths

Step 4: Fix and Re-Measure

Typical fixes:

  • Cache computed results
  • Stream instead of building big strings or arrays
  • Move CPU-heavy work to worker threads or a queue
  • Avoid repeated work inside loops
  • Reduce logging volume in hot paths

Run the same load test again and compare with the baseline. If it's not measurably faster, revert the complexity.

Micro-Benchmarks

For comparing two implementations of a function, use a benchmark library (e.g. tinybench or mitata) — but always confirm improvements with a real load test.

In Production

APM tools (New Relic, OpenTelemetry-based tools) show slow transactions and, in some cases, continuous profiling — so you can find hot paths with real traffic.

Optimisation without measurement is just rewriting code. Profile, fix the widest bar, and measure again.

Arivanandhan Chitheshwaran