🤖 The AI Prompt That Spots a Memory Leak in a Long-Running Loop
A memory leak in code that only runs once is a rounding error, but the same pattern inside a worker loop or background service that’s meant to run for days compounds into an eventual crash, and the patterns that cause it, unbounded collection growth, event handlers that are never unsubscribed, closures capturing large objects past a single iteration, are specific enough that a model can be pointed at them directly instead of asked to find a leak in general.
🔎 The Prompt
Review this long-running loop or background service for memory growth that would only show up after hours or days of uptime, not in a short test run. Specifically check for: 1. Any collection (List, Dictionary, cache) that items get added to but nothing removes from 2. Event handlers or callbacks subscribed inside the loop body that are never unsubscribed 3. Closures capturing large objects that outlive a single iteration 4. Any static or singleton-scoped field that accumulates per-iteration data For each one found, explain which iteration count or runtime duration would make it observable, and suggest the minimal fix that doesn't change the loop's external behavior.
✅ What Makes This Prompt Actually Work
- Ask specifically for the growth rate per iteration, not just whether a leak exists, since a one-byte-per-iteration leak and a one-megabyte-per-iteration leak call for very different urgency even though both are technically leaks.
- Have it flag any fix that would change observable behavior, like now actually disposing a resource callers were relying on staying open, so the fix doesn’t introduce a different regression.
- Pair the review with an actual memory profiler snapshot taken after a few thousand synthetic iterations, since a static review can flag a real pattern the specific runtime’s GC tuning already mitigates in practice.
🚨 Why This Is Dangerous Without It
- A service that passes every short-lived test and load test cleanly can still be leaking slowly enough that it only runs out of memory after the exact multi-day uptime a staging environment never gets tested at, surfacing for the first time in production.
A memory leak in a loop that runs once is a rounding error — in a loop that runs forever, it’s just a countdown to the crash.




