How do you find and fix memory leaks in a web app?
AdvancedPerformance interview questionBy UIRound, updated 17 November 2026
Short answer
A memory leak in a web app is memory that stays reachable after it is no longer needed, usually through a forgotten listener, timer, subscription, cache or detached DOM node. To find one, repeat a suspect action several times, take heap snapshots in Chrome DevTools before and after, and compare them. Objects whose count keeps growing are the leak; their retainer path shows what holds them. Then remove that reference.
What a leak looks like
The garbage collector frees anything not reachable from a root such as window, the current stack or an active closure (see how garbage collection works). It cannot free something your code still points to, even by accident. In a single-page app the page never reloads, so a leak of a few hundred kilobytes per route change becomes hundreds of megabytes after an hour. Symptoms are a tab that gets slower over time, longer garbage collection pauses, and, on phones, the tab being killed and reloaded.
Common causes
| Cause | Why it leaks | Fix |
|---|---|---|
Event listeners on window, document or a long-lived element |
The target holds the handler, the handler closes over component state | Remove it on teardown, or pass an AbortSignal |
setInterval or a recurring setTimeout |
The timer keeps its callback alive until cleared | clearInterval on teardown |
| Detached DOM nodes | A removed element is still referenced from a variable, array or map, so it and its whole subtree stay alive | Drop the reference, or key data by the node in a WeakMap |
| Closures | A long-lived function captures a large object it no longer needs | Capture only what you need; set big locals to null when done |
| Unbounded caches and registries | A Map or array that only grows |
Cap it (LRU), expire entries, or use a WeakMap |
| Subscriptions | Store, WebSocket, observer or event bus subscriptions that outlive the component | Unsubscribe in cleanup |
| Object URLs | URL.createObjectURL keeps the blob until revoked |
URL.revokeObjectURL when done |
In React, almost all of these show up as an effect without a cleanup function:
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
window.addEventListener("resize", onResize, { signal });
const id = setInterval(poll, 5000);
const unsubscribe = store.subscribe(onChange);
fetch(`/api/items/${itemId}`, { signal })
.then((res) => res.json())
.then(setItem)
.catch((err) => {
if (err.name !== "AbortError") setError(err);
});
return () => {
controller.abort(); // removes the listener and cancels the fetch
clearInterval(id);
unsubscribe();
};
}, [itemId]);One AbortController can remove many listeners at once; see the addEventListener options. React's Strict Mode mounts, unmounts and remounts components in development precisely so a missing cleanup shows up early; the Strict Mode effects guide explains it.
Finding a leak in Chrome DevTools
1. Confirm it is a leak
Open the Performance monitor (Command menu, "Show Performance monitor") and watch JS heap size, DOM nodes and JS event listeners while you repeat an action, such as opening and closing a modal ten times. Healthy memory rises and falls back. A leak climbs in steps and never returns to its starting level, even after you click the "Collect garbage" button in the Memory or Performance panel.
2. Compare heap snapshots
Use the three-snapshot method in the Memory panel:
- Load the page, do the action once to warm up caches, take snapshot 1.
- Repeat the action several times (say five), take snapshot 2.
- Repeat it five more times, take snapshot 3.
Taking a snapshot runs a garbage collection first, so what remains is truly reachable. Select snapshot 3, choose the Comparison view against snapshot 2, and sort by "# Delta". A constructor whose count grows by five on every round (five modals' worth of HTMLDivElement, closures or your own ModalController) is your leak. Type "Detached" in the class filter to list DOM nodes that are no longer in the document but still in memory.
3. Follow the retainers
Click one leaked object. The Retainers pane shows the chain of references from a root to it, for example Window → listeners → onResize closure → context → ModalController. The first link in that chain that belongs to your code and should have been cleared is the bug. Ignore entries in grey or labelled as internal until you have checked your own objects.
4. Use allocation tools for harder cases
Allocation instrumentation on timeline records allocations over time; bars that stay blue after garbage collection are objects still alive, and you can click a bar to see what was allocated then. Allocation sampling is cheaper and groups allocations by function, which helps find which code creates the growing objects. In the console, queryObjects(ModalController) lists live instances and getEventListeners(window) shows what is attached.
WeakMap, WeakRef and when to use them
A WeakMap holds its keys weakly: data keyed by a DOM node disappears when the node is collected, so a metadata store cannot leak nodes. WeakRef lets a cache hold a value without keeping it alive, and FinalizationRegistry can clean up the cache entry after collection. Collection timing is not guaranteed, and finalisers may never run, so treat these as tools for caches, not for required cleanup. The real fix for most leaks is still an explicit teardown.
Practise it
Work through a full investigation in Find and fix an SPA memory leak with heap snapshots, then fix typical causes in Fix a DOM node registry that leaks callback refs, Implement a memory-efficient event bus with lifecycle and Create and revoke upload preview URLs with useObjectURL. Build a weak-value cache with WeakRef covers the weak references.
Common follow-up questions
Why does memory not go down right after I fix the leak?
The collector runs when it decides to, not when an object becomes unreachable. Click "Collect garbage" or take a snapshot, which forces a collection, before you judge the result.
Can a closure leak memory on its own?
Only if the closure itself stays reachable, for example as a listener or in a long-lived array. A closure that is called and dropped is collected with everything it captured.
How do you detect leaks in production?
Field data helps: in cross-origin-isolated pages, Chromium's performance.measureUserAgentSpecificMemory() reports memory use you can send to analytics and watch per release. Rising crash or reload rates on phones are another sign. Reproduce locally with snapshots to find the cause.
Are memory leaks possible on the server side of a Next.js app?
Yes. A module-level cache or array in a long-running Node process grows across requests. Use bounded caches, and in Node take snapshots with --inspect or v8.writeHeapSnapshot().
Mistakes to avoid
Judging by one snapshot instead of comparing several after repeated actions
Forgetting cleanup in effects, or returning cleanup that does not match what was set up (a new function reference passed to
removeEventListener)Keeping removed DOM nodes in arrays, maps or component state
Caching without a size limit or expiry
Relying on
FinalizationRegistrycallbacks for required cleanupProfiling with browser extensions running; use a guest profile or an incognito window, where most extensions are off, so their objects do not pollute the snapshot
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Find and fix an SPA memory leak with heap snapshotsHard45 min
- Fix a DOM node registry that leaks: callback refs with cleanup functionsHard40 min
- Implement a memory-efficient event bus with lifecycle cleanup and leak detectionHard60 min
- Create and revoke upload preview URLs with
useObjectUrlMedium30 min - Build a weak-value cache with
WeakRefandFinalizationRegistry, and test it with a fake garbage collectorMedium35 min