Node.jsPerformanceError Fix2026 Updated

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

January 202610 min readNode.js · All OS

⚡ 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:

ProblemWhat happensRoot cause
Memory leakHeap grows over hours/days → crashObjects never garbage collected
Heap out of memoryImmediate crash: FATAL ERRORProcessing too-large data or memory leak reached limit
Event loop blockedServer stops responding for secondsSynchronous CPU-intensive code running on main thread

Part 1 — Node.js Memory Leak

1

Monitor Memory Usage

See if memory is actually growing
2 min
server.js — log memory every 30s
// 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 leak

A 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.

2

Find Leaks with Chrome DevTools

Heap snapshots — identify leaking objects
10 min
Step 1 — Start with inspector
node --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

terminal
# 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 Profile
3

Common Memory Leak Patterns and Fixes

The actual code fixes
5 min

1. Growing global arrays / maps

server.js
// ❌ 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 items

2. Event listeners not removed

server.js
// ❌ 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

server.js
// ❌ 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

server.js
// ❌ 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
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)
4

Increase Heap Size

Immediate fix while you find the root cause
1 min
terminal / package.json
# 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.

5

Use Streams for Large Files

Process large data without loading into RAM
5 min

The 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.

server.js
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

6

Find Blocking Code

Identify what is blocking the event loop
5 min

When 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:

terminal
# 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 spikes

Measure event loop lag manually

server.js
// 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 operationsUse async crypto APIs
Heavy computation loopWorker Thread or setImmediate chunks
7

Move CPU Work to Worker Threads

True parallel processing for heavy computation
5 min

Worker Threads run JavaScript in separate OS threads — CPU-intensive work runs in parallel without blocking the main event loop.

worker.js
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 })
server.js
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

8

Use setImmediate for Long Loops

Yield control back to event loop periodically
3 min

If you have a long computation that cannot be moved to a worker thread, break it into chunks using setImmediate to yield control between chunks.

server.js
// ❌ 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

Frequently Asked Questions

How do I find a memory leak in Node.js?+
Start your server with: node --inspect server.js. Open Chrome at chrome://inspect. Take heap snapshots over time in the Memory tab. Look for objects that keep growing. Alternatively, log process.memoryUsage().heapUsed every 30 seconds — if it keeps climbing without coming down, you have a leak.
How do I fix Node.js heap out of memory?+
Short-term: increase heap size with node --max-old-space-size=2048 server.js. Long-term: find and fix the memory leak. Use streams instead of loading entire files into memory. Process large datasets in chunks.
What causes Node.js event loop to be blocked?+
CPU-intensive synchronous operations: large JSON.parse/stringify, image processing, crypto operations, heavy computations, or synchronous file reads of large files. These block the event loop and prevent the server from handling other requests.
How do I know if the event loop is blocked?+
Use the event loop lag metric. Install clinicjs: npm install -g clinic. Run: clinic doctor -- node server.js. It shows event loop delays visually. Or measure manually with: const start = Date.now(); setImmediate(() => console.log('Loop lag:', Date.now() - start, 'ms'))
Common Node.js memory leak causes?+
1) Global variables accumulating data, 2) Event listeners not removed, 3) Closures holding references to large objects, 4) Caches with no eviction policy, 5) Growing arrays/maps never cleared, 6) Database connection pools not closed.
What are Worker Threads in Node.js?+
Worker Threads (built into Node.js 10.5+) let you run JavaScript in separate threads. Use them for CPU-intensive work like image processing, encryption, or data transformation that would otherwise block the event loop. Import with: const { Worker, isMainThread, parentPort } = require('worker_threads')

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