---
title: "How do I find a memory leak in Node.js?"
description: "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."
url: https://www.danny.engineering/answer/nodejs/how-do-i-find-a-memory-leak-in-nodejs
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T20:30:00.000Z
tags: ["Node.js"]
---

# How do I find a memory leak in Node.js?

## 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.


```bash
node --inspect server.js
# Open chrome://inspect in Chrome, click "inspect",
# 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 `Map` or 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 with `MaxListenersExceededWarning` when one emitter has more than 10 listeners for an event.
- **Timers.** A `setInterval` that 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.


```javascript
setInterval(() => {
  const { heapUsed, rss } = process.memoryUsage();
  console.log(`heap ${(heapUsed / 1e6).toFixed(1)} MB, rss ${(rss / 1e6).toFixed(1)} MB`);
}, 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.

1. Run `node --inspect server.js` and open `chrome://inspect`.
2. Take a heap snapshot once the app has warmed up.
3. Send traffic for a few minutes, for example with a load testing tool.
4. Take a second snapshot, then a third after more traffic.
5. 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.


```bash
# Write a snapshot whenever the process receives SIGUSR2
node --heapsnapshot-signal=SIGUSR2 server.js
kill -USR2 <pid>

# Write up to 2 snapshots as the heap nears its limit
node --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:


```javascript
// Entries disappear when the key object is no longer used elsewhere
const metadata = new WeakMap();

function tag(req, info) {
  metadata.set(req, info);
}
```


Remove listeners and timers when you are done with them, or register them once outside request handlers:


```javascript
const onData = (chunk) => handle(chunk);
stream.on('data', onData);

stream.once('close', () => {
  stream.off('data', onData);
  clearInterval(timer);
});
```


Then repeat the snapshot comparison to confirm the count stays flat.


## Common pitfalls

- **Raising the memory limit to hide it.** `--max-old-space-size` buys 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.** `MaxListenersExceededWarning` is 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

- [Node.js: Using heap snapshots](https://nodejs.org/en/learn/diagnostics/memory/using-heap-snapshot)
- [Node.js: Command-line options](https://nodejs.org/api/cli.html)
