Skip to main content

Node.js JavaScript heap out of memory — fix guide

TL;DR

How to diagnose and fix JavaScript heap out of memory errors in production Node.js applications.

Key facts

Topic
Production error triage
Stack
Node.js / Linux

TL;DR

The FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory crash means your Node.js process exceeded the V8 engine's default heap limit (approximately 1.7 GB on 64-bit systems). This is one of the most common Node.js production failures.

Common causes

  • Processing large JSON payloads or datasets entirely in memory
  • Unbounded in-process caching without eviction policies
  • Streaming data being buffered instead of piped correctly
  • Memory leaks accumulating over long-lived processes

Immediate fix

Increase the V8 heap limit with the --max-old-space-size flag:

node --max-old-space-size=4096 app.js

With PM2, set it in your ecosystem file:

module.exports = {
  apps: [{
    name: 'app',
    script: 'app.js',
    node_args: '--max-old-space-size=4096',
    max_memory_restart: '3500M',
  }],
};

Diagnosis workflow

  1. Review PM2 or systemd logs around the crash timestamp for memory figures
  2. Take heap snapshots with --inspect and Chrome DevTools or the heapdump package
  3. Compare two snapshots taken 10 minutes apart to spot retained object growth
  4. Use clinic doctor from the Clinic.js suite for a visual memory profile

Long-term fix

  • Stream large files with createReadStream and pipe rather than buffering into memory
  • Paginate all database queries — never load an entire table into an array
  • Configure max_memory_restart in PM2 so the process recycles before the OOM killer fires
  • Add an LRU eviction strategy to any in-process caches

Where Reflex helps

Reflex monitors Node.js process RSS and V8 heap usage continuously. When memory crosses a configurable threshold, Reflex executes a graceful restart playbook — draining active connections, restarting via PM2, and verifying the new process is healthy — before the kernel OOM killer intervenes. See How it works.