← Back to Node.js, page 6

nodejs-0120 · Hard senior

What do three typical Node.js memory leak case studies look like (an unbounded map, listeners on a shared emitter, a forgotten timer), and how do you confirm each fix?

Case 1: a module-level Map keeps an entry per request and nothing deletes it. Case 2: each request adds a listener to a long-lived emitter and never removes it. Case 3: a setInterval is never cleared and its closure keeps request data alive. Confirm with heapUsed after a forced GC before and after the load, and fix with bounded caches, once or removeListener, and clearInterval.

Full answer

A leak is memory that stays reachable but is no longer needed. Reachability comes from roots: module variables, long-lived objects, active timers, and event listeners.

Case 1: the unbounded map

  • Symptom: the heap grows linearly with traffic and never drops. A heap snapshot shows a Map with millions of entries.
  • Cause: a module-level Map or object used as a cache or session store, with no size limit or expiry.
  • Fix: delete entries when the request ends, use a bounded LRU with a TTL, or use WeakMap when keys are objects that have their own lifetime.

Case 2: listeners on a shared emitter

  • Symptom: MaxListenersExceededWarning appears, or someone raises the limit to silence it, and memory grows. Each listener closure holds its request data.
  • Cause: emitter.on(...) inside a request handler on an emitter that lives for the whole process (a pool, a message bus, process).
  • Fix: use once, remove the listener in a finally block, or use events.once with an AbortSignal. Never silence the warning without understanding it.

Case 3: the forgotten timer

  • Symptom: memory grows and CPU usage creeps up because the intervals keep running.
  • Cause: setInterval created per request or per connection, with no clearInterval when the connection closes. The callback closure keeps its captured objects alive.
  • Fix: store the timer id and clear it on close, use AbortSignal-based timers, and call unref() for timers that must not keep the process alive.

How to prove a fix:

  • Run a repeatable load (for example 1000 simulated requests), force garbage collection (node --expose-gc), then compare heapUsed with the baseline.
  • Repeat the run a few times. A real leak keeps growing and a cache fills up and stops.
  • Compare two heap snapshots and look at the retained size and the retainer path.
  • Add the load test to CI for services that had a leak before.
javascript
const { spawnSync } = require('node:child_process');

// The experiment runs in a child process so that --expose-gc can be used.
const experiment = `
const EventEmitter = require('node:events');
const REQUESTS = 1000;
const heapMB = () => { global.gc(); global.gc(); const m = process.memoryUsage(); return (m.heapUsed + m.arrayBuffers) / 1048576; };
const payload = () => Buffer.alloc(16 * 1024);

function measure(run) {
  const before = heapMB();
  const cleanup = run();
  const during = heapMB() - before;
  if (cleanup) cleanup();
  return during;
}

// Case 1: a module-level Map
const sessions = new Map();
const leakyMap = () => { for (let i = 0; i < REQUESTS; i++) sessions.set('r' + i, payload()); return () => sessions.clear(); };
const fixedMap = () => { for (let i = 0; i < REQUESTS; i++) { sessions.set('r' + i, payload()); sessions.delete('r' + i); } };

// Case 2: listeners on a shared emitter
const bus = new EventEmitter();
bus.setMaxListeners(0); // this switches the warning off, which is how such leaks stay hidden
const leakyListeners = () => { for (let i = 0; i < REQUESTS; i++) { const data = payload(); bus.on('tick', () => data.length); } return () => bus.removeAllListeners('tick'); };
const fixedListeners = () => { for (let i = 0; i < REQUESTS; i++) { const data = payload(); const fn = () => data.length; bus.on('tick', fn); bus.off('tick', fn); } };

// Case 3: timers that are never cleared
const timers = [];
const leakyTimers = () => { for (let i = 0; i < REQUESTS; i++) { const data = payload(); timers.push(setInterval(() => data.length, 1e6)); } return () => timers.forEach(clearInterval); };
const fixedTimers = () => { for (let i = 0; i < REQUESTS; i++) { const data = payload(); clearInterval(setInterval(() => data.length, 1e6)); } };

const cases = [['map', leakyMap, fixedMap], ['listeners', leakyListeners, fixedListeners], ['timers', leakyTimers, fixedTimers]];
for (const [name, leaky, fixed] of cases) {
  const leakedMB = measure(leaky);
  const fixedMB = measure(fixed);
  console.log(name.padEnd(10), 'leaky keeps more than 8 MB:', leakedMB > 8, '| fixed keeps less than 2 MB:', fixedMB < 2);
}
process.exit(0);
`;

const run = spawnSync(process.execPath, ['--expose-gc', '-e', experiment], { encoding: 'utf8' });
process.stdout.write(run.stdout);
if (run.status !== 0) console.log('child failed', run.stderr);

A child process simulates 1000 requests of 16 KB each for every case, forces garbage collection, and compares memory with and without the fix. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): map leaky keeps more than 8 MB: true | fixed keeps less than 2 MB: true listeners leaky keeps more than 8 MB: true | fixed keeps less than 2 MB: true timers leaky keeps more than 8 MB: true | fixed keeps less than 2 MB: true

Key points

  • Leaks are reachable but useless memory.
  • Module-level maps, shared emitters and timers are the usual roots.
  • Do not silence MaxListenersExceededWarning without fixing the cause.
  • Prove a fix with forced GC before and after a repeatable load.
  • Bounded caches, once or removeListener, and clearInterval are the fixes.

Common mistakes

  • Raising setMaxListeners instead of removing the listener.
  • Reading memory without forcing GC and calling normal growth a leak.
  • Using an object as an unbounded cache.
  • Creating timers per request and relying on the process to end.
  • Taking one heap snapshot instead of two to compare.

Follow-ups

  • How would you find which of these three leaks you have using heap snapshots?
  • When is a WeakMap or WeakRef the right fix?
  • How do you make a leak test stable enough to run in CI?

Tips

  • Name the root in each case: module, emitter, timer.
  • Describe how you would prove a fix.
  • Mention that warnings should be investigated.