Node.js Reference ยท Concepts and Pitfalls
Memory leaks in Node.js
The most common causes of memory leaks in Node.js programs: unbounded caches, forgotten listeners, timers and closures, plus how to spot and fix them.
A memory leak in a garbage-collected language is memory that your program no longer needs but still references, so the collector cannot free it. Node.js uses V8's garbage collector, which reclaims everything unreachable. A leak therefore always means "something reachable is holding on": a global, a cache, a listener list, a timer, a closure.
Leaks matter most in long-running servers. A leak of a few kilobytes per request is invisible in a test and fatal after a week. The usual symptom is a heap size that climbs steadily, never returns to its earlier level after load drops, and ends in an out of memory crash or a restart by your process manager.
const cache = new Map(); // lives for the whole process function lookup(id) { cache.set(id, load(id)); } // never evicts: a leak
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Where leaks hide
- Unbounded collections. Maps, arrays and objects used as caches, request logs or "seen" sets that only grow. Bound them (size or time), or use
WeakMapwhen the key is an object whose lifetime you do not control. - Event listeners that are never removed. Each
on()call adds a function to a list that lives as long as the emitter. Node warns when more than ten listeners of one event are added, seesetMaxListeners(); the warning is a hint, not a limit. - Timers. An interval holds its callback, and everything that callback closes over, until you call
clearInterval(). Usetimer.unref()for background timers that must not keep the process alive. - Closures that capture too much. A small callback stored for a long time can keep a large object alive because both live in the same scope.
- Global state and module-level variables, especially request-scoped data written to a module singleton.
- Un-closed resources. Streams, sockets, file handles and database connections that are opened per request and never closed hold buffers outside the JavaScript heap too.
- Promises that never settle, and the objects they hold, when a callback is lost.
Finding a leak
- Watch the trend.
process.memoryUsage().heapUsedafter forced garbage collection (node --expose-gc, thenglobal.gc()) should return to a stable level under steady load. A staircase that never comes down points to a leak. - Take heap snapshots.
v8.writeHeapSnapshot()writes a.heapsnapshotfile you can open in Chrome DevTools (Memory tab). Take one, run load, take another, and compare: look for object types whose counts grow. - Use
node --inspectto attach DevTools to a running process and use the allocation timeline. - Reproduce small. Once you know the type of object that leaks, a test that creates and discards it a thousand times will show the growth.
Usage notes
- High memory is not always a leak. V8 lets the heap grow before collecting. Compare after garbage collection, not at an arbitrary moment.
- Buffers live outside the heap.
process.memoryUsage().externalandarrayBufferscount them; a leak of large buffers may not show inheapUsed. WeakRefandFinalizationRegistryexist but are a last resort; their timing is not deterministic.- Set a ceiling in production with
--max-old-space-sizeand let the process manager restart a leaking process while you investigate. That hides the bug; it does not fix it.