Take heap snapshots a few minutes apart and compare them in Chrome DevTools to see which objects keep growing. Here is how to capture snapshots locally and in production.
The short answer
#Confirm memory keeps growing, then take two or three heap snapshots a few minutes apart and compare them in Chrome DevTools. The objects whose count keeps rising, and the retainer chain that keeps them alive, point to the leak.
_10node --inspect server.js_10# Open chrome://inspect in Chrome, click "inspect",_10# then use the Memory tab to take heap snapshots.
Why it happens
#JavaScript frees memory automatically, but only for objects nothing can reach any more. A leak in Node.js is almost always an object that is still reachable by accident, so the garbage collector must keep it. Common causes:
- Caches without limits. A module-level
Mapor object that you add to on every request but never clear. - Event listeners that are never removed. Calling
emitter.on(...)inside a request handler adds a new listener each time. Node.js warns withMaxListenersExceededWarningwhen one emitter has more than 10 listeners for an event. - Timers. A
setIntervalthat is never cleared keeps its callback and everything it closes over alive. - Closures that capture large values. A small callback stored somewhere long-lived can hold on to a big buffer or request object.
- Global state. Arrays that log every request, or session data stored in memory.
A growing heap is not always a leak. Memory often rises after startup and then levels off as caches warm up. A leak keeps climbing under steady load until the process crashes with "JavaScript heap out of memory".
How to fix it
#Confirm the growth first
Log memory use at an interval while the app is under realistic load.
_10setInterval(() => {_10 const { heapUsed, rss } = process.memoryUsage();_10 console.log(`heap ${(heapUsed / 1e6).toFixed(1)} MB, rss ${(rss / 1e6).toFixed(1)} MB`);_10}, 10_000).unref();
If heapUsed keeps rising over many minutes and never comes back down, you probably have a leak in JavaScript objects. If only rss grows, look at buffers or native modules instead.
Compare heap snapshots in DevTools
Start the app with the inspector, connect Chrome, and use the Memory tab.
- Run
node --inspect server.jsand openchrome://inspect. - Take a heap snapshot once the app has warmed up.
- Send traffic for a few minutes, for example with a load testing tool.
- Take a second snapshot, then a third after more traffic.
- Select the last snapshot and switch the view to Comparison against an earlier one.
Sort by # Delta or Size Delta. Look for your own class names, closures, strings or arrays that keep increasing. Click one and read the Retainers panel at the bottom. It shows the chain of references from a root to that object, which usually names the variable or listener that holds it.
Taking a snapshot triggers a garbage collection first, so anything left over is genuinely still referenced.
Capture snapshots in production
You often cannot attach DevTools to a live server. Node.js has flags that write snapshots to disk for you to open later in the Memory tab.
_10# Write a snapshot whenever the process receives SIGUSR2_10node --heapsnapshot-signal=SIGUSR2 server.js_10kill -USR2 <pid>_10_10# Write up to 2 snapshots as the heap nears its limit_10node --heapsnapshot-near-heap-limit=2 server.js
The signal flag does not work on Windows. You can also write a snapshot from code with v8.writeHeapSnapshot(), for example from an admin-only endpoint.
Be careful: writing a snapshot pauses the process and needs roughly as much extra memory as the heap itself. Do it on one instance taken out of the load balancer if you can. Snapshots also contain real data from memory, including user data and secrets, so treat the files as sensitive.
Fix the common causes
Once you know what is growing, the fix is usually small. Put a limit on caches, or let entries be collected:
_10// Entries disappear when the key object is no longer used elsewhere_10const metadata = new WeakMap();_10_10function tag(req, info) {_10 metadata.set(req, info);_10}
Remove listeners and timers when you are done with them, or register them once outside request handlers:
_10const onData = (chunk) => handle(chunk);_10stream.on('data', onData);_10_10stream.once('close', () => {_10 stream.off('data', onData);_10 clearInterval(timer);_10});
Then repeat the snapshot comparison to confirm the count stays flat.
Common pitfalls
#- Raising the memory limit to hide it.
--max-old-space-sizebuys time but the process still crashes eventually. Use it as a stopgap, not a fix. - Snapshotting too early. Startup work, module loading and cache warm-up all look like growth. Compare snapshots taken after warm-up.
- Testing without load. Many leaks are per request. If no requests arrive between snapshots, nothing changes.
- Ignoring the warning.
MaxListenersExceededWarningis very often the leak itself. Find where listeners are added in a loop. - Reading only Shallow Size. A small object can retain a huge tree. Sort by Retained Size to find what holds the most memory.
Related reading
#Was this resource helpful?