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
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 teardown2. 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 unmount3. 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 object4. 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 orundefinedif 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- 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
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?
You want to cache computed metadata per DOM node, but the cache must not keep removed nodes alive. Which structure fits?
Order the workflow to diagnose and fix a slow retention leak.
- 1 Confirm growth: RSS / heapUsed climbs monotonically over time
- 2 Take heap snapshots at intervals and diff them to find the object type growing unbounded
- 3 Open the retainer path from a growing object up to its GC root
- 4 Identify the unintended reference on that path (timer, listener, cache entry, closure)
- 5 Sever it (clearInterval/removeEventListener/evict/WeakMap) so the subtree becomes unreachable
- 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.
- 01Why can you still leak memory in a garbage-collected language, and what is the general fix?
- 02List the most common concrete retainers and their fixes.
- 03When should you use WeakMap, WeakRef, and FinalizationRegistry, and what is the trap?
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.
appears again in184
- Why GraphQL gets N+1junior
- DataLoader mechanics: tick-boundary batchingmiddle
- Batch function contracts: ordering, shapes, errorsmiddle
- Federation and lookahead: batching beyond DataLoadermiddle
- Query complexity defences: depth, cost, persisted queriesmiddle
- Senior GraphQL API: scheduling contract, tenant isolation, observabilitysenior
- Why idempotency: making retries safejunior
- Server-side state machine: four states of an idempotency keymiddle
- Outbox and inbox: effectively-once across the dual-write boundarymiddle
- Concurrency and cache architecture for idempotency at scalesenior
- Observability, production failures, and global-scale designsenior
- The event loop: one thread, three queuesjunior
- Tasks, microtasks, and scheduler.yield()middle
- Microtask starvation, Long Tasks, and LoAFsenior
- Node.js event loop: phases, nextTick, and loop lagsenior
- React, Vue, and INP observability in productionsenior
- The render pipeline: six stages from bytes to pixelsjunior
- Stage costs and the renderer process modelmiddle
- Invalidation, dirty bits, and containmiddle
- Compositor layers: promotion, overlap, and GPU memorymiddle
- DevTools flame strip and the frame lifecyclemiddle
- Layout thrash: forced synchronous layoutsenior
- BeginMainFrame, compositor-driven animations, and GPU memorysenior
- Production observability: LoAF, INP, and the full attack surfacesenior
- What V8 is and why performance varies 100×junior
- V8''''s four-tier JIT pipeline and profile-guided tieringmiddle
- Hidden classes, transition trees, and memory layoutmiddle
- Inline caches, IC states, and deoptimizationmiddle
- Orinoco GC: parallel scavenger, concurrent marking, and write barriersmiddle
- TurboFan''''s speculative engine and the deopt-loop trapsenior
- V8 in production: isolates, pointer compression, and real failuressenior
- Service worker lifecycle and cache strategiesmiddle
- Service worker edge cases: version skew, durability, and navigation trapssenior
- What the reconciler does: render vs commitjunior
- The fiber object and the double-buffer treemiddle
- Render phase purity and commit phase sub-stepsmiddle
- Reconciliation: diffing heuristics and the key trapmiddle
- Priority lanes, time-slicing, and useTransitionmiddle
- Bailout, memoisation, and tearingsenior
- React Profiler, the Compiler, and production observabilitysenior
- Rendering strategies: SSG, SSR, ISR, streaming, and hydrationjunior
- SSG, SSR, ISR, streaming, and RSC — how each worksmiddle
- Hydration cost: selective, progressive, islands, resumabilitymiddle
- Hydration mismatch: causes, detection, and the determinism rulesenior
- RSC, per-route strategy, and production observabilitysenior
- Core Web Vitals: what LCP, INP, and CLS measurejunior
- CLS: why layout shifts happen and how to stop themmiddle
- Metric tradeoffs, RUM attribution, and the CI+field loopsenior
- The full picture: URL to LCP to INP as a relay racejunior
- Eight layers traced: from the service worker to the second navigationmiddle
- Five canonical breaks: where production reliably diessenior
- The three-track method: reading traces and building a monitored systemsenior
- What is a cache stampede and why it makes things worsejunior
- Lock and single-flight: bounding concurrent rebuildsmiddle
- XFetch: coordination-free probabilistic early expirationmiddle
- Stale-while-revalidate and CDN request coalescingmiddle
- Detecting stampedes and designing TTL for productionmiddle
- Metastable failure, fencing tokens, and production postmortemssenior
- What a relation is: tables, rows, keys, and constraintsjunior
- Constraints, keys, and Postgres data typesmiddle
- Normal forms, denormalization, and why schemas stickmiddle
- JSONB, arrays, and when a side table winsmiddle
- Heap storage, TOAST, and column alignmentsenior
- Schema integrity: deferral, versioning, and production failure modessenior
- Relational vs document, wide-column, graph, and key-valuesenior
- Index-only scans, the Visibility Map, and INCLUDEsenior
- Production failure modes and the index audit playbooksenior
- pg_statistic, ANALYZE, and production observabilitymiddle
- Production failure modes and plan stabilitysenior
- MVCC: why readers and writers never wait for each otherjunior
- Row versions and snapshots: the on-disk mechanicsmiddle
- HOT updates and isolation levels: what you gain and what you paymiddle
- Vacuum and bloat: keeping the storage tax boundedmiddle
- CLOG, XID wraparound, and MultiXact: deep visibility internalssenior
- SSI internals and production autovacuum tuningsenior
- Real-world MVCC failures, deployment patterns, and distributed snapshotssenior
- Connection pools: amortising the cost of a Postgres backendjunior
- PgBouncer session, transaction, and statement modesmiddle
- Pool sizing: the (cores × 2) + spindles formula and the two-layer stackmiddle
- Pool exhaustion and idle-in-transaction: the 3 AM failure modemiddle
- Migrating to transaction mode: rollout playbook and PgBouncer 1.21 prepared statementsmiddle
- The Postgres process model and why raising max_connections degrades throughputsenior
- Pooler landscape 2026, serverless connection storms, and the full failure-mode taxonomysenior
- What a schema migration is and why it replaces ad-hoc DDLjunior
- ADD COLUMN: instant in PG 11+ vs rewrite in older Postgresjunior
- The lock-queue failure mode: why instant DDL can freeze the databasemiddle
- Safe DDL patterns: NOT VALID, CONCURRENTLY, and unsafe-op fixesmiddle
- Expand-contract: zero-downtime for breaking schema changesmiddle
- Advisory locks, migration tools, and deploy coordinationsenior
- Migration failure taxonomy and production disciplinesenior
- Why sharding exists: the single-Postgres ceilingjunior
- Shard-key selection: hash, range, list, and directory strategiesmiddle
- Partitioning vs sharding: same word, two different thingsmiddle
- Co-location and Citus: the invariant that makes sharding usablemiddle
- The hot-shard failure mode: detection, isolation, and durable policymiddle
- Schema-based sharding and multi-tenancy alternativessenior
- Online resharding, 2PC, and the operational cost of shardingsenior
- The seven acts: from CREATE TABLE to Citusjunior
- Acts 1–3 in depth: schema, indexes, and planner statisticsmiddle
- Acts 4–6 in depth: MVCC bloat, connection pooling, and safe migrationsmiddle
- Act 7 in depth: sharding, co-location, and the seven-tier tradeoff cascademiddle
- Observability, anti-patterns, and production triagesenior
- Raft roles, terms, and why majority quorums prevent split brainjunior
- How Raft replicates a log entry and decides it is safe to commitmiddle
- Raft leader election: timeouts, voting rules, and the four safety propertiesmiddle
- Raft in the real world: partitions, slow disks, and client routingmiddle
- Raft extensions: pre-vote, learners, snapshots, and linearizable readssenior
- Raft in production: membership changes, Multi-Raft, and observabilitysenior
- Where data fetching happens — and why it decides LCPjunior
- Fetch waterfalls — diagnosis and the Promise.all curemiddle
- React Server Components and Suspense streamingmiddle
- Client-side cache: TanStack Query, SWR, and stale-while-revalidatemiddle
- LCP, prefetch, and race conditions in interactive fetchingmiddle
- Senior internals: RSC payload, caching layers, and production failure modessenior
- The three-way handshakejunior
- Sequence numbers and connection statemiddle
- DNS: what it does and why it existsjunior
- The resolver walk: referrals, record types, and gluemiddle
- TTL, caching, and DNS propagationmiddle
- The 1-RTT handshake: key shares and ECDHEmiddle
- Session resumption and 0-RTTmiddle
- WebSocket: the HTTP upgrade handshakejunior
- WebSocket frame format: opcodes, masking, fragmentationmiddle
- WebSocket backpressure: when clients can''''t keep upmiddle
- Reconnection: jittered backoff, thundering herd, message resumptionsenior
- WebSocket at scale: HTTP/2 multiplexing, permessage-deflate, C10Msenior
- WebSocket in production: proxies, security, and distributed architecturesenior
- What reverse proxies dojunior
- Health checks, connection draining, and slow startmiddle
- Session affinity, consistent hashing, and the right fixmiddle
- Retry storms, circuit breakers, and load sheddingsenior
- Resilient LB architecture: anycast, zone-aware routing, and observabilitysenior
- Why QUIC and not TCP+TLSjunior
- Connection IDs and network migrationmiddle
- 0-RTT resumption and packet encryptionsenior
- DDoS: what it is and why it worksjunior
- Amplification attacks and state exhaustionmiddle
- Rate limiting: algorithms and architecturemiddle
- WAFs, firewalls, mTLS, and HSTSmiddle
- DNS cache poisoning and BGP hijackingsenior
- Defense-in-depth architecture and attack economicssenior
- DNS, TCP, TLS in sequence: where the milliseconds gomiddle
- Proxy intercepts and security gates: rate limiters, WAF, mTLSmiddle
- Alternate paths: QUIC 0-RTT, WebSocket upgrade, connection migrationmiddle
- Observability: distributed traces, USE/RED, and samplingsenior
- Resilience: cascading retries, circuit breakers, and error budgetssenior
- What the three signals are: logs, metrics, and tracesjunior
- Why structured logs exist: the diary vs the spreadsheetjunior
- The production log schema: fields every line must carrymiddle
- PII redaction and log injectionsenior
- OTel Logs Data Model and audit logs as a subsystemsenior
- SLI, SLO, and the error budget: reliability by the numbersjunior
- Error budget policy, latency SLOs, and composite journeysmiddle
- Production SLO failures, self-observability, security, and the big picturesenior
- The incident loop: from pager to postmortem to preventionmiddle
- Cache lines, struct layout, and false sharingmiddle
- SIMD, SoA vs AoS, and memory bandwidthmiddle
- Cache-oblivious algorithms, PGO, and production failuressenior
- GC in production: observability, security, edge cases, and fleet governancesenior
- Batching: amortize fixed cost per operationjunior
- The batching window: size and wait timemiddle
- Batching in Kafka and Postgresmiddle
- io_uring and observability of batchingmiddle
- From Nagle to io_uring: evolution of batchingmiddle
- Backpressure, failure isolation, and batch security in productionsenior
- CI enforcement and RUM: making budgets stickmiddle
- V8 JIT pipeline, HTTP priorities, and bundle securitysenior
- The performance loop: discipline, not a projectjunior
- Classify and fix: matching bottleneck families to remediesmiddle
- Observability stack and CI gates: catching regressions before they shipmiddle
- Incident to enforcement: SLO burn to verified fix in 35 minutesmiddle
- Culture, economics, and org-scale performancesenior
- At-most-once, at-least-once, exactly-once: the three delivery contractsjunior
- The three failure legs — where duplicates and losses actually happenmiddle
- Consumer-side dedup: the cheapest path to exactly-once processingmiddle
- Kafka exactly-once semantics: idempotent producer and transactionsmiddle
- SQS visibility timeout, DLQ, and the outbox patternmiddle
- Exactly-once in production: impossibility proof, hybrid patterns, and real incidentssenior
- What OAuth is and why passwords are not the answerjunior
- Authorization code flow with PKCEmiddle
- ID token validation and JWKS cache managementmiddle
- Refresh token rotation and scope-based least privilegemiddle
- Sender-constrained tokens: DPoP and mTLSsenior
- OAuth in production: audience attacks, observability, and real failuressenior
Something unclear?
Ask a question about this lesson. Questions are anonymous and go straight to the author to make the lesson better.