Generate Node.js Heap Snapshot on Out of Memory

When a Node.js application crashes due to out-of-memory (OOM) errors, identifying the exact cause of the memory leak can be difficult. This article explains how to configure your Node.js process to automatically generate a heap snapshot right before it runs out of memory, allowing you to analyze the heap state and pinpoint the memory-hogging objects using debugging tools.

The --heapsnapshot-near-heap-limit Flag

Starting from Node.js v12.18.0 and v14.5.0, V8 provides a built-in command-line option to write a heap snapshot to disk when the V8 heap is nearly full. This is the most efficient and reliable way to capture the state of your application’s memory before a crash.

To use this feature, start your Node.js application with the --heapsnapshot-near-heap-limit flag:

node --heapsnapshot-near-heap-limit=1 app.js

Understanding the Parameter Value

The integer value assigned to the flag (e.g., =1) specifies the maximum number of heap snapshots that Node.js is allowed to generate.

Because Node.js might trigger multiple garbage collection cycles while hovering near the memory limit, setting this value prevents the process from repeatedly writing snapshots and exhausting your server’s disk space. Setting it to 1 is highly recommended for production environments.

Configuring via Environment Variables

If you cannot easily modify the start command of your Node.js process (for example, when running inside Docker, PM2, or a cloud platform), you can enable this behavior using the NODE_OPTIONS environment variable:

export NODE_OPTIONS="--heapsnapshot-near-heap-limit=1"

Where is the Snapshot Saved?

By default, Node.js saves the generated snapshot file in the working directory of the process. The file name follows this pattern:

Heap.${YYYYMMDD}.${HHMMSS}.${pid}.${thread_id}.${seq}.heapsnapshot

If you want to customize the directory where the snapshot is saved, you can combine it with the --heapsnapshot-dir flag:

node --heapsnapshot-near-heap-limit=1 --heapsnapshot-dir=/var/log/snapshots app.js

Analyzing the Snapshot

Once the application runs out of memory and crashes, locate the .heapsnapshot file and analyze it using the following steps:

  1. Open Google Chrome (or any Chromium-based browser).
  2. Press F12 to open Developer Tools.
  3. Go to the Memory tab.
  4. Right-click the left sidebar under “Profiles” and select Load… (or click the “Load” button at the bottom).
  5. Select your .heapsnapshot file.
  6. Use the Summary or Comparison views to find which objects are taking up the most memory (look at “Constructor”, “Distance”, and “Retained Size”).