JavaScript Heap Out of Memory: Find the Limit First

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory means V8’s old space, where long-lived objects are kept, hit its size limit and garbage collection could not free enough to continue, so Node aborted. Raise the limit with --max-old-space-size, but print the limit in force first, because the fix depends on where that number came from.

Everything below was run on Node 24.12.0 on macOS (arm64, 64 GiB of memory) on 29 November 2026, unless a sentence says it comes from the docs or the source. Node 26 is the newest LTS line as of that date. We did not run it.

What does “JavaScript heap out of memory” mean?

V8 sorts its heap by age. New objects start in a small young generation that is collected often, and the survivors are promoted to the old space. The limit that kills a process is the old space’s.

This script keeps every object it creates:

const kept = [];

setInterval(() => {
  for (let i = 0; i < 20_000; i++) {
    kept.push({ id: kept.length, label: `row ${kept.length}` });
  }
  const { heapUsed, rss } = process.memoryUsage();
  console.log(`heapUsed ${Math.round(heapUsed / 2 ** 20)} MiB, rss ${Math.round(rss / 2 ** 20)} MiB`);
}, 50);

Run with node --max-old-space-size=64 leak.mjs, it lasted two seconds. The end of the output, with the two garbage collection lines trimmed:

heapUsed 62 MiB, rss 118 MiB

<--- Last few GCs --->

[70886:0x7a280c000]     1991 ms: Mark-Compact (reduce) 62.4 (66.5) -> 61.9 (64.2) MB, [...]
[70886:0x7a280c000]     2037 ms: Mark-Compact (reduce) 63.4 (64.7) -> 62.8 (65.2) MB, [...]

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
----- Native stack trace -----

Two full collections ran 46 ms apart and each recovered about half a megabyte. The shell reported exit status 134, which is an abort (SIGABRT). The words before “Allocation failed” vary: ours were Reached heap limit, and the example in Node’s CLI reference shows Ineffective mark-compacts near heap limit. Both end in the same five words.

The error does not mean the machine ran out of memory. Ours had 64 GiB and the process was using 118 MiB.

The limit does not count Buffers either. Under the same 64 MiB limit, a script that allocated eight 64 MiB Buffers finished normally and reported heapUsed 3 MiB, arrayBuffers 512 MiB and rss 556 MiB. Buffer contents sit outside the V8 heap, so a process can use far more real memory than this limit and never print this message.

What is the heap limit where the code runs?

Ask V8, in the environment that failed:

import os from 'node:os';
import v8 from 'node:v8';

const mib = (bytes) => Math.round(bytes / 1024 / 1024);

console.log({
  node: process.version,
  heapLimitMiB: mib(v8.getHeapStatistics().heap_size_limit),
  systemMiB: mib(os.totalmem()),
  constrainedMiB: mib(process.constrainedMemory()),
});

With no flags this printed heapLimitMiB: 4288. With --max-old-space-size=1024 it printed 1216, and with 64 it printed 256. On this machine heap_size_limit came out 192 MiB above whatever old space we set, the extra being room for the young generation. That is why the leak died at a heapUsed of 62 MiB while the reported limit was 256. Compare heapUsed with the old space figure, not with heap_size_limit.

The default matters most in a container, and here we are reading code, not reporting a run. Node’s startup code hands V8 the smaller of the system’s memory and the cgroup limit. V8’s sizing function then gives the old space half of that on a 64-bit build, capped at 2 GiB, or 4 GiB when it sees 15 GiB or more. By that reading a 1 GiB container gets an old space near 512 MiB, an eighth of what our Mac got. We did not run Node in a container, so print the number in yours. constrainedMiB is the limit Node detected, and the docs say process.constrainedMemory() returns 0 when there is none.

Where does —max-old-space-size go so it reaches the process?

The value is in MiB, and a flag applies to the process it is given to:

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

Often the process that dies is a build tool you never start with node yourself. Then the setting has to travel in the environment:

NODE_OPTIONS=--max-old-space-size=4096 npm run build

