memory-leak-debugging
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.heapsnapshotfiles directly — they are extremely large and will consume too many tokens. Always usememlabto 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:
- Use tools like
click,navigate_page,fill, etc., to manipulate the page into the desired state. - Revert the page back to the original state after interactions to see if memory is released.
- Repeat the same user interactions 10 times to amplify the leak.
- Use
take_memory_snapshotto save.heapsnapshotfiles to disk at baseline, target (after actions), and final (after reverting actions) states.
2. Using Memlab to Find Leaks (Recommended)
Once you have generated .heapsnapshot files using take_memory_snapshot, use memlab to automatically find memory leaks:
npx memlab analyze --snapshot-dir /path/to/snapshotsDo 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
windowor 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.