How to Fix Node.js Memory Leak Detection
In this tutorial, you'll learn about How to Fix Node.js Memory Leak Detection. We cover key concepts, practical examples, and best practices.
The Problem
A Node.js process uses increasing memory over time and eventually crashes with FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - <a href="/programming-languages/javascript/">JavaScript</a> heap out of memory, caused by objects that are no longer needed but remain referenced.
Quick Fix
Step 1: Monitor memory usage
Track memory growth over time:
setInterval(() => {
const usage = process.memoryUsage();
console.log({
rss: `${(usage.rss / 1024 / 1024).toFixed(1)} MB`,
heapTotal: `${(usage.heapTotal / 1024 / 1024).toFixed(1)} MB`,
heapUsed: `${(usage.heapUsed / 1024 / 1024).toFixed(1)} MB`
});
}, 5000);
Step 2: Clean up event listeners
Accumulated event listeners prevent garbage collection:
function processItems(items) {
items.forEach(item => {
eventEmitter.on('data', (data) => {
item.process(data);
});
});
}
Each call adds listeners that are never removed. Fix:
function processItems(items) {
const handler = (data) => {
items.forEach(item => item.process(data));
};
eventEmitter.on('data', handler);
return () => eventEmitter.removeListener('data', handler);
}
Step 3: Clear timers and intervals
Uncleared intervals keep references alive:
let counter = 0;
setInterval(() => {
counter++;
doWork();
}, 1000);
If the interval is no longer needed, store and clear the reference:
const intervalId = setInterval(() => {
if (!shouldRun) {
clearInterval(intervalId);
return;
}
doWork();
}, 1000);
Step 4: Avoid global caches without limits
Unbounded caches grow indefinitely:
const cache = {};
function getData(key) {
if (cache[key]) return cache[key];
cache[key] = fetchExpensiveData(key);
return cache[key];
}
Add a size limit:
class LRUCache {
constructor(maxSize = 100) {
this.maxSize = maxSize;
this.cache = new Map();
}
get(key) {
if (!this.cache.has(key)) return undefined;
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
set(key, value) {
if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, value);
}
}
Step 5: Take and compare heap snapshots
node --inspect app.js
Open chrome://inspect in Chrome, take a heap snapshot, perform operations, take another snapshot, and compare to find retained objects.
Prevention
- Always clean up event listeners, timers, and subscriptions.
- Use WeakMap and WeakSet for caches that should not prevent GC.
- Limit cache sizes with LRU or TTL expiration.
- Monitor memory in production with tools like clinic.js or heapdump.
- Use
--max-old-space-sizeto set a heap limit and crash fast instead of swapping.
Common Mistakes with memory leak
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world NODE code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro