How do you debug a memory leak in a Node.js process?
Approach it as measure, capture, compare, fix.
- Confirm it is real. Track
process.memoryUsage().heapUsedover hours. Node's heap grows and then plateaus normally; a leak keeps climbing and does not come back down after garbage collection. Run with--expose-gcand force a collection to be sure. - Capture heap snapshots. Start with
--inspectand take a snapshot in Chrome DevTools, or usev8.writeHeapSnapshot(). Take one early, apply load, take another. - Compare them. The comparison view sorts objects by what was allocated and never freed. Look at retained size and follow the retainer path to whatever is still holding the reference.
The usual culprits:
- A module-level array or Map that only ever grows — caches without eviction are the number one cause.
- Event listeners added per request but never removed, which is why Node warns at eleven listeners.
- Timers that are never cleared.
- Closures capturing a large object and stored somewhere long-lived.
Note: Mention WeakMap and WeakRef as the structural fix when you need to associate data with an object without keeping it alive.





