open atlas
↑ Back to track
JavaScript Engine internals JSE · 06 · 05

Leaks in a garbage-collected language

A leak here is unintended retention: a live reference keeps a dead-in-spirit object reachable. A field guide to the real causes — timers, listeners, growing caches, closures pinning a Context, detached DOM, sliced strings, globals

JSE Senior ◷ 15 min
Level
FoundationsJuniorMiddleSenior

A Node service starts at 180 MB RSS and climbs 40 MB a day. No crash, no error, no obvious culprit — the code “doesn’t allocate anything it doesn’t free”, because in JavaScript you don’t free anything. The GC is working perfectly. That is exactly the problem: every byte it refuses to reclaim is reachable, and something in your code is keeping it that way. A leak in a GC’d language is never a missing free; it is a reference you forgot you still hold.

Retention, not “forgetting to free”

From lesson 01: the GC keeps everything reachable from a root, because reachability over-approximates liveness. A leak in a garbage-collected language is the over-approximation biting back — an object you are logically done with stays reachable through some reference you did not intend to keep. The GC is correct to retain it; the bug is in your reference graph, not in the collector.

So leak hunting is never “where did I forget to free?” It is “what is the retainer path?” — the chain of references from a root down to the leaked object. Cut any link on that path and the object becomes unreachable and gets collected. The fix is always severing a reference, never freeing.

This builds directly on closures pinning their Context (05-closures-scope/02-closure-memory): a closure is one of the commonest accidental retainers, because it keeps its whole captured environment alive for as long as the closure itself is reachable.

A field guide to real retainers

1. Timers and intervals that are never cleared. setInterval keeps its callback reachable forever from the runtime’s timer table; the callback’s closure keeps everything it captured alive.

function startPolling(bigState) {
  setInterval(() => check(bigState), 1000);  // bigState pinned forever
}
// fix: const id = setInterval(...); clearInterval(id) on teardown

2. Event listeners never removed. el.addEventListener('x', handler) makes the target retain handler, and handler’s closure retains whatever it captured. On SPA route changes this accumulates.

window.addEventListener('resize', onResize);  // retains onResize + its closure
// fix: window.removeEventListener('resize', onResize) on unmount

3. Unbounded caches — Map/array/Set used as a cache that only grows. The container is module-scoped (a root), so every entry is retained until removed. Without a cap or TTL, it grows monotonically.

const cache = new Map();
function memo(key, compute) {
  if (!cache.has(key)) cache.set(key, compute(key));  // never evicted
  return cache.get(key);
}
// fix: LRU with a max size, or a TTL, or WeakMap if keyed by an object

4. Closures sharing a Context that pins a big variable. Multiple closures from the same scope share one Context object; if any closure is long-lived, the whole Context — including a huge variable only another closure used — stays alive. (See 05-closures-scope/02-closure-memory.)

5. Detached DOM nodes still referenced from JS. You remove a node from the document, but a JS variable, array, or closure still references it. The node — and its entire subtree — cannot be collected. In browsers this also keeps detached windows/iframes alive, a heavy leak.

6. SlicedString pinning a huge parent. huge.slice(0, 10) in V8 can produce a SlicedString that references the original string rather than copying 10 chars, so a tiny substring keeps a multi-megabyte parent alive. Force a copy when you keep a small slice of a large string.

7. Global accumulation. Anything hung off globalThis / window (or a module-level singleton) is rooted for the process lifetime. An accidental global (x = 1 without declaration in sloppy mode) is a classic.

8. “Collected but not returned to the OS.” Sometimes the object is collected but RSS does not drop: the heap was fragmented, so V8 holds the pages. This is not a JS-level leak — it is fragmentation (lesson 03’s compaction territory), diagnosed differently (RSS high, heapUsed low).

What unites all eight patterns: each one is an unintended root-to-object path. Without it the GC would collect freely; with it the GC is merely doing its job. When you see RSS climb on a production service, mentally trace the chain — container → closure → object — until you find the link that does not belong.

Weak references: let the GC win the tie

