Spring Fresh Sale! - Up To 67% OFF BDIX Hosting + Free Domain
Node.js

How to Capture and Analyze Node.js Heap Snapshots and CPU Profiles

Heap snapshots show what is using your memory; CPU profiles show what is using your processing time. Together they turn "my app is slow and bloated" into "this exact function and this exact object are the problem". Here is how to capture and read both.

Capturing a heap snapshot

Connect Chrome DevTools to your app via the inspector, open the Memory tab, and take a heap snapshot. For leak hunting, take one, exercise the app under load, then take another.

Reading a heap snapshot

  • Compare two snapshots using the "Comparison" view — objects that grew between them are your leak candidates.
  • Look at retained size — how much memory an object keeps alive, not just its own size.
  • Follow retainers — the chain of references keeping an object in memory, which points you to the code holding it.

This is the core technique for fixing memory leaks.

Capturing a CPU profile

In the DevTools Performance (or Profiler) tab, start recording, run the slow operation, then stop. You get a breakdown of where CPU time went.

Reading a CPU profile

  • Flame chart — wide bars are functions taking the most time; that width is your bottleneck.
  • Self vs total time — self time is spent in the function itself; total includes what it called.
  • Hot paths — the deepest, widest stacks are where to optimise first.

If a CPU profile shows one synchronous function dominating, that is likely blocking the event loop — a candidate for worker threads.

Frequently asked questions

How do I find a leak with snapshots?

Take two snapshots under load, minutes apart, and use the comparison view to see which object types grew. Follow their retainers to the code holding them, then break that reference.

What does "retained size" mean?

The total memory that would be freed if that object were collected — including everything it keeps alive. A small object with a huge retained size is holding a lot hostage, which is exactly what you want to find.

Can I profile production safely?

Yes, but capture briefly and reach the inspector only over a secure tunnel, never a public port. Profiling adds some overhead, so keep production captures short.

Was this article helpful?