Full answer
V8 frees an object when nothing reachable refers to it. A leak is an object you forgot that you still refer to.
Typical causes:
- Unbounded caches: a Map or plain object keyed by user, URL or request id that only grows. Fix with a size limit (LRU), a time limit (TTL), or a WeakMap if keys are objects.
- Global arrays used as logs or queues that are never trimmed.
- Event listeners added per request and never removed (see MaxListenersExceededWarning).
- Timers: setInterval callbacks that are never cleared keep their closure alive.
- Closures that capture a large variable although they only need a small part of it.
- Promises that never settle and hold their callbacks.
- Native memory: Buffers, streams not destroyed, unclosed sockets or file handles (these show up as rss and external, not as heapUsed).
How to find them:
- Watch process.memoryUsage(): a leak shows as a steady staircase in heapUsed after garbage collection, and rss rising. A sawtooth that returns to the same low level is healthy.
- Take heap snapshots with node --inspect and Chrome DevTools, or v8.writeHeapSnapshot(). Take one, run load, take another, and compare. Look at the objects with growing counts and the retaining path (what holds them).
- Use allocation sampling and the --heapsnapshot-signal option on a live process.
- Load test a staging copy with a fixed request mix, and see whether memory settles.
A high memory number alone is not a leak. Node may keep memory it can reuse. Check the trend after forced GC.
javascript
const v8 = require('node:v8');
const vm = require('node:vm');
// Allow forced garbage collection without starting node with --expose-gc.
v8.setFlagsFromString('--expose-gc');
const gc = vm.runInNewContext('gc');
const heapMB = () => {
gc();
return process.memoryUsage().heapUsed / 1024 / 1024;
};
// 1. Unbounded cache: every request adds an entry and nothing removes it.
const leakyCache = new Map();
function handleLeaky(requestId) {
leakyCache.set(requestId, new Array(50_000).fill(requestId)); // about 0.4 MB each
}
// 2. Bounded cache: keeps only the 5 newest entries.
const boundedCache = new Map();
function handleBounded(requestId) {
boundedCache.set(requestId, new Array(50_000).fill(requestId));
if (boundedCache.size > 5) boundedCache.delete(boundedCache.keys().next().value);
}
const start = heapMB();
for (let i = 0; i < 200; i++) handleLeaky(i);
const afterLeaky = heapMB();
console.log('leaky cache entries:', leakyCache.size, '| heap grew by more than 40 MB:', afterLeaky - start > 40);
leakyCache.clear();
for (let i = 0; i < 200; i++) handleBounded(i);
const afterBounded = heapMB();
console.log('bounded cache entries:', boundedCache.size, '| heap grew by less than 10 MB:', afterBounded - start < 10);The snippet forces garbage collection before each measurement, so the comparison does not depend on when the collector happens to run. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): leaky cache entries: 200 | heap grew by more than 40 MB: true bounded cache entries: 5 | heap grew by less than 10 MB: true
Key points
- A leak is an unwanted reachable reference.
- Typical sources: unbounded caches, listeners, timers, closures, native handles.
- Look at heapUsed after GC over time, not at one number.
- Compare heap snapshots to see the retaining path.
Common mistakes
- Treating high rss as proof of a leak.
- Using a plain object as a cache with no limit.
- Adding a setInterval in a request handler.
- Taking one heap snapshot and expecting it to show a leak.
Follow-ups
- How does a WeakMap help with caches?
- What does the retaining path in a heap snapshot tell you?
- How do you find a native memory leak that does not show in the heap?
Tips
- Say 'reachable but unused' to define a leak.
- Describe the two-snapshot method, since it shows practical skill.
- Name bounded caches as the first thing to fix.