← Runtimes
Runtimes

Leaks in garbage-collected programs

Caches, listeners and closures that keep values reachable.

Trace retained data to the structure that still owns it after its intended work ends.

Outcome

Find the long-lived structure that keeps finished data reachable, remove that path when the data’s owner finishes, and give caches an explicit bound.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Retention
Keeping a value reachable, on purpose or by mistake.
Leak (in a collected program)
Data the program has finished with that is still reachable from a long-lived root.
Bounded cache
A cache with an enforced limit on a stated quantity, such as entries or bytes, and a policy that evicts when needed. A count limit alone does not bound bytes.
Least recently used (LRU)
An eviction rule that drops the entry that has gone longest without a lookup.
Heap snapshot
A snapshot of the captured V8 heap and its retaining relationships. Native/external allocations and other process memory need separate accounting.

When retention becomes a leak

Retention means that a reference or owner keeps a value available. It becomes an application leak when that lifetime extends beyond the value’s purpose. Automatic memory management cannot infer that purpose from the program’s references, and safe counted ownership can also retain data longer than intended.

Investigate the path from a long-lived structure to the retained value: an intermediate callback, closure or view can matter as much as a direct entry. Then compare that path’s lifetime with the work it serves. An intentional cache also needs an enforced limit on a stated quantity, such as entries or bytes.

01Listeners

What keeps a closed page’s data alive?

A closed price-report page still receives market updates, and its 100000-row report remains retained. Follow the subscription from the long-lived listener table before changing collection settings. Once that page’s subscription is removed, investigate a second path: the service’s shared cache retains a rendered response for every new URL.

A page opens, builds a large report and subscribes a callback to price updates. The callback refers to the report. Then the page closes without unsubscribing.

Each program checks whether the report still exists after the page closes, and again after the listener is removed.

The module-held listener array reaches the captured report in this source. WeakRef resolves an optional target; creating/dereferencing it keeps its result usable during the current job, without permanent strong ownership.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A page subscribes to price updates and then closes without unsubscribing.
// Run with node --expose-gc so the program can ask for a collection.

type PriceReport = { rows: number[] };
type Listener = (price: number) => void;

const listeners: Listener[] = [];
let watched: WeakRef<PriceReport> | undefined;

function openPage(): void {
  const report: PriceReport = { rows: new Array(100_000).fill(0) };
  watched = new WeakRef(report);
  const onPrice: Listener = (price) => report.rows.push(price);
  listeners.push(onPrice);
}

const nextTask = () => new Promise((resolve) => setTimeout(resolve, 0));
const collect = (globalThis as { gc?: () => void }).gc ?? (() => {});

async function main(): Promise<void> {
  openPage();
  // The page closes here; nothing in the page's own code refers to report.

  await nextTask();
  collect();

  console.log(`after close: report alive ${watched?.deref() !== undefined}`);

  listeners.length = 0;
  await nextTask();
  collect();

  console.log(`after unsubscribe: report alive ${watched?.deref() !== undefined}`);
}

void main();
What did the program print in the recorded Node run?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --strict && node --expose-gc main.ts

The quoted outputs are historical observations, not new runs. Node --expose-gc permits a collection request but does not guarantee WeakRef clearing; the Go probe’s runtime.GC plus 50-millisecond sleep does not guarantee cleanup execution. Removing the final strong path changes eligibility. It does not promise a print deadline, reclaimed-byte count or OS memory drop.

02Caches

When is a cache a leak?

A cache keeps results reachable on purpose. It becomes a leak when nothing limits it: each new key adds an entry that stays until the process ends.

Choose the quantity to bound and enforce eviction: entry count, total key/value bytes, or both. An age rule must actually remove entries; TTL alone gives no finite bound under arbitrary arrival rate, large values or stale entries left in storage. LRU chooses the least recently used entry, refreshing recency on a hit.

Common paths that keep finished data reachable
PathSymptomFix
Listener or callback listClosed things still receive eventsUnsubscribe when the owner closes
Unbounded cache or global mapMemory grows with traffic and never fallsBound it and evict, or remove entries when their work ends
Timer, retry or goroutineWork keeps running for something that is goneUse that API’s cancellation signal and completion protocol; dropping a handle may detach rather than stop work
Small view of a large bufferA few bytes keep a large allocationCopy the retained range when independent ownership is needed; a view can retain the backing allocation
A service caches every rendered page by URL in a map that lives as long as the process. Nothing ever removes an entry. Over a week, memory climbs while the collector runs normally. What is wrong?

03Weak maps

Can weak references fix a leak?

Weak-key associations can attach metadata to a separately owned object, such as a DOM node, without being the sole reason that key survives. WeakMap uses ephemeron-style key/value reachability; it is not just a Map of WeakRef values. A WeakRef lookup instead gives an optional target, with no collection deadline.

JavaScript permits object and nonregistered-symbol weak keys, but not string request IDs or registered symbols. Even valid keys do not establish a count or byte limit, especially when other owners keep them live.

A team stores per-request data in a map keyed by the request’s ID string, and someone suggests switching to a weak map so entries go away by themselves. Will that bound the map?

04Practice

Finish the session hub

The lab is one session hub. It reads visitor sessions, subscriptions and cache lookups from stdin, and retained reports what the hub’s tables still hold. It models retention by counting those tables; it does not measure real memory. Each level supplies the parts that already work.

The session hub

Let closed sessions go, unsubscribe on close, then bound the shared cache.

  1. easy · R-LEAK-V4-1 Let closed sessions go
  2. medium · R-LEAK-V4-2 Unsubscribe on close
  3. hard · R-LEAK-V4-3 Bound the cache
In the frontend Review a subscription owner Optional

This is an incomplete subscription handler under review. The feed returns a disposal function, but the handler discards it. Follow feed → callback → report, then identify which component lifetime must own that registration. Changing the report or closing the panel does not itself tell this external feed to remove its callback.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

import { useEffect, useState } from "react";

type Feed = { subscribe: (listener: (price: number) => void) => () => void };
type Report = { rows: number[] };

export default function ReportWatch({ feed, report }: { feed: Feed; report: Report }) {
  const [label, setLabel] = useState("Waiting for price");

  useEffect(() => {
    const held = report;
    // Under review: the returned disposal function is discarded.
    feed.subscribe((price) => setLabel(held.rows.length + " rows at " + price));
  }, [feed, report]);

  return <output>{label}</output>;
}

The callback reads the report after registration. React can invoke effect setup/cleanup more than once in development; this diagnostic supplies no cleanup. Inspect the subscription API and owner before treating a closed panel as released.

Sources: React: effects with external systems,Svelte: effect dependencies and teardown.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.