Using Heap Snapshot

You can take a Heap Snapshot from your running application and load it into Chrome Developer Tools to inspect certain variables or check retainer size. You can also compare multiple snapshots to see differences over time.

Warning

When creating a snapshot, all other work in your main thread is stopped. Depending on the heap contents it could even take more than a minute. The snapshot is built in memory, so it can double the heap size, resulting in filling up entire memory and then crashing the app.

If you're going to take a heap snapshot in production, make sure the process you're taking it from can crash without impacting your application's availability.

How To

Get the Heap Snapshot

There are multiple ways to obtain a heap snapshot:

  1. via the inspector,
  2. via an external signal and command-line flag,
  3. via a writeHeapSnapshot call within the process,
  4. via the inspector protocol.

1. Use memory profiling in inspector

Works in all actively maintained versions of Node.js

Run node with --inspect flag and open the inspector. open inspector

The simplest way to get a Heap Snapshot is to connect a inspector to your process running locally. Then go to Memory tab and take a heap snapshot.

take a heap snapshot

2. Use --heapsnapshot-signal flag

Works in v12.0.0 or later

You can start node with a command-line flag enabling reacting to a signal to create a heap snapshot.

$ node --heapsnapshot-signal=SIGUSR2 index.js

  1. Let the process load all sources and finish bootstrapping. It should take a few seconds at most.
  2. Start using the functionality you suspect of leaking memory. It's likely it makes some initial allocations that are not the leaking ones.
  3. Take one heap snapshot.
  4. Continue using the functionality for a while, preferably without running anything else in between.
  5. Take another heap snapshot. The difference between the two should mostly contain what was leaking.
  6. Open Chromium/Chrome dev tools and go to Memory tab
  7. Load the older snapshot file first, and the newer one second. Load button in tools
  8. Select the newer snapshot and switch mode in the dropdown at the top from Summary to Comparison. Comparison dropdown
  9. Look for large positive deltas and explore the references that caused them in the bottom panel.

You can practice capturing heap snapshots and finding memory leaks with this heap snapshot exercise.