How do you fix "FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory" in Node.js? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you fix "FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory" in Node.js?

message-square
0

To fix FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory in Node.js, first increase the V8 heap ceiling via NODE_OPTIONS="--max-old-space-size=4096" (or --max-old-space-size=<MB>) when a build, test runner, or data job legitimately needs more memory than Node’s default limit, and then fix the root cause—such as unbounded array/Map growth, retaining large buffers/closures, loading entire large files into memory at once instead of streaming, or accidental infinite recursion / object graph retention—so the process does not simply exhaust a larger heap later.


1. Raising the V8 Heap Limit with --max-old-space-size

Pass --max-old-space-size=<megabytes> through NODE_OPTIONS (works across node, npm, npx, pnpm, yarn, and test runners without editing command flags in every script):

# Run a Node process or build script with a 4 GB (4096 MB) old-space heap limit
NODE_OPTIONS="--max-old-space-size=4096" node dist/server.js

# Equivalent inside a Node launcher script with defensive environment validation
function ensureHeapLimit(targetMegabytes = 4096) {
  if (typeof targetMegabytes !== "number" || !Number.isInteger(targetMegabytes) || targetMegabytes < 256) {
    throw new RangeError("Expected targetMegabytes to be an integer >= 256.");
  }

  const currentOptions = process.env.NODE_OPTIONS ?? "";
  if (currentOptions.includes("--max-old-space-size")) {
    return currentOptions;
  }

  const updatedOptions = `${currentOptions} --max-old-space-size=${targetMegabytes}`.trim();
  process.env.NODE_OPTIONS = updatedOptions;
  return updatedOptions;
}

try {
  console.log("Configured NODE_OPTIONS:", ensureHeapLimit(4096));
} catch (error) {
  console.error(`${error.name}: ${error.message}`);
}
  • Containers (Docker / Kubernetes) need memory limits aligned: If a container’s cgroup memory limit is 2 GB and you set --max-old-space-size=4096, the OS OOM killer (SIGKILL, exit code 137) can terminate the container before V8 hits its heap cap.
  • Treat flag increases as a stopgap or sizing adjustment: If memory keeps climbing over time, you have a leak or whole-dataset buffering bottleneck rather than a fixed peak requirement.

2. Streaming Large Datasets Instead of Buffering Everything in Memory

Loading massive JSON files, CSVs, or API responses into a single string or array (fs.readFileSync, JSON.parse(hugeFile), or Array.from() over huge streams) spikes V8 old-space usage—use fs.createReadStream() and readline or chunked processing instead:

// Process a large line-delimited file in bounded chunks instead of reading all lines at once
import fs from "node:fs";
import readline from "node:readline";

async function processLargeFileByLine(filePath, onRecord) {
  if (typeof filePath !== "string" || filePath.trim().length === 0) {
    throw new TypeError("Expected filePath to be a non-empty string.");
  }
  if (typeof onRecord !== "function") {
    throw new TypeError("Expected onRecord to be a function.");
  }

  const fileStream = fs.createReadStream(filePath, { encoding: "utf8" });
  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });

  let processedCount = 0;

  try {
    for await (const line of rl) {
      const trimmed = line.trim();
      if (!trimmed) {
        continue;
      }

      let parsed;
      try {
        parsed = JSON.parse(trimmed);
      } catch (parseError) {
        throw new SyntaxError(`Malformed JSON on line ${processedCount + 1}: ${parseError.message}`);
      }

      await onRecord(parsed, processedCount);
      processedCount += 1;
    }
  } finally {
    rl.close();
    fileStream.destroy();
  }

  return processedCount;
}

// Example usage:
// const count = await processLargeFileByLine("./events.ndjson", async (row) => { /* handle row */ });
  • Avoid await Promise.all(hugeArray.map(...)) without concurrency limits: Firing thousands of concurrent promises at once can buffer huge payloads and exhaust heap or sockets.
  • Process and discard per iteration: Avoid accumulating every processed item in a giant array unless you truly need all items resident in RAM.

3. Diagnosing Heap Leaks and Capturing Heap Snapshots / Logs

When heap exhaustion happens repeatedly or unexpectedly, inspect heap usage (process.memoryUsage()), enable V8 heap logging (--heapsnapshot-signal=SIGUSR2 or v8.writeHeapSnapshot()), and look for unbounded caches, detached listeners/timers, or closures holding large objects:

// Log readable V8 memory metrics and optionally write a heap snapshot on demand
import v8 from "node:v8";
import path from "node:path";

function logMemoryUsage(label = "snapshot") {
  const mem = process.memoryUsage();
  const toMb = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;

  return {
    label,
    rss: toMb(mem.rss),
    heapTotal: toMb(mem.heapTotal),
    heapUsed: toMb(mem.heapUsed),
    external: toMb(mem.external),
    arrayBuffers: toMb(mem.arrayBuffers)
  };
}

function captureHeapSnapshotSafe(outputDir = ".") {
  if (typeof outputDir !== "string" || outputDir.trim().length === 0) {
    throw new TypeError("Expected outputDir to be a non-empty string.");
  }

  try {
    const filename = `Heap-${Date.now()}.heapsnapshot`;
    const fullPath = path.join(outputDir, filename);
    const writtenPath = v8.writeHeapSnapshot(fullPath);
    return writtenPath;
  } catch (error) {
    throw new Error(`Failed to write heap snapshot: ${error.message}`);
  }
}

// Example usage:
console.log(logMemoryUsage("startup"));
// Compare heapUsed across requests/batches; steadily rising baseline after GC indicates retention.
  • Use WeakMap / WeakSet for object-keyed metadata: Normal Map or Set keys keep referenced objects alive indefinitely unless explicitly deleted.
  • Watch arrayBuffers and external memory: Large Buffer or Uint8Array allocations outside JS objects still count toward container memory even when heapUsed looks moderate.