A Node.js service whose RSS climbs from 200 MiB to 1.5 GiB over a week, then OOMs and gets respawned by systemd, almost always has a closure holding references to objects that should be free. Heap snapshots are V8’s mechanism for exposing every object in memory and the references holding it. This runbook covers triggering snapshots safely on a production process, diffing two snapshots to find what grew, and reading the retainer chain to identify the responsible code.
How to verify
Confirm the leak exists before chasing ghosts:
ps -o pid,rss,cmd -p $(pgrep -f 'node.*server') # RSS over time
curl -s http://127.0.0.1:3000/_metrics | grep -E 'nodejs_heap|process_resident'
journalctl -u myapp --since "24 hours ago" | grep -i 'OOM\|killed\|memory'
node -e "console.log(process.memoryUsage())" # baseline from a fresh process
ls -lh /tmp/heap-*.heapsnapshot
If RSS grows monotonically and never plateaus under steady traffic, you have a leak. If it grows then falls back after GC, you have churn — different problem, different fix.
What’s happening
V8’s garbage collector frees objects that have no path back to a GC root (the global object, the call stack, an active timer, the require cache). A “leak” in Node usually means a reference is being held intentionally somewhere — most often an array or Map that keeps growing because nothing ever removes from it. Common culprits: EventEmitter listeners that aren’t removed, closures captured by setInterval callbacks that reference large objects, caches keyed by user input with no eviction, the require cache holding compiled modules.
A heap snapshot is a serialized dump of every JS object reachable from a GC root, with its size, type, and references. The format is JSON and snapshots are large — a 500 MiB heap dumps to 1-2 GiB of JSON. Two snapshots taken at different times can be diffed to find objects allocated between them and still alive at the second snapshot — that diff is the leak.
The procedure
-
Add a heap-snapshot trigger to your service. Two safe ways: an HTTP endpoint bound to localhost, or a signal handler:
import v8 from 'node:v8'; import { writeFileSync } from 'node:fs'; process.on('SIGUSR2', () => { const file = `/tmp/heap-${Date.now()}.heapsnapshot`; console.log(`writing heap snapshot to ${file}`); v8.writeHeapSnapshot(file); }); -
Trigger snapshot #1 when the service is freshly started and has served some traffic:
pgrep -f 'node.*server' sudo kill -SIGUSR2 <pid> ls -lh /tmp/heap-*.heapsnapshot -
Wait long enough for the leak to manifest — usually 30 to 60 minutes of typical traffic. Then trigger snapshot #2:
sudo kill -SIGUSR2 <pid> ls -lh /tmp/heap-*.heapsnapshot -
Copy both snapshots to your laptop and load them into Chrome DevTools:
scp deploy@app-01:/tmp/heap-*.heapsnapshot ./In Chrome, open
chrome://inspect→ “Open dedicated DevTools for Node” → Memory tab → “Load” → pick snapshot #1, then “Load” again for snapshot #2. Switch the Memory view to “Comparison” and pick snapshot #1 as the baseline. The columns ”# Delta” and “Size Delta” show objects created and not freed between the two captures. -
Sort by Size Delta descending. Open the top type (often
Objectorstring). Each entry has a “Retainers” pane at the bottom — that’s the chain of references holding it alive. Follow the chain up to the root; the file:line at each link tells you who is holding the reference. -
Once you identify the leaking code path (a Map without eviction, a listener never removed, an interval capturing a large closure), fix it and verify with a third snapshot: the count for that retainer should now stay flat between two captures.
Common pitfalls
writeHeapSnapshotpauses the event loop for the duration of the dump. A 1 GiB heap takes 8-15 seconds — drain the node from the load balancer first.- DevTools struggles with snapshots larger than 2 GiB. For very large heaps, use the
heapsnapshot-parserCLI to analyze offline, or take the snapshot earlier in the leak when the heap is smaller. - The snapshot file is dropped wherever
process.cwd()is, which in a container may be inside the container’s writable layer — burning disk. Mount/tmpas a tmpfs volume or point the path at a volume mount. - Closures captured by
setIntervalandsetTimeout(when long-running) hold every variable in their lexical scope. A common leak issetInterval(() => useState(largeArray), 1000)—largeArrayis pinned forever. - React/Vue/Next isomorphic bundles can leak module-scope state between requests in SSR mode if singletons accumulate per-request data. Diffing snapshots after 1000 SSR requests will show the linear growth.
For continuous heap stats without taking snapshots, see continuous V8 profiling with pprof. In the engagements Stack Harbor runs, heap snapshots are part of the standard incident toolkit — every Node service ships with the SIGUSR2 handler, alerts fire when RSS exceeds a baseline by 25%, and the on-call team has a tested runbook for diff’ing snapshots as part of managed operations so a memory leak doesn’t escalate to a restart loop.