Testing, Performance & Deployment
Node.js Memory Leaks and Debugging
A Node memory leak is a reference that is never released — a growing cache, listeners added but never removed, or closures holding large objects. Heap snapshots taken over time show what is accumulating.
What is Memory Leaks and Debugging in Node.js?
A Node memory leak is a reference that is never released — a growing cache, listeners added but never removed, or closures holding large objects. Heap snapshots taken over time show what is accumulating.
Memory Leaks and Debugging example
// 1. watch the trend
setInterval(() => {
const { heapUsed, rss } = process.memoryUsage();
logger.info({ heapMB: Math.round(heapUsed / 1e6), rssMB: Math.round(rss / 1e6) });
}, 60_000);
// 2. take heap snapshots and compare in Chrome DevTools
import { writeHeapSnapshot } from 'node:v8';
process.on('SIGUSR2', () => writeHeapSnapshot());
// 3. bound anything cache-like
import { LRUCache } from 'lru-cache';
const cache = new LRUCache({ max: 5000, ttl: 300_000 });Key points to remember
- Compare two heap snapshots taken minutes apart and sort by retained size.
- Rising RSS with flat heap usually means native or buffer allocations.
- A restart hides a leak; it does not fix it.
Common leak sources
| Source | Fix |
|---|---|
| a plain object used as an unbounded cache | use an LRU cache with max and ttl |
| listeners added per request | remove them, or register once at startup |
| uncleared setInterval | clearInterval on shutdown |
| closures capturing large buffers | null the reference once done |
| a growing global array of logs or metrics | cap the length or flush periodically |
Node.js Memory Leaks and Debugging— Interview Questions & FAQs
How do I find a memory leak in a Node.js app?+
Log heap usage over time to confirm a trend, then take two heap snapshots minutes apart and diff them in Chrome DevTools. The objects that grew between snapshots point straight at the retaining code.
