Memory leaks and heap snapshots
Finding a Node memory leak with process.memoryUsage, heap snapshots and the comparison view, taking snapshots from a live process, and setting heap limits.
The process objectEvents and EventEmitterProfiling and finding bottlenecks
Memory leaks and heap snapshots
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A leak in a garbage-collected language is memory that is still reachable but no longer needed: something global, such as a Map, an array, a closure or an event listener, still points at it.
- Watch `process.memoryUsage()`. `heapUsed` is V8 objects. `external` covers Buffers and other off-heap memory, and `rss` is what the OS sees. A leak of Buffers can leave `heapUsed` flat while `rss` climbs.
- A heap snapshot is a full dump of reachable objects. Take one, run the suspect workload, take another, and use DevTools' Comparison view to see which constructors gained the most objects and bytes.
- Retained size is what would be freed if an object were deleted, so it points at the owner. Follow the Retainers panel from a leaked object back to the global that keeps it alive.
- `v8.writeHeapSnapshot()`, `--heapsnapshot-signal=SIGUSR2` and `--heapsnapshot-near-heap-limit=N` take snapshots without a debugger. A snapshot freezes the process while it is written and needs memory roughly the size of the heap.
- `--max-old-space-size` sets the heap ceiling in MB. Raising it delays a leak's crash but does not fix it, and in containers it must stay below the memory limit.
- The usual culprits are unbounded caches, listeners added per request and never removed, timers and intervals never cleared, and closures holding large request data.
How a garbage-collected language leaks
JavaScript frees memory automatically, so how can it leak? The collector only frees what nothing can reach. If a global Map holds a reference to an object, that object is reachable, so it stays, whether or not your code will ever read it again. A leak is just a reference you forgot you were keeping. The mechanics of garbage collection are in memory management and garbage collection. This lesson is about finding the forgotten reference in a running Node process.
The shape of a leak is easy to recognize on a graph. Memory climbs with traffic, never returns to a baseline after garbage collection, and the process eventually dies with FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory, or is killed by the container for exceeding its limit. For the Node process view of memory numbers, see the process object.
Reading the numbers
const m = process.memoryUsage();
console.log(m.heapUsed, m.external, m.rss);
heapUsed counts live objects on V8’s heap. external is memory V8 tracks that lives outside it, mostly Buffers. rss is the whole resident set the operating system sees. They can disagree, and the disagreement is informative. I wrote a small leaky handler:
const cache = new Map(); // never evicted
const bus = new EventEmitter();
bus.setMaxListeners(0);
function handle(id) {
cache.set(id, { id, payload: Buffer.alloc(10_000, 1) });
bus.on('tick', () => cache.size); // a new listener per call, never removed
}
for (let n = 0; n < 20000; n++) handle(n);
After 20,000 calls, forcing a garbage collection, heapUsed was only about 11 MB, up from 4. But external was 193 MB and RSS 237 MB. The 10 KB Buffers do not live on the V8 heap, so the heap number alone hid most of the leak. Always look at external and RSS too. Then I cleared the cache, and memory dropped back to about 5 MB, which confirmed the Map was the retainer.
The usual suspects
Nearly every Node leak is one of these:
- An unbounded cache: a
Mapor object keyed by user, request or url that grows forever. Fix with a size limit, TTL or an LRU cache. - Listeners added repeatedly:
emitter.on(...)inside a request handler, with no matchingoff. Each listener’s closure keeps its captured variables alive. Node warns after ten listeners per event:MaxListenersExceededWarning: Possible EventEmitter memory leak detected. Treat that warning as a bug report, not noise to silence. See events and EventEmitter. - Timers never cleared:
setIntervalthat nothing stops, holding its callback’s scope. - Closures holding big data: a long-lived callback that closes over a whole request or response object when it only needs an id.
- Global state that accumulates: arrays of recent events, metrics labels with unbounded cardinality, request-scoped data stashed in module variables.
Heap snapshots
Reasoning from the code gets you only so far. A heap snapshot records every reachable object, its type and size, and what points to it. Take one and open it in Chrome DevTools, in the Memory panel.
You can take one from code, with a flag, or by signal, and none needs a debugger attached:
import v8 from 'node:v8';
v8.writeHeapSnapshot('leak.heapsnapshot'); // returns the file name
node --heapsnapshot-signal=SIGUSR2 app.js # kill -USR2 <pid> writes Heap.<date>.<pid>.heapsnapshot
node --max-old-space-size=60 --heapsnapshot-near-heap-limit=1 app.js
I ran all three on Node 26. The signal flag wrote a snapshot file from a running idle process when I sent SIGUSR2. --heapsnapshot-near-heap-limit=1 made a deliberately runaway script write one snapshot as it approached its 60 MB limit, then crash with the fatal out-of-memory error. That one is the best for production: you get a snapshot of the process in its worst state. Snapshots are big (the leaky example’s was about 13 MB), and writing one pauses the process and needs memory comparable to the heap, so do not take them casually on a nearly full instance. They also contain your data, including secrets and personal information, so treat the files as sensitive.
The comparison workflow
One snapshot shows you what is there, but not what is growing. The reliable method uses two:
- Start the app, run some warm-up traffic, and take snapshot A.
- Run the suspect operation many times, for example 1,000 requests.
- Take snapshot B.
- In DevTools, load both, select B, and switch the view to Comparison against A.
Sort by size delta or object count delta. A constructor whose count rose by about 1,000 along with your workload is a leak candidate. Click an instance and open the Retainers panel, which walks from the object back to what keeps it alive: perhaps an entry in a Map, or an (array) held by an EventEmitter’s listener list. That chain is the fix site.
Two terms help when reading the table. Shallow size is the object’s own bytes. Retained size is how much memory would be freed if that object were deleted, including everything only it keeps alive. Sort by retained size to find owners, rather than a million small strings.
Limits and containers
V8’s heap has a ceiling. On my machine v8.getHeapStatistics().heap_size_limit reported about 4,192 MB. --max-old-space-size=<MB> changes it:
node --max-old-space-size=512 app.js
Set it deliberately in containers, to a value comfortably below the container’s memory limit, so Node fails with a clear out-of-memory error and a snapshot rather than being killed silently by the kernel. Do not treat a bigger heap as the fix for a leak. It only delays the crash, and longer garbage collection pauses make the service worse before it does. Containers are covered in deploying Node applications.
What the video covers
The embedded talk is Ali Sheikh’s “Understanding and Debugging Memory Leaks in Your Node.js Applications” for the Node.js Foundation, from 2017. Its description says it introduces what memory leaks are, how they can exist in a garbage-collected language, and the tooling to understand and isolate them, specifically heap snapshots and the sampling heap profiler in V8. Ali Sheikh was a member of the Node.js CTC (its core technical committee) and a V8 contributor at Google. The talk is old and about Node 8, so some tooling it shows, such as installing the heapdump module and the chrome://inspect workflow, is superseded by v8.writeHeapSnapshot() and the flags above. The model of the heap and the Comparison view it teaches have not changed. At 31 minutes it is long. A November 2025 video from a small channel, DevTools99, in the “go deeper” links, describes the modern flags, but I could not verify its contents. Transcripts were unavailable for both, so the talk is described from its abstract, and the code, flags and numbers above come from running them locally.
Where this fits
Profiling and leak hunting are about your own code. The other production risk is code you did not write, which arrives through npm install: securing Node dependencies and the supply chain.
Check yourself
A service's RSS grows steadily but `process.memoryUsage().heapUsed` stays flat. Where might the memory be?
Outside the V8 heap, most likely in Buffers or other native allocations counted under `external` or `arrayBuffers`, or in native addons, or in fragmentation. In my test, 20,000 retained 10 KB Buffers left `heapUsed` near 11 MB while `external` was 193 MB and RSS 237 MB. A heap snapshot shows the small JavaScript wrappers but not the bytes, so check `external` first.
How do you use two heap snapshots to find a leak?
Take one after the app has warmed up, run the suspect operation many times, take another, and open both in Chrome DevTools' Memory panel. In the Comparison view, sort by size delta or object count delta, and look for a constructor that grew in step with your workload. Then use the Retainers panel on one of those objects to see which global or closure keeps it alive.
What does `MaxListenersExceededWarning: Possible EventEmitter memory leak detected` warn about?
More than ten listeners were added for the same event on one emitter. It is usually a sign that code adds a listener per request or per call and never calls `off`, so each listener and everything its closure references stays reachable. Fix the registration, rather than silencing it with `setMaxListeners`.
Why is raising `--max-old-space-size` not a fix for a leak?
It only raises the ceiling, so the process runs longer before it hits the limit and then crashes with an out-of-memory error in the same way, often with longer garbage-collection pauses before it does. The cause is retained objects, and only removing the reference, bounding the cache or clearing the listener solves it.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.