When you need to associate data with an object without keeping that object alive, use a weak reference, which the GC ignores when computing reachability:

  • WeakMap / WeakSet — keys (WeakMap) or values (WeakSet) are held weakly. When the only remaining references to a key object are weak, the entry is collectible automatically. Perfect for per-object metadata caches keyed by the object itself — no manual eviction, no leak.
  • WeakRef — a weak reference to a single object; .deref() returns the object or undefined if it has been collected. For caches where you want the value to disappear under memory pressure.
  • FinalizationRegistry — register a cleanup callback that may run after an object is collected. Use sparingly: finalizers are not guaranteed to run, run at an unspecified time, and must never be relied on for correctness — only for best-effort cleanup of external resources.
const meta = new WeakMap();          // keyed by DOM node, say
meta.set(node, { lastSeen: now });   // does NOT keep `node` alive
// when `node` is removed and otherwise unreferenced, the entry vanishes
Leak field guide
Root cause (always)
unintended reachability
The fix (always)
cut the retainer path
Top Node leak
unbounded Map / Set cache
Top browser leak
listeners + detached DOM
Per-object metadata
WeakMap (auto-evicts)
RSS high, heapUsed low
fragmentation, not a leak
Quiz

A heap snapshot shows 50,000 'request context' objects that should be transient. What is the single most useful thing to look at to fix the leak?

Quiz

You want to cache computed metadata per DOM node, but the cache must not keep removed nodes alive. Which structure fits?

Order the steps

Order the workflow to diagnose and fix a slow retention leak.

  1. 1 Confirm growth: RSS / heapUsed climbs monotonically over time
  2. 2 Take heap snapshots at intervals and diff them to find the object type growing unbounded
  3. 3 Open the retainer path from a growing object up to its GC root
  4. 4 Identify the unintended reference on that path (timer, listener, cache entry, closure)
  5. 5 Sever it (clearInterval/removeEventListener/evict/WeakMap) so the subtree becomes unreachable
  6. 6 Re-snapshot to confirm the object count is now bounded
Common mistake

A subtle one: reaching for WeakRef/FinalizationRegistry to “fix” a leak that is really an unbounded cache. Finalizers do not run promptly or reliably, so they will not bound your memory under load — and code that depends on a finalizer running is buggy by construction. The right fix for a growing cache is a real eviction policy (LRU, max-size, TTL). Reserve WeakMap for associative per-object data and WeakRef for genuinely optional caches, not as a band-aid over missing eviction.

Recall before you leave
  1. 01
    Why can you still leak memory in a garbage-collected language, and what is the general fix?
  2. 02
    List the most common concrete retainers and their fixes.
  3. 03
    When should you use WeakMap, WeakRef, and FinalizationRegistry, and what is the trap?
Recap

In a tracing GC, a memory leak is never a missing free — it is unintended retention. The collector keeps every object reachable from a root, and reachability over-approximates liveness, so an object you are logically done with stays alive whenever a reference you forgot still points to it. Diagnosis is therefore about the retainer path: the chain of references from a GC root down to the leaked object. The common concrete retainers are uncleared timers, un-removed event listeners, unbounded Map/Set/array caches, closures whose shared Context pins a large captured variable, detached DOM nodes (and windows/iframes) still referenced from JS, a SlicedString holding a huge parent, and global or module-scope accumulation. Every fix is the same shape: sever a link on the retainer path so the subtree becomes unreachable — clearInterval, removeEventListener, evict, copy the slice, or key the data weakly. WeakMap/WeakSet give automatic per-object associations the GC ignores, WeakRef gives optional caches, and FinalizationRegistry gives best-effort cleanup — but none of them substitute for a real eviction policy, and finalizers must never be relied on for correctness. Finally, distinguish a true retention leak (heapUsed grows) from fragmentation (RSS high, heapUsed low). Now when you see RSS climbing on a production Node service and the GC logs look clean, your first instinct should be to take a heap snapshot and read a retainer path — not to force GCs or raise the heap limit.

Practice

Start at the top. Tasks go easiest → hardest: recall a fact, apply it to a case, then a senior-level stretch. Open one, attempt it, then reveal.

recallapplystretch0 of 7 done
Connected lessons
appears again in184

Something unclear?

Ask a question about this lesson. Questions are anonymous and go straight to the author to make the lesson better.

shortcuts expand
search
K
prev piece
k
next piece
j
cycle tier
t
this menu
?
sources3
expand
  1. 01
  2. 02
  3. 03

Trademarks belong to their respective owners. Editorial reference only.