Node.js Memory Leaks: A 7-Point Checklist to Find the Root Cause
Archi4 min read
Contents
- Start With the Heap, Not the Hypothesis
- 1. Confirm It Is a Leak and Not Normal Growth
- 2. Check the Event Listener Count
- 3. Audit Timers and Intervals
- 4. Inspect Closures Held by Callbacks
- 5. Look for Unbounded Caches and Maps
- 6. Trace Promise Chains and Async Context
- 7. Verify With a Forced GC and a Retainer Path
- What the Fix Usually Looks Like
Start With the Heap, Not the Hypothesis#
A Node.js process that climbs from 200 MB to 2 GB over six hours is not a mystery. It is a signal. The leak has a cause, and the cause lives in the heap. Before you touch code, capture two heap snapshots: one at steady state and one after the growth is visible. The delta between them is where the diagnosis begins.
The checklist below moves from cheap checks to expensive ones. Stop when you find the cause. Most teams find it in the first three steps.
1. Confirm It Is a Leak and Not Normal Growth#
Memory that rises during a traffic spike and falls afterward is not a leak. Memory that rises in a straight line while traffic is flat is. Plot process.memoryUsage().heapUsed every 10 seconds for an hour. A leak shows a positive slope during idle periods. Cache warm-up, lazy-loaded modules, and JIT compilation all produce early growth that plateaus. If the line never plateaus, keep going.
2. Check the Event Listener Count#
Event listeners are the most common leak in Node.js. Every emitter.on() call that lacks a matching removeListener() keeps the callback and everything it closes over alive. In a long-lived process, a request handler that attaches a listener to a shared emitter on every request will accumulate listeners until the process dies.
Run emitter.listenerCount('event') on your shared emitters. Node warns at 11 listeners by default, but a leak can hide below that threshold if the emitter is created per request and never released. Look for emitters stored on module scope, on global, or on a singleton service.
3. Audit Timers and Intervals#
setInterval and setTimeout hold references to their callbacks until they fire or are cleared. A timer created inside a request handler without clearInterval keeps the handler's closure alive for as long as the timer runs. If the timer is recurring, the closure never dies.
Search the codebase for setInterval and setTimeout calls that are not stored in a variable. If the return value is discarded, you cannot clear it. That is a leak waiting for a code path to trigger it repeatedly.
4. Inspect Closures Held by Callbacks#
A callback retains its entire lexical scope, not just the variables it references. A small handler that closes over a 50 MB buffer keeps that buffer alive as long as the callback is reachable. This is easy to miss because the code looks innocent.
In the heap snapshot, filter by constructor name for the objects you expect to be large. If a buffer or a request body appears in the retainer path of a long-lived object, the closure is the cause. The fix is to null out or restructure the captured variables, or to move the work out of the closure entirely.
5. Look for Unbounded Caches and Maps#
A Map used as a cache with no eviction policy grows until the process runs out of memory. The same applies to plain objects used as lookup tables, arrays that only get pushed to, and any module-level collection that accumulates per-request data.
Check every Map, Set, and object declared outside a function. Ask: what removes entries? If the answer is nothing, you have found the leak. Add an LRU bound, a TTL, or a periodic sweep. The specific mechanism matters less than the bound.
6. Trace Promise Chains and Async Context#
An unresolved promise keeps its .then callbacks and their closures alive. A promise that never settles, because an await hangs on a socket that never closes, holds everything downstream. In heap snapshots, look for retained promises and the async resources attached to them.
Use async_hooks sparingly in production, but in a reproduction environment it will show you which async resource is holding the chain. A common pattern is a database query wrapped in a promise that has no timeout. The connection pool waits, the promise waits, and the closure waits with it.
7. Verify With a Forced GC and a Retainer Path#
Before you conclude anything, force garbage collection with node --expose-gc and call global.gc() between snapshots. Without a forced GC, the snapshot includes garbage that has not been collected yet, and you will chase objects that are already dead.
Then take a comparison snapshot and inspect the retainer path of the largest growing object. The retainer path tells you exactly what is holding the reference: a listener, a timer, a map entry, or a closure. That path is the root cause. Everything above it is symptom.
What the Fix Usually Looks Like#
The fix is rarely a rewrite. It is a removeListener call, a clearInterval, a bounded cache, or a timeout on an awaited promise. The hard part is finding the reference, not removing it. Once you have the retainer path, the patch is usually a few lines.
Add a memory assertion to your test suite: run a load test for ten minutes and assert that heapUsed after forced GC is within 15 percent of the starting value. That single check catches most regressions before they reach production. It will not catch every leak, but it catches the ones caused by the patterns above, which are the ones that ship.
More articles