How to Prompt an AI Coding Agent to Fix a Memory Leak
Vague prompts produce vague fixes. Here is how to feed an AI coding agent heap snapshot evidence so it finds the actual retained reference instead of guessing.
delete
What actually works is treating the agent like a pair programmer who is very fast at pattern matching but has zero access to your running process. You do the measuring, it does the reading.
Step 1: Capture Two Heap Snapshots, Not a Vibe
.heapsnapshot
Step 2: Give the Agent the Diff, Not the Symptom
A prompt like "the app leaks memory, please fix it" gives the model nothing to anchor on. Instead, hand it the comparison view and ask a narrower question:
Weak prompt | Why it fails | Better prompt |
|---|---|---|
Fix the memory leak in server.js | No evidence, agent pattern-matches to generic causes | Here is a heap snapshot diff showing 40,000 retained EventEmitter listeners after 500 requests. Find where listeners are added without a matching removeListener. |
The app uses too much RAM | Vague symptom, could be leak or just working-set growth | RSS grows 4MB per request and never drops after GC. Compare these two snapshots and identify the top three retained object types by count delta. |
Optimize memory usage | Optimization and leak-fixing are different problems | This class is retained by a closure captured in a setInterval callback that never gets cleared. Show me every setInterval/setTimeout in this file and whether each has a matching clear call. |
Notice the pattern: every strong prompt names a concrete object type, a growth number, or a specific language construct that causes retention (closures, listeners, timers, caches without eviction). That specificity is what turns a coding agent from a guesser into a debugger.
Step 3: Ask It to Trace the Retention Path, Not Just the Symptom Line
Heap snapshot tools show a retainer tree: the chain of references keeping an object alive. Paste that chain into the prompt and ask the agent to explain, in plain terms, which link in the chain should not exist. This is a different task than "find the bug": it is "read this reference graph and tell me which edge is wrong." Coding agents are noticeably better at the second framing because it is closer to code review than to open-ended search.
A useful follow-up prompt once you have a suspect: "assume this closure is the leak. Show me every place this function is created, and for each one, whether the enclosing scope is ever released." That forces the agent to check call sites instead of only the definition, which is where most real fixes live.
Step 4: Make It Prove the Fix, Not Just Propose One
An agent will confidently suggest a change and move on. Do not let it. Ask explicitly: "after this change, what would the second heap snapshot show differently? Name the object type and the expected count." If it cannot answer that, the fix is a guess wearing a diff.
For anything shipping to production, pair this with a short regression check: run the same load pattern before and after the patch and diff the retained size. Coding agents are good at writing that harness for you if you ask directly: "write a script that runs this function 1,000 times and logs process.memoryUsage().heapUsed every 100 iterations."
Common Leak Patterns to Name Explicitly in Your Prompt
Event listeners added in a loop or on every request without a matching removeListener, especially on long-lived objects like a shared EventEmitter or WebSocket server.
Closures captured by setInterval or setTimeout that outlive the component or request that created them.
Module-level caches (a plain object or Map used as a cache) with no eviction policy, growing forever as new keys arrive.
Detached DOM nodes still referenced by a JavaScript variable after removal from the page, common in single-page apps with manual DOM manipulation.
Global arrays used as logs or queues that are pushed to but never trimmed or flushed.
Naming the pattern you suspect, even tentatively, gives the agent a search target. "Check whether this is an event listener leak" produces a focused, verifiable answer. "Why is memory going up" produces speculation.
When to Stop Prompting and Start Profiling Differently
If two or three rounds of this have not narrowed the retainer chain, the leak is probably not in the code the agent can see: it might be a native addon, a database driver connection pool, or a third-party dependency. At that point the more useful prompt is a scoping one: "given this list of dependencies and this retained object type, which of these libraries is known to hold onto connections after use?" That turns the agent into a research assistant instead of a debugger, which is a legitimate and often faster path.
The Same Method Outside Node.js
tracemallocstart()take_snapshot()pprofgo tool pprof -base
Whatever the language, paste the comparison output, not a description of it. "Memory keeps climbing in the Java service" gives the agent nothing. "VisualVM's dominator tree shows 2.1 million retained char[] instances under a HashMap called sessionCache, up from 40,000 at startup" gives it a specific structure to open and a specific question to answer: does anything ever remove entries from sessionCache.
Overcorrections to Watch For
Once an agent has a real lead, it sometimes swings too far the other way and proposes changes broader than the evidence supports. Two overcorrections show up often enough to name in advance:
Wrapping the whole file in defensive null checks and early returns because it is not fully sure where the reference is created, rather than fixing the one call site the retainer chain actually points to.
Replacing a working cache with an unbounded-looking library call (swapping one Map for another abstraction) instead of adding the eviction policy the original cache was actually missing.
If a proposed fix touches more files than the retainer chain mentions, ask it directly to justify each additional change against the evidence. Most of the time it will narrow the diff back down on its own once asked, because the broader version was a hedge, not a finding.
how to pick the right AI coding toolusing an AI coding agent to review a pull requestsandboxing an AI coding agent
FAQ
Can an AI coding agent read a heap snapshot file directly?
Most agents cannot parse the binary .heapsnapshot format itself, but they can reason well over a summary you export from Chrome DevTools or a profiler's comparison view: object type, shallow size, retained size, and count delta. Export that table as text or a screenshot description and paste it in.
What if I do not have a way to capture heap snapshots?
--inspect
Why does the agent keep suggesting I add more garbage collection calls?
Manual GC calls are a common agent default when it has no evidence, because they "might help" without requiring a diagnosis. Explicitly rule this out in your prompt: "do not suggest manual garbage collection, find the retained reference instead."
Is this approach different for a memory leak in a long-running AI agent process itself?
Not fundamentally. Long-running agent loops often leak through accumulating conversation history or tool-call logs kept in memory across turns. The same diff-first approach applies: snapshot before and after N loop iterations, then ask the agent to trace what is retaining the growing array or map.
How did this land?
About the author

Developer Advocate
Steve builds something with Swarmz every week and writes up what worked, what broke, and what he'd do differently. Tutorials and hands-on guides are his lane.


