← Back to Node.js, page 4

nodejs-0063 · Hard senior

How do you use heap snapshots to find what is leaking, step by step?

Take a snapshot after the app has warmed up, run the suspect workload, force garbage collection, take a second snapshot, and compare. The constructor whose instance count keeps growing is the suspect, and its retainer path shows which variable still holds it. In Node, v8.writeHeapSnapshot() writes a .heapsnapshot file that DevTools can open.

Full answer

A heap snapshot is a full list of live objects with their sizes and the references between them. It is the best tool for a growing heapUsed.

Method:

  1. Warm up the app (load modules, fill normal caches) so start-up objects do not look like a leak.
  2. Force a garbage collection (node --expose-gc and global.gc(), or the DevTools trash icon) and take snapshot 1.
  3. Run a fixed amount of the suspect work, for example 1,000 requests.
  4. Collect garbage again and take snapshot 2.
  5. In Chrome DevTools, Memory tab, load both files, choose snapshot 2 and set the view to "Objects allocated between Snapshot 1 and Snapshot 2". Sort by count or retained size.
  6. Open a suspicious constructor and read its Retainers panel from the bottom up. The path ends at a root such as a module variable, a closure, a Map, a timer or an event listener list. That is the reference you must remove.

Ways to take snapshots in Node: v8.writeHeapSnapshot(file), the --heapsnapshot-signal=SIGUSR2 flag (send the signal to a running process), the DevTools Memory tab over --inspect, or the heapdump-like APIs in diagnostics tools. A snapshot pauses the process and needs memory about twice the heap size, so take it on a staging copy or a single instance taken out of rotation.

Read the numbers carefully: shallow size is the object itself, retained size is what would be freed if the object went away. Growing counts of strings, arrays or closures usually point to a cache or listener list. The same analysis can be scripted by reading the JSON file, as the snippet shows.

javascript
const v8 = require('node:v8');
const vm = require('node:vm');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

v8.setFlagsFromString('--expose-gc');
const gc = vm.runInNewContext('gc');

class StudentSession {
  constructor(id) { this.id = id; this.history = new Array(20).fill(id); }
}
const activeSessions = []; // the leak: sessions are added and never removed

function countInstances(className) {
  gc();
  const file = path.join(os.tmpdir(), `snap-${process.pid}-${Date.now()}.heapsnapshot`);
  v8.writeHeapSnapshot(file);
  const snapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
  fs.rmSync(file);
  const fields = snapshot.snapshot.meta.node_fields;
  const stride = fields.length;
  const nameIndex = fields.indexOf('name');
  const typeIndex = fields.indexOf('type');
  const objectType = snapshot.snapshot.meta.node_types[0].indexOf('object');
  let count = 0;
  for (let i = 0; i < snapshot.nodes.length; i += stride) {
    if (snapshot.nodes[i + typeIndex] === objectType && snapshot.strings[snapshot.nodes[i + nameIndex]] === className) count++;
  }
  return count;
}

const before = countInstances('StudentSession');
for (let i = 0; i < 500; i++) activeSessions.push(new StudentSession(i)); // 500 "requests"
const after = countInstances('StudentSession');

console.log('snapshot 1: StudentSession objects =', before);
console.log('snapshot 2: StudentSession objects =', after);
console.log('growth between snapshots:', after - before);

activeSessions.length = 0; // fix: release the references
console.log('after releasing the array, objects =', countInstances('StudentSession'));

The code reads the snapshot file the way DevTools does and counts objects by constructor name. Snapshot files are removed after reading. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): snapshot 1: StudentSession objects = 0 snapshot 2: StudentSession objects = 500 growth between snapshots: 500 after releasing the array, objects = 0

Key points

  • Compare two snapshots taken after garbage collection.
  • A growing instance count of one constructor is the lead.
  • The retainer path shows which reference keeps objects alive.
  • Snapshots pause the process and need a lot of memory.

Common mistakes

  • Taking a snapshot before warm-up and blaming start-up objects.
  • Comparing snapshots without forcing garbage collection first.
  • Taking a snapshot on a busy production instance.
  • Reading shallow size only and missing the large retained size.

Follow-ups

  • What is the difference between shallow size and retained size?
  • How would you find a leak in a process that runs in a container?
  • Which objects are GC roots?

Tips

  • Number the six steps. Interviewers want a method.
  • Say 'retainers' and explain that they answer who is holding the object.
  • Mention the cost of a snapshot to show care for production.