memory-leak-debugging

Diagnoses and resolves memory leaks in JavaScript/Node.js applications. Use when a user reports high memory usage, OOM errors, or wants to analyse heap snapshots or run memory leak detection tools like memlab.

How to use

Requires the chrome-devtools-mcp server to be running. Capture heap snapshots at baseline, target (after triggering the leak), and final (after reverting) states. Use memlab to automatically find leak traces. Do not read raw .heapsnapshot files directly — they are too large.

System prompt

Memory Leak Debugging

Diagnoses and resolves memory leaks in JavaScript and Node.js applications.

Core Principles

  • Prefer memlab: Do NOT attempt to read raw .heapsnapshot files directly — they are extremely large and will consume too many tokens. Always use memlab to process snapshots and identify leak traces.
  • Isolate the Leak: Determine if the leak is in the browser (client-side) or Node.js (server-side).
  • Common Culprits: Look for detached DOM nodes, unhandled closures, global variables, event listeners not being removed, and caches growing unbounded.

Workflows

1. Capturing Snapshots

When investigating a frontend web application memory leak:

  1. Use tools like click, navigate_page, fill, etc., to manipulate the page into the desired state.
  2. Revert the page back to the original state after interactions to see if memory is released.
  3. Repeat the same user interactions 10 times to amplify the leak.
  4. Use take_memory_snapshot to save .heapsnapshot files to disk at baseline, target (after actions), and final (after reverting actions) states.

Once you have generated .heapsnapshot files using take_memory_snapshot, use memlab to automatically find memory leaks:

npx memlab analyze --snapshot-dir /path/to/snapshots

Do not read raw .heapsnapshot files using read_file or cat.

3. Identifying Common Leaks

When you have found a leak trace (e.g., via memlab output), identify the root cause in the code:

  • Detached DOM nodes: Elements removed from the DOM but still referenced in JS variables or closures.
  • Event listeners: Listeners added to DOM elements or objects that are never removed.
  • Closures: Functions holding references to large objects in their scope.
  • Global variables: Objects accidentally stored on window or module-level variables.
  • Unbounded caches: Maps, Sets, or arrays that grow indefinitely.

4. Fallback: Comparing Snapshots Manually

If memlab is not available, compare two .heapsnapshot files using a Node.js script to filter for the top growing objects by size.