Skip to the page

Errors, memory and request context · senior

Memory leaks and heap snapshots

A memory leak in Node is memory that stays reachable when it should not, usually from unbounded caches, listeners or timers that are never removed, or closures holding big objects; you find it by comparing heap snapshots taken over time.

The notes

What you must know

  • The V8 heap has a young generation (short-lived objects, quick scavenges) and an old generation (long-lived objects, mark-sweep-compact). GC only frees objects nothing references.
  • Common leaks: a module-level Map or array used as a cache with no size limit or TTL; adding event listeners per request; setInterval never cleared; closures capturing large objects; keeping request objects in global state.
  • Signs: heapUsed/RSS from process.memoryUsage() climbs under steady traffic, GC pauses get longer, then 'JavaScript heap out of memory' or the container is OOM-killed.
  • Find it: run with --inspect and take heap snapshots in Chrome DevTools (or v8.writeHeapSnapshot(), --heapsnapshot-signal=SIGUSR2, --heapsnapshot-near-heap-limit=3). Take three snapshots under load, compare which object counts keep growing, and read the retainers path.
  • Fix: bounded caches (LRU with a max size and TTL), remove listeners (off, once, AbortSignal), clear timers, WeakMap for per-object metadata.
  • --max-old-space-size sets the old-generation limit in MiB; in containers keep it below the container limit (or use --max-old-space-size-percentage). Raising it only delays a leak.

The red pen

Common traps: mistake → fix

  • Mistake: Garbage collection means JavaScript cannot leak

    Fix: anything still referenced (global Map, listener, timer) is never collected.

  • Mistake: Raise --max-old-space-size to fix the crash

    Fix: that only delays it; find what keeps growing.

  • Mistake: One heap snapshot shows the leak

    Fix: compare several snapshots over time; one only shows what is big right now.

Easy to hard

Questions interviewers ask, easy to hard

  1. Can a garbage-collected language leak memory? How, in Node?
  2. Memory grows 50 MB an hour in production. Walk me through finding the cause.
  3. What is a heap snapshot and what do you look for in it?
  4. How do you design an in-memory cache that cannot leak?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview