← Debugging Guides

阅读中文版本

Memory Leak via Closures — Unintentional Retention

Diagnose memory leaks where closures unintentionally retain large objects, preventing garbage collection even after they are unused.

advanceddebuggingjsphase-16

Symptoms

  • Process memory (heap/RSS) grows steadily and never returns to baseline even after idle.
  • Error message: (No error — heap memory grows steadily; RSS keeps rising in production)
  • Failure occurs intermittently or after a specific code path

Possible causes

  • A closure captures a large object reference that is never released.
  • Event listeners or timers reference the closure, keeping it alive indefinitely.
  • Environment or runtime version mismatch introduces the defect

Diagnosis steps

Reproduce the error in a minimal isolated test case

node -e "require('./repro')"

Interpretation

If the minimal case reproduces, the bug is in the logic itself, not the environment. If not, collect environment details.

Capture the full error stack trace and identify the originating line

Set NODE_OPTIONS=--stack-trace-limit=100 and run with verbose logging

Interpretation

The first frame in user code is the trigger. Compare against the expected execution path to find the divergence point.

Inspect the values of all variables at the failure point

Add console.log / debugger / breakpoint at the line before the throw

Interpretation

Check for undefined, null, wrong type, or unexpected shape. The error message tells you what was wrong; the variables tell you why.

Root cause

A closure holds a reference to a large object through its scope chain, and an external reference (listener, timer, map) keeps the closure alive, so GC cannot collect the object.

Fix

Null out the captured reference when done, remove listeners/timers, or use WeakRef/WeakMap for optional retention.

Risk note

Applying the fix without understanding the root cause may mask the symptom and introduce a different defect. Always verify with the reproduction case.

Verify the fix

Use --inspect to take heap snapshots before and after; confirm the leaked object is collected after the fix.

Symptom and Error Message

When running the JavaScript code, the runtime raises the following error:

(No error — heap memory grows steadily; RSS keeps rising in production)

This error indicates that process memory (heap/rss) grows steadily and never returns to baseline even after idle. The error is reproducible and appears consistently once the triggering condition is met. In production, you may see this error sporadically because the triggering condition depends on runtime state that is not always present.

Root Cause Analysis

The fundamental cause is: a closure holds a reference to a large object through its scope chain, and an external reference (listener, timer, map) keeps the closure alive, so gc cannot collect the object. Two factors converge to produce the visible error. First, a closure captures a large object reference that is never released. Second, event listeners or timers reference the closure, keeping it alive indefinitely. Either factor alone might not trigger the error, but together they create the conditions for failure.

Diagnosis Walkthrough

Start by reproducing the error in isolation. Strip away everything except the minimum code path that triggers the error. Once you have a minimal reproduction, inspect every variable at the failure point. Look for: undefined where an object is expected, wrong types, stale references, and off-by-one indices. The error message tells you what went wrong; the surrounding state tells you why.

Fix and Code Example

// Before (buggy)
// ... code that triggers the error ...

// After (fixed)
// ... corrected code with proper guard or type check ...

The fix addresses the root cause directly: null out the captured reference when done, remove listeners/timers, or use weakref/weakmap for optional retention. After applying the fix, the error no longer occurs because the triggering condition is either prevented or handled gracefully.

Verification

Use –inspect to take heap snapshots before and after; confirm the leaked object is collected after the fix. Run the reproduction case again and confirm the error is gone. Then run the full test suite to check for regressions. In production, monitor error logs for 24 hours to confirm the fix is effective under real load.

Common Pitfalls

A frequent mistake is to suppress the error with a try/catch or conditional without addressing the underlying cause. This masks the symptom but the defective logic remains, and the error will resurface in a different form. Always fix the root cause, not just the error message. Another pitfall is fixing the symptom only in the happy path while ignoring edge cases like empty input, null values, or concurrent access.