liveBook · Manning

Memory leak

As explained in JavaScript in Depth

A condition in which memory remains retained or allocated despite no longer being needed by a program.

A process’s memory can keep rising even though it has finished using the data it allocated. A memory leak occurs when code still holds a reference to an unneeded object, preventing the garbage collector from reclaiming it. Rising memory alone is not proof: temporary allocation pressure can also enlarge the heap. section 11.2 section 11.2.2

Closures expose a less obvious route to retention. In V8, a function that captures an outer variable references a heap-allocated Context. That Context can outlive the outer call. A returned function that reads only an ID may therefore keep a large processed string in scope alive too. V8 may optimize unused captures away, but that is not guaranteed; separating data processing from creation of the returned function limits what it can retain. section 6.4

function processData() {
  const str = 'a'.repeat(1_000_000);
  const id = generateId();
  processStr(str);
  return function getId() {
    return id;
  };
}
const getId = processData();

The returned getId function uses id, not str. Inspect the enclosing scope to see why the million-character string may remain retained. section 6.4

A registered listener creates another long-lived reference. If its surrounding scope contains large data, leaving the listener installed can prolong that data’s lifetime. Keep a reference to the handler and remove it when the work ends; a finally block can make cleanup explicit. section 6.4

Diagnose retention in order:

  • Confirm the symptom. Sample process.memoryUsage() under load and compare post-collection heapUsed troughs, not just peaks. Stable troughs fit ordinary collection; rising troughs indicate accumulating survivors. section 11.2.1
  • Identify the growing metric. Rising heapUsed points toward JavaScript objects; rising external with stable heapUsed points toward Buffers or ArrayBuffers. Rising rss alone needs care: on Bun, allocator retention can raise rss without a JavaScript heap leak. section 11.2.1 section 11.1.1
  • Distinguish leak from pressure. Under --trace-gc, stable mu and a return to baseline after load stops favor pressure. Declining mu or a baseline that stays elevated favors a leak. section 11.2.2
  • Find what accumulates, then find the reference retaining it. Reduce allocation rate or object lifetime for pressure; remove the unnecessary reference for a leak. section 11.2 section 11.2.2

How JavaScript in Depth covers it

How deep it goes
Works through a four-step diagnostic flow and V8 closure retention, while detailing only the flow’s first two steps.
Examples
Uses a closure retaining a million-character string, an event listener, and rising post-collection heap troughs.
What it assumes
Assumes familiarity with JavaScript functions and runtime memory metrics, while defining a leak and explaining closure retention.
What you can do after
Diagnose/debug with it by checking memory baselines, separating leaks from pressure, and removing references that retain unneeded objects.
How it connects
Connects memory leaks to closures, garbage collection, allocation pressure, event listeners, and process memory metrics.

Also explained in

Compare how 9 books explain memory leak →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.