debugjavascriptMajor
V8 heap out of memory in Node.js
Viewed 0 times
NODE_OPTIONS env var for heap size: Node 8+
heap out of memorymax-old-space-sizememory leakV8 heapgarbage collectionnode memory
nodejs
Error Messages
Problem
Node.js crashes with FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory. Default heap limit is ~1.7GB for 64-bit systems.
Solution
Increase heap size or fix the memory issue:
# Increase heap limit
node --max-old-space-size=4096 app.js # 4GB
# In package.json
"scripts": {
"start": "node --max-old-space-size=4096 app.js"
}
# Environment variable (Node 20+)
NODE_OPTIONS='--max-old-space-size=4096' node app.js
# Find the leak
node --inspect app.js
# Open chrome://inspect, take heap snapshots, compare
# Common causes:
# 1. Unbounded arrays/caches growing forever
# 2. Event listeners not cleaned up
# 3. Closures holding references to large objects
# 4. Reading entire large files into memory (use streams instead)
# Increase heap limit
node --max-old-space-size=4096 app.js # 4GB
# In package.json
"scripts": {
"start": "node --max-old-space-size=4096 app.js"
}
# Environment variable (Node 20+)
NODE_OPTIONS='--max-old-space-size=4096' node app.js
# Find the leak
node --inspect app.js
# Open chrome://inspect, take heap snapshots, compare
# Common causes:
# 1. Unbounded arrays/caches growing forever
# 2. Event listeners not cleaned up
# 3. Closures holding references to large objects
# 4. Reading entire large files into memory (use streams instead)
Why
V8 has a default heap limit to prevent runaway processes from consuming all system memory. The limit is typically 1.4-1.7GB for 64-bit systems. For memory-intensive tasks (large datasets, image processing), you need to increase it.
Gotchas
- --max-old-space-size is in MB not GB
- Setting it too high can cause the OS to swap/OOM kill
- Use streams for large file processing instead of readFileSync
- Global variables and module-level caches are never garbage collected
Code Snippets
Increase Node.js heap and debug memory
# Run with increased heap
node --max-old-space-size=4096 app.js
# Debug memory
node --inspect --expose-gc app.js
# Then: chrome://inspect → Take Heap SnapshotContext
When Node.js process runs out of memory during large data processing or has a memory leak
Revisions (0)
No revisions yet.