--max-old-space-size is on the list of V8 options that NODE_OPTIONS accepts. We printed the limit from each kind of child. With NODE_OPTIONS, an npm script, a fork() child, a spawn(process.execPath) child and a worker thread all reported the raised limit. With the flag on the command line, the fork() child and the worker inherited it, and the spawned child went back to 4288. When both were set, the command-line flag won.

For a team, a line in the project’s .npmrc saves everyone remembering shell syntax:

node-options=--max-old-space-size=4096

npm’s config reference says node-options is passed to lifecycle scripts through NODE_OPTIONS. On npm 11.6.2 it replaced a NODE_OPTIONS already set in our shell and did not merge with it.

There is also --max-old-space-size-percentage, which the 24.x CLI reference lists with no “added in” version. At 50 it gave us an old space of 32,768 MiB, half the machine. It beat --max-old-space-size when we passed both, as the docs say it does, and it worked from NODE_OPTIONS. Its source takes the percentage of the cgroup limit when one exists, which again we read and did not run.

A worker thread can carry a smaller limit of its own through resourceLimits.maxOldGenerationSizeMb. Our worker with a 64 MiB limit emitted an error with the code ERR_WORKER_OUT_OF_MEMORY and the main thread carried on, which is the isolation our worker threads and child processes comparison relies on.

How high can the limit go?

Lower than the memory you have. The V8 heap is one part of the process, and Buffers, native addons and thread stacks sit beside it: the leak above held 62 MiB of heap in 118 MiB of rss. Node’s CLI reference gives a worked figure: “On a machine with 2 GiB of memory, consider setting this to 1536 (1.5 GiB) to leave some memory for other uses and avoid swapping.”

Set the limit above what a container allows and the failure changes shape. Docker’s resource constraints page says the kernel kills processes in a container that runs out of memory. When we sent SIGKILL to a running script ourselves, the shell reported status 137 and stderr was empty.

So 134 with a garbage collection trace points at V8’s limit. 137 with nothing printed points at something outside Node, and a higher --max-old-space-size pushes a process from the first towards the second. We did not reproduce a container kill.

Is it a leak, or a job that needs more memory?

A build has an end. Its peak grows with the project and then the process exits, so a bundler or type checker that dies partway through a large project usually needs a bigger number. A server is different: if its heapUsed climbs for hours under steady traffic it is leaking, and a higher limit only lengthens the gap between crashes. None of the exit, uncaughtException or signal handlers we registered ran before the abort, so the graceful shutdown a SIGTERM would get never happens.

Two flags help you tell them apart, one cheap and one expensive.

--report-on-fatalerror writes a diagnostic report as the process dies. Ours was a 53 KB JSON file holding the command line and the heap broken down by space, with old_space nearly full. Its JavaScript stack section read “Unavailable”, so on our run it showed which space filled and not which line filled it.

--heapsnapshot-near-heap-limit=2 writes heap snapshots as the limit approaches, and the docs mark it experimental. Budget for it. On the same leak with the same 64 MiB limit, the run wrote snapshots of 183 MB and 769 MB, heapUsed reached 445 MiB before the abort, rss peaked above 2 GiB, and the process took 27 seconds to die. The docs explain that Node adjusts the heap to make room for the snapshot, and warn that the process “may be terminated abruptly by the system”. In a tight container that could turn a readable 134 into a silent 137. Run it where memory is spare, then compare the two files in Chrome DevTools, which Node’s heap snapshot guide walks through.

What should change first?

Nothing, until you have printed the limit and process.constrainedMemory() where the failure happened.

For a build, set node-options in .npmrc to a value comfortably under the memory of the machine or container, and commit it. For a long-running service, do not start by raising the limit. Turn on --report-on-fatalerror, graph heapUsed, and raise the limit only if the heap levels off above the previous limit. A heap that never levels off is a leak, and the snapshot flag belongs on a machine with room to spare. We would also leave the percentage flag out of a container until we had printed what it produces there.

Whoooop builds Node.js back ends and takes on existing Node codebases whose authors have moved on. Our Node.js development page covers both.

Need this built properly?

Get in touch

Hack the planet!