Node.js theorytheory 0/50 · 0%
Performance · hard

39. Memory management and leaks

How V8's garbage collector works and common leak patterns.

V8 automatically reclaims memory no longer reachable from any root reference (globals, the call stack, closures). A memory leak in JavaScript means objects that should be garbage are still reachable — commonly through a growing array/Map that's never cleared, forgotten event listeners, or closures capturing more than intended.

js
// leak: this array grows forever, and the listener is never removed
const cache = [];
emitter.on("data", (chunk) => cache.push(chunk));

// fix: bound growth and remove listeners when done
const cache2 = [];
const MAX = 1000;
function onData(chunk) {
  cache2.push(chunk);
  if (cache2.length > MAX) cache2.shift();
}
emitter.on("data", onData);
// later: emitter.off("data", onData);

`node --inspect` plus Chrome DevTools' heap snapshot tool is the standard way to diagnose a real leak: take two snapshots under load, minutes apart, and compare which object types grew unexpectedly.

Check your understanding

  1. 1. What does a memory leak in JavaScript actually mean?

  2. 2. What is a common cause of leaks in long-running Node servers?

  3. 3. What tool helps diagnose a real memory leak?