Back to results for “Debugging”
Node.js › Debugging & Diagnostics

How do you use Node's built-in heap snapshot capability to diagnose a suspected memory leak?

Intermediate

Answer

Node.js can generate a heap snapshot (a complete picture of all objects currently in memory and their retaining relationships) via the --heapsnapshot-signal flag, the inspector's Memory panel in Chrome DevTools, or programmatically via the v8 module -- comparing two snapshots taken minutes apart, focusing on which object types have grown significantly in count, reveals what's accumulating and, via the retainer graph, why those objects are still reachable and therefore not being garbage collected.
const v8 = require('node:v8');
const fs = require('node:fs');

function takeHeapSnapshot() {
  const snapshotStream = v8.getHeapSnapshot();
  const fileStream = fs.createWriteStream(`heap-${Date.now()}.heapsnapshot`);
  snapshotStream.pipe(fileStream);
}
// Load the resulting .heapsnapshot file into Chrome DevTools' Memory panel
Real-world example A production service with steadily climbing memory usage has two heap snapshots taken ten minutes apart compared in Chrome DevTools, revealing a rapidly growing count of retained EventEmitter listener objects, pointing directly at the specific class where listeners were being added without ever being removed.

Common follow-ups: How do you interpret the 'retainers' view in a heap snapshot comparison to trace back to the actual leaking code?;What's the overhead of taking a heap snapshot on a live production process, and how do you minimize its impact?