How to Detect and Fix Memory Leaks in Node.js
Find and fix a leak: watch the heap over time, take heap snapshots, look for grown object groups, and remove the retention path.
On this page
Introduction
A memory leak is memory that is allocated and never freed because something still references it. In Node.js the garbage collector frees unreachable objects, so a leak means an object is reachable when it should not be: a listener that was never removed, a map that grows forever, a closure that captures a large object it no longer needs. The symptom is a heap that keeps rising under steady load until the process runs out of memory and crashes.
This tutorial finds a leak by watching the heap, taking snapshots, following the retainer path to the reference that holds the objects, and removing it. The examples use Node.js tools, and the method applies to any runtime with garbage collection and a heap profiler.
Confirm it is a leak, not a working set
A large heap is not necessarily a leak. A service with a large working set holds a lot of memory legitimately, and it stays roughly flat under steady load. A leak is a heap that keeps rising even after a garbage collection, because the objects are still reachable and cannot be freed. Measure the heap over time under a steady load and compare the values after a forced collection.
Rule out the alternatives: a growing request rate explains a growing heap, and a one-time warm-up explains an early rise that then flattens. The leak signal is a rise that continues after the warm-up at a steady load, with the heap after a collection trending up. Use process.memoryUsage to watch it, and take the measurements at a fixed interval so the trend is visible.
setInterval(() => {
const m = process.memoryUsage();
metrics.gauge('heap.used_mb', m.heapUsed / 1e6);
metrics.gauge('rss_mb', m.rss / 1e6);
}, 10000);
// a heapUsed that trends up after a warm-up at steady load is the leak signal
Take heap snapshots and compare
A heap snapshot is a full list of the objects in the heap and their references. The technique is differential: take a snapshot, drive the suspected operation, force a collection, take another snapshot, and compare. The objects that grew between the snapshots, and are still present, are the leak candidates, because a well-behaved operation frees its temporary objects.
For a request-driven leak, repeat the operation many times between snapshots so the growth is large enough to see above the noise. A single request may allocate and free, showing no growth, while ten thousand requests show the accumulating objects. Compare the object counts by constructor name, and look for one that grows with the number of operations.
node --inspect server.js
# connect Chrome DevTools > Memory > take snapshot 1
# drive the suspected operation (e.g. 10k requests)
# force GC, take snapshot 2, compare: which constructor grew?
Follow the retainer path
A leaked object is kept alive by a reference from a reachable one. The retainer path, from a garbage collection root to the object, names the reference that holds it. In a heap snapshot, select the grown object group and inspect its retainers to see what keeps it alive. The retainer is often what you fix: an event emitter with an accumulated listener, a module-level map, a closure over a large value.
Common retainers are: an event listener added on every request without removal, so the emitter accumulates listeners; an unbounded cache or map keyed by a value that is never evicted; a closure created per request that captures a large object and is stored somewhere; a timer or interval whose callback holds an object and never clears. The retainer path points to one of these, and removing it frees the objects.
// leak: a listener added per request and never removed
emitter.on('data', handler); // every call adds another listener
// fix: add once, or remove when done
emitter.once('data', handler);
// or: emitter.on('data', handler); ...later... emitter.off('data', handler);
Fix the retention and bound the store
Once you have the retainer, remove the reference: detach the listener, clear the interval, delete the map entry, or replace the unbounded store with a bounded one. For a cache, bound it with an LRU and a maximum, so it evicts instead of growing. For a listener, add it once, or always remove it in a finally. For a closure, avoid capturing a large object when a small one or a key would do.
Some leaks are structural: a module-level map that accumulates every request, a global array that is appended to and never trimmed, a global registry that is not cleaned. These need a bound or a cleanup policy, not a one-line fix. The rule is that every store of objects that outlives a request needs a maximum or a removal, or it will grow with the request count.
// structural leak: request-level data kept in a module-level map
const seen = new Map(); // grows forever
// fix: bound it, or key it with a TTL and evict
const seen = new LRUCache({ max: 10000, ttl: 60000 }); // evicts, bounded
Verify the fix with the same measurement
After removing the retention, repeat the measurement that showed the leak: drive the same load and watch the heap. Assert the heap after a collection no longer trends up, which proves the leak is fixed. A heap that stays flat under the same load is the confirmation, and a test that drives the operation many times and asserts a stable heap catches a reintroduction.
# drive 10k requests and print the heap delta after GC
node --expose-gc -e '
for (let i = 0; i < 10000; i++) { await handleRequest(); }
global.gc();
console.log("heap after:", process.memoryUsage().heapUsed / 1e6, "MB"); // stable
'
Common pitfalls
Concluding a leak from a large heap without a stable-load measurement, taking a single snapshot so the growth is lost in the noise, looking at allocated objects instead of the retainer that keeps them alive, fixing one listener while a module-level map keeps growing, and not verifying the fix with the same measurement are the recurring mistakes. A steady-load heap watch, differential snapshots, the retainer path, a bound or removal, and a repeat measurement address them.
Conclusion
A leak is memory that something still references. Confirm it with a heap that rises after collection at steady load, take differential snapshots to find the grown object group, follow the retainer path to the reference holding it, and remove that retention or bound the store. Self-check by driving the load again and asserting the heap no longer trends up. Then the process holds its working set and nothing more.
Sources: Node.js: Memory and diagnostics, Node.js: process.memoryUsage, Chrome DevTools: Heap snapshots.
FAQ
- Why does the heap not shrink after collection?
- A garbage collection frees only unreachable objects. If the heap stays high after a collection, the objects are still reachable, which means something holds a reference to them, such as a long-lived map, an event listener, or a cache with no bound.
- What are common leak sources in Node.js?
- Event listeners added without being removed, unbounded caches and maps, closures that capture large objects, timers and intervals never cleared, and global arrays that accumulate. Most are an object held by something long-lived that should have released it.
Report a problem with this articleOpens a pre-filled issue on GitHub.