Node.js Memory Leak, Heap Out of Memory& Event Loop Blocked — Fixed [2026]
Covers: FATAL ERROR Allocation failed · JavaScript heap out of memory · Event loop lag · Worker Threads
⚡ Immediate Fixes
Heap OOM
node --max-old-space-size=2048 server.js
Monitor memory
node --inspect server.js → chrome://inspect
Event loop lag
npx clinic doctor -- node server.js
Understand What Is Happening
These three problems are related but distinct. Each has a different cause and a different fix:
| Problem | What happens | Root cause |
|---|---|---|
| Memory leak | Heap grows over hours/days → crash | Objects never garbage collected |
| Heap out of memory | Immediate crash: FATAL ERROR | Processing too-large data or memory leak reached limit |
| Event loop blocked | Server stops responding for seconds | Synchronous CPU-intensive code running on main thread |
Part 1 — Node.js Memory Leak
Monitor Memory Usage
See if memory is actually growing// Add to your server — watch for steady upward trend
setInterval(() => {
const mem = process.memoryUsage()
console.log({
heapUsed: Math.round(mem.heapUsed / 1024 / 1024) + ' MB',
heapTotal: Math.round(mem.heapTotal / 1024 / 1024) + ' MB',
rss: Math.round(mem.rss / 1024 / 1024) + ' MB',
external: Math.round(mem.external / 1024 / 1024) + ' MB',
})
}, 30000)
// If heapUsed grows from 100MB to 500MB over an hour
// without coming back down → memory leakA healthy server's heap usage fluctuates — it grows during requests and comes back down after garbage collection. A memory leak shows a one-way upward trend over time.
Find Leaks with Chrome DevTools
Heap snapshots — identify leaking objectsnode --inspect server.js
# Open Chrome and go to: chrome://inspect- Open Chrome → chrome://inspect → click 'inspect' under your Node process
- Go to Memory tab → click 'Take snapshot'
- Make several requests to your app
- Take a second snapshot
- Select 'Comparison' view to see what grew
- Look for objects with large Retained Size that keep growing
Or use the --heap-prof flag
# Generate heap profile
node --heap-prof server.js
# Run some requests, then Ctrl+C
# A .heapprofile file is created
# Load it in Chrome DevTools → Memory → Load ProfileCommon Memory Leak Patterns and Fixes
The actual code fixes1. Growing global arrays / maps
// ❌ WRONG — cache grows forever
const cache = {}
app.get('/data/:id', async (req, res) => {
cache[req.params.id] = await fetchData(req.params.id) // never evicted!
res.json(cache[req.params.id])
})
// ✅ CORRECT — use LRU cache with size limit
const LRU = require('lru-cache')
const cache = new LRU({ max: 500 }) // keeps only 500 most recent items2. Event listeners not removed
// ❌ WRONG — new listener added on every request
app.get('/stream', (req, res) => {
emitter.on('data', (data) => {
res.write(data) // new listener each request — never removed
})
})
// ✅ CORRECT — remove listener when connection closes
app.get('/stream', (req, res) => {
const handler = (data) => res.write(data)
emitter.on('data', handler)
req.on('close', () => emitter.off('data', handler)) // cleanup!
})3. Timers not cleared
// ❌ WRONG — interval never cleared
function startPolling() {
setInterval(() => fetchUpdates(), 1000) // grows if called multiple times
}
// ✅ CORRECT — store reference and clear when done
let pollInterval = null
function startPolling() {
if (pollInterval) clearInterval(pollInterval)
pollInterval = setInterval(() => fetchUpdates(), 1000)
}
function stopPolling() {
clearInterval(pollInterval)
pollInterval = null
}4. Closures holding large objects
// ❌ WRONG — closure keeps entire file in memory
function processFile(content) {
const largeBuffer = content // held in closure
return function handler(req, res) {
res.send(largeBuffer) // largeBuffer never GC'd
}
}
// ✅ CORRECT — only keep what you need
function processFile(content) {
const result = extract(content) // process and discard
return function handler(req, res) {
res.send(result) // only keep small result
}
}Part 2 — Heap Out of Memory
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
1: 0xb7c9e0 node::Abort() [node]
2: 0xa93510 node::FatalError(char const*, char const*) [node]
Aborted (core dumped)Increase Heap Size
Immediate fix while you find the root cause# Run with 2GB heap (default is ~1.5GB)
node --max-old-space-size=2048 server.js
# 4GB for very large workloads
node --max-old-space-size=4096 server.js
# In package.json scripts
{
"scripts": {
"start": "node --max-old-space-size=2048 server.js"
}
}
# With PM2
pm2 start server.js --node-args="--max-old-space-size=2048"
# Check current heap limit
node -e "console.log(require('v8').getHeapStatistics().heap_size_limit / 1024 / 1024, 'MB')"Increasing heap size is a temporary fix. The real solution is finding why the heap grows — use Fix 2 and Fix 3. Unlimited heap growth will always eventually crash the server.
Use Streams for Large Files
Process large data without loading into RAMThe most common cause of instant heap OOM is loading an entire large file (CSV, JSON, video) into memory. Use streams to process data piece by piece.
const fs = require('fs')
const path = require('path')
// ❌ WRONG — loads entire 1GB file into memory at once
app.get('/download', (req, res) => {
const content = fs.readFileSync('/data/huge-file.csv') // 1GB in RAM!
res.send(content)
})
// ✅ CORRECT — stream the file, only a chunk in memory at once
app.get('/download', (req, res) => {
const filePath = path.join(__dirname, 'data', 'huge-file.csv')
const stream = fs.createReadStream(filePath)
stream.pipe(res) // streams directly to response — minimal memory
})
// ✅ Stream + transform (e.g. CSV processing)
const { Transform } = require('stream')
const processLine = new Transform({
transform(chunk, encoding, callback) {
const processed = chunk.toString().toUpperCase()
callback(null, processed)
}
})
fs.createReadStream('huge.csv')
.pipe(processLine)
.pipe(res)Streaming a 1GB file uses only ~64KB of RAM at any time. Loading it with readFileSync uses 1GB immediately. Always stream large files.
Part 3 — Event Loop Blocked
Find Blocking Code
Identify what is blocking the event loopWhen the event loop is blocked, all incoming requests queue up and wait. The server appears frozen during heavy operations. Here is how to find the culprit:
# Install clinic.js profiler
npm install -g clinic
# Profile your app
clinic doctor -- node server.js
# Make requests to your app while it runs
# Then Ctrl+C — clinic generates an HTML report
# Look for event loop delay spikesMeasure event loop lag manually
// Add this to your server — watch for values above 10ms
setInterval(() => {
const start = process.hrtime.bigint()
setImmediate(() => {
const lag = Number(process.hrtime.bigint() - start) / 1_000_000
if (lag > 100) {
console.warn(`Event loop blocked for ${lag.toFixed(0)}ms!`)
}
})
}, 1000)Common blocking operations
| Blocking ❌ | Non-blocking ✅ |
|---|---|
| JSON.parse(huge string) | Stream + JSONStream package |
| fs.readFileSync(large file) | fs.promises.readFile() or stream |
| bcrypt.hashSync() | bcrypt.hash() async |
| crypto sync operations | Use async crypto APIs |
| Heavy computation loop | Worker Thread or setImmediate chunks |
Move CPU Work to Worker Threads
True parallel processing for heavy computationWorker Threads run JavaScript in separate OS threads — CPU-intensive work runs in parallel without blocking the main event loop.
const { parentPort, workerData } = require('worker_threads')
// Heavy computation here — runs in its own thread
function heavyComputation(data) {
let result = 0
for (let i = 0; i < data.count; i++) {
result += Math.sqrt(i) * Math.PI
}
return result
}
const result = heavyComputation(workerData)
parentPort.postMessage({ result })const { Worker } = require('worker_threads')
const path = require('path')
function runWorker(data) {
return new Promise((resolve, reject) => {
const worker = new Worker(path.join(__dirname, 'worker.js'), {
workerData: data
})
worker.on('message', resolve)
worker.on('error', reject)
worker.on('exit', code => {
if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`))
})
})
}
// Express route — computation runs in worker, event loop stays free
app.post('/process', async (req, res) => {
try {
const result = await runWorker({ count: 10_000_000 })
res.json(result)
} catch (err) {
res.status(500).json({ error: err.message })
}
})Use a worker pool (via 'piscina' package) in production so you reuse workers instead of creating a new thread per request: npm install piscina
Use setImmediate for Long Loops
Yield control back to event loop periodicallyIf you have a long computation that cannot be moved to a worker thread, break it into chunks using setImmediate to yield control between chunks.
// ❌ WRONG — blocks event loop for entire duration
function processItems(items) {
for (const item of items) {
heavyProcess(item) // 10,000 items × 1ms = 10 seconds blocked!
}
}
// ✅ CORRECT — process in chunks, yielding between each
async function processItemsAsync(items, chunkSize = 100) {
for (let i = 0; i < items.length; i += chunkSize) {
const chunk = items.slice(i, i + chunkSize)
chunk.forEach(item => heavyProcess(item))
// Yield control to event loop — let other requests run
await new Promise(resolve => setImmediate(resolve))
}
}
app.post('/process-all', async (req, res) => {
await processItemsAsync(req.body.items)
res.json({ done: true })
})Prevention Checklist
- Monitor memory with process.memoryUsage() logged every 30 seconds
- Set max_memory_restart in PM2 to auto-restart before OOM crash
- Always stream large files — never readFileSync for files over 1MB
- Use LRU caches with size limits — never unbounded global objects
- Remove event listeners when connections close
- Clear timers and intervals when no longer needed
- Use Worker Threads for CPU-intensive operations
- Profile regularly with clinic.js in staging
- Set --max-old-space-size in production as a safety net
Frequently Asked Questions
How do I find a memory leak in Node.js?+−
How do I fix Node.js heap out of memory?+−
What causes Node.js event loop to be blocked?+−
How do I know if the event loop is blocked?+−
Common Node.js memory leak causes?+−
What are Worker Threads in Node.js?+−
Need Expert Help?
We Optimise Production Node.js Applications
Softplix builds and optimises full-stack Node.js applications. Dealing with memory leaks or performance issues in production? We can profile, diagnose, and fix.
Talk to an Engineer