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.jsUnderstanding 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.jsAnalyzing the Snapshot
Once the application runs out of memory and crashes, locate the
.heapsnapshot file and analyze it using the following
steps:
- Open Google Chrome (or any Chromium-based browser).
- Press
F12to open Developer Tools. - Go to the Memory tab.
- Right-click the left sidebar under “Profiles” and select Load… (or click the “Load” button at the bottom).
- Select your
.heapsnapshotfile. - Use the Summary or Comparison views to find which objects are taking up the most memory (look at “Constructor”, “Distance”, and “Retained Size”).