Finding and Fixing Memory Leaks in Node.js
A memory leak shows as a slow, steady climb in memory until the process crashes or gets OOM-killed — often days after a deployment.
Common Causes
- Unbounded caches — objects added to a Map and never removed
- Event listeners never removed (
emitter.onin a request handler) - Closures holding large objects longer than intended
- Global arrays collecting data
- Timers (
setInterval) never cleared - Unclosed resources (streams, sockets)
Step 1: Confirm It's a Leak
Monitor heap usage over time:
setInterval(() => {
const { heapUsed } = process.memoryUsage();
console.log('heapUsed MB', Math.round(heapUsed / 1024 / 1024));
}, 30000);
A sawtooth that returns to a baseline is normal garbage collection. A rising baseline is a leak. APM tools show this too.
Step 2: Take Heap Snapshots
node --inspect server.js
Open chrome://inspect, connect, go to Memory, and take a heap snapshot. Generate load, take another, and compare.
You can also write snapshots programmatically:
import { writeHeapSnapshot } from 'node:v8';
writeHeapSnapshot();
Step 3: Compare
In the comparison view, look for object types whose count keeps growing. Follow the retainers path to see what's holding them.
Fix Patterns
- Use an LRU cache with a max size instead of a plain Map
- Remove listeners (
emitter.off) or useonce - Clear timers on shutdown or when no longer needed
- Use
WeakMapfor metadata keyed by objects
Memory leaks are found with snapshots, not guesses. Measure, compare, follow the retainers.