FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
Node.js · updated 2026-11-05
Printed by V8 just before the process aborts, so no JavaScript handler can catch it. Typical during next build, webpack or tsc on large codebases, and in long-running servers whose memory climbs until it reaches the heap ceiling.
<--- Last few GCs ---> [18324:0x150008000] 182340 ms: Mark-Compact 4043.1 (4130.4) -> 4029.7 (4132.9) MB, 1823.40 / 0.00 ms (average mu = 0.112, current mu = 0.041) allocation failure; scavenge might not succeed <--- JS stacktrace ---> FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory ----- Native stack trace ----- 1: 0x100c1b5c8 node::OOMErrorHandler(char const*, v8::OOMDetails const&) [/usr/local/bin/node] 2: 0x100e0a1f4 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, v8::OOMDetails const&) [/usr/local/bin/node] 3: 0x100fd9a20 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/usr/local/bin/node]
Quick fix
Give V8 more old-generation heap with --max-old-space-size (in megabytes), for example NODE_OPTIONS=--max-old-space-size=4096, keeping it below the machine or container memory limit. That unblocks builds. For a server that slowly climbs to the limit, more heap only delays the crash: take heap snapshots and fix the leak.
- Decide whether the crash is in a build step or a running server.
- For builds, set NODE_OPTIONS=--max-old-space-size=4096 (or higher) in that environment.
- Keep the value under the container memory limit, leaving room for native memory.
- For servers, log process.memoryUsage().heapUsed over time to confirm steady growth.
- Start with --heapsnapshot-near-heap-limit=2 and compare snapshots in Chrome DevTools.
- Fix whatever retains the growing objects: caches, listeners, closures, module-level arrays.
# Build step that needs more heap
NODE_OPTIONS=--max-old-space-size=4096 npm run build
# Server: write up to 2 heap snapshots as memory nears the limit
node --max-old-space-size=2048 --heapsnapshot-near-heap-limit=2 server.jsPaste this into Claude Code, Cursor or Codex in the project that throws it. The agent reads this guide in plain text and applies the fix that matches your stack.
Read https://runheed.com/errors/heap-out-of-memory.md and fix this error in this project.Why it happens
Memory leak in a long-running process
Module-level Maps or arrays used as caches with no eviction, event listeners added per request and never removed, or closures that keep whole request objects alive. Heap use rises with traffic until garbage collection can no longer free enough.
Loading a whole dataset into memory
JSON.parse on a very large file, fs.readFileSync of a big export, or an ORM query that returns every row at once. Parsed JavaScript objects take far more memory than the raw bytes they came from.
Large builds on small machines
TypeScript type checking, webpack and Next.js builds on big monorepos can need more heap than the default allows. The default depends on the Node version and system memory, so a build that passes on a 32 GB laptop can fail on a 4 GB CI runner.
Unbounded concurrency
Promise.all over tens of thousands of items starts every request at once and holds every pending response in memory until all of them finish. Batching or a concurrency limit keeps the working set small.
Other fixes
- Stream large files with fs.createReadStream and a streaming JSON or CSV parser instead of reading them whole.
- Paginate or use a cursor for big database queries rather than loading every row.
- Give in-process caches a size cap and TTL (an LRU) so they stop growing.
- If the process dies with exit code 137 and no FATAL ERROR line, the container limit killed it first: raise the container memory or lower the heap flag.
Same error, other wording
- FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
- FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
- FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory
Let your coding agent catch the next one
This crash aborts the process before any JavaScript can run, so Runheed doesn't record it. What it does record is the exceptions your running server code throws (route handlers, server rendering, API errors and background jobs) with the stack trace and the breadcrumbs before them, and serves those errors to Claude Code, Cursor or any MCP client.
Setup for Node.js and Express or Vercel Functions, then have your agent fix and resolve it.
Related errors
- RangeError: Maximum call stack size exceeded
- [UnhandledPromiseRejection: This error originated either by throwing inside of an async...
- An error occurred in the Server Components render. The specific message is omitted in...
More in Memory, async and the process
- RecursionError: maximum recursion depth exceededPython
- RuntimeError: Event loop is closedPython
- RuntimeWarning: coroutine 'fetch_user' was never awaitedPython
- Error: listen EADDRINUSE: address already in use :::3000Node.js
- OSError: [Errno 98] Address already in usePython
- Error: error:0308010C:digital envelope routines::unsupportedNode.js
- MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error...Node.js
- Error: ENOENT: no such file or directory, open '/app/config.json'Node.js
- Error: EACCES: permission denied, open '/app/data/cache.json'Node.js
- Error: EMFILE: too many open files, open '/app/uploads/0412.jpg'Node.js
- PermissionError: [Errno 13] Permission denied: '/app/data/report.csv'Python
- CredentialsProviderError: Could not load credentials from any providersNode.js
- botocore.exceptions.NoCredentialsError: Unable to locate credentialsPython
- django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.Python
Other error topics
- httpx.ReadTimeout: The read operation timed outNetwork and HTTP
- TokenExpiredError: jwt expiredNetwork and HTTP
- Error: getaddrinfo ENOTFOUND api.example.comNetwork and HTTP
- error: permission denied for table profilesDatabases
- redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection...Databases
- psycopg.errors.UniqueViolation: duplicate key value violates unique constraint...Databases
- Error: Cannot find module 'x'Imports and modules
- ImportError: cannot import name 'x' from partially initialized module 'y' (most likely...Imports and modules
- Error: Could not load the "sharp" module using the linux-x64 runtimeImports and modules
- Error: Event handlers cannot be passed to Client Component props.React and Next.js rendering
- TypeError: Failed to parse URL from /api/ordersReact and Next.js rendering
- Failed to find Server Action "7f3a9c2e5d1b4a6f8c0e2d7b9a1c3e5f7d9b0a2c4e". This request...React and Next.js rendering
- panic: runtime error: invalid memory address or nil pointer dereferenceUndefined, None and type errors
- ReferenceError: x is not definedUndefined, None and type errors
- ValueError: invalid literal for int() with base 10: ''Undefined, None and type errors
- TypeError: Converting circular structure to JSONJSON, parsing and validation
- json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)JSON, parsing and validation
- UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byteJSON, parsing and validation
- McpError: MCP error -32001: Request timed outMCP servers and clients
- Bad Request: No valid session ID providedMCP servers and clients
- Error executing tool get_orderMCP servers and clients
Free tools: Source map stack trace decoder · Uptime and SLA downtime calculator · Error budget calculator · Stack trace formatter · JSON log viewer · HTTP status code reference.
References: Node.js CLI options (--max-old-space-size, --heapsnapshot-near-heap-limit), Node.js v8 module (heap snapshots and statistics)
Spotted a mistake? Email hello@greatwork.company. About Runheed.