← Back to Node.js, page 10

nodejs-0181 · Hard senior

A Node.js process is killed with 'JavaScript heap out of memory' or exit code 137. How do you find out why, and what are the fixes?

There are two different kills. 'JavaScript heap out of memory' (SIGABRT) means V8 reached its own heap limit, which --max-old-space-size controls. Exit code 137 in a container means the operating system or the orchestrator killed the process with SIGKILL because the whole process (heap, Buffers, native memory) went over the container limit. Find out which one it is, then look for growth with heap snapshots, and fix leaks or unbounded data before raising limits.

Full answer

Two different failures

  • V8 heap limit: the old space is full and garbage collection cannot free enough. Node prints FATAL ERROR ... JavaScript heap out of memory and aborts (SIGABRT). The limit depends on the version and the machine and can be set with --max-old-space-size=MB (in a container, set it to about 75 percent of the memory limit).
  • Container OOM kill: the kernel kills the process with SIGKILL when the memory of the whole process (heap, Buffers, native addons, thread stacks) exceeds the cgroup limit. Exit code 137 (128 + 9) and 'OOMKilled' in the orchestrator. No JavaScript error appears. Buffers and external memory are outside the V8 heap, so the heap can look healthy while the container dies.

Investigation

  1. Read process.memoryUsage(): heapUsed, external, arrayBuffers and rss. Which one grows?
  2. Is the growth steady (a leak) or a spike (a huge request, reading a whole file, a big query result)? Look at memory against traffic and deploys.
  3. Take heap snapshots at two times (v8.writeHeapSnapshot(), or node --heapsnapshot-near-heap-limit=N to capture one before the crash) and compare them in Chrome DevTools: look for objects that only increase, such as Maps, arrays and closures.
  4. Typical causes: unbounded caches or Maps, listeners added per request, global arrays used as logs, request data captured in closures or timers, reading whole files and uploads into memory, and large JSON.parse.

Fixes

  • Bound caches (LRU with a maximum size and TTL), remove listeners, stream large data, paginate queries, apply backpressure, and limit request body size.
  • Raise --max-old-space-size or the container memory only after the cause is understood.
  • Alert on memory growth, not only on a crash.
javascript
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const runNode = (flags, code, cwd) => spawnSync(process.execPath, [...flags, '-e', code], { encoding: 'utf8', cwd });
const heapLimitMB = (flags) => Number(runNode(flags, "console.log(Math.round(require('v8').getHeapStatistics().heap_size_limit / 1048576))").stdout);

// 1. The V8 limit follows the flag.
const defaultLimit = heapLimitMB([]);
const smallLimit = heapLimitMB(['--max-old-space-size=48']);
console.log('1. limit with --max-old-space-size=48 is lower than the default:', smallLimit < defaultLimit);

// 2. An unbounded array fills the heap and the process aborts.
const leak = "const keep = []; for (;;) keep.push(new Array(10000).fill(Math.random()));";
const crashed = runNode(['--max-old-space-size=48'], leak);
console.log('2. leak crashed with signal :', crashed.signal, '| message mentions heap out of memory:', /heap out of memory/.test(crashed.stderr));

// 3. A bounded buffer, same work, no crash.
const bounded = "const keep = []; for (let i = 0; i < 3000; i++) { keep.push(new Array(10000).fill(i)); if (keep.length > 20) keep.shift(); } console.log('done');";
const fixed = runNode(['--max-old-space-size=48'], bounded);
console.log('3. bounded version          : exit', fixed.status, fixed.stdout.trim());

// 4. Ask Node to write a heap snapshot before it dies.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'oom-'));
runNode(['--max-old-space-size=48', '--heapsnapshot-near-heap-limit=1'], leak, dir);
console.log('4. snapshot file written near the limit:', fs.readdirSync(dir).some((name) => name.endsWith('.heapsnapshot')));
fs.rmSync(dir, { recursive: true, force: true });

Child processes with a 48 MB heap limit are used so that the crash is quick. Never run a leak on a shared server. The heap snapshot step can take a few seconds. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. limit with --max-old-space-size=48 is lower than the default: true 2. leak crashed with signal : SIGABRT | message mentions heap out of memory: true 3. bounded version : exit 0 done 4. snapshot file written near the limit: true

Key points

  • V8 heap out of memory and container OOM kill are different failures.
  • --max-old-space-size sets the V8 limit; keep it below the container limit.
  • Buffers and native memory are outside the V8 heap.
  • Compare heap snapshots over time to find what grows.
  • Bound caches and stream large data before raising limits.

Common mistakes

  • Raising the memory limit and calling the incident closed.
  • Setting --max-old-space-size above the container limit.
  • Looking only at heapUsed while Buffers and native memory grow.
  • Taking a heap snapshot on a busy production instance without isolating it.
  • Not bounding caches and Maps that are keyed by user input.

Follow-ups

  • How do you tell a leak from a traffic spike in the graphs?
  • What is the difference between rss, heapUsed and external?
  • How do you set the heap size inside a Docker image?

Tips

  • Split the two kinds of kill first.
  • Say 'compare two snapshots'.
  • Mention bounding caches.