How to allocate more memory to your app
JavaScript applications can run into memory-related issues as they scale, and understanding how to manage memory effectively is crucial for building robust applications. One of the most important concepts in Node.js memory management is the max-old-space-size
parameter, which directly impacts how your application handles memory allocation.
What is max-old-space-size?
The max-old-space-size
is a Node JavaScript engine parameter that sets the maximum memory limit in Node applications. By default, Node.js applications are limited to approximately 1.4GB of memory on 64-bit systems and 512MB on 32-bit systems.
The "old space" refers to a specific region of V8 JavaScript engine's heap where long-lived objects are stored. When your application exceeds this limit, it will crash with an out-of-memory error, typically showing a message like "JavaScript heap out of memory."
Why Memory Limits Exist
V8 imposes memory limits for several reasons:
- Garbage Collection Performance: Larger heaps mean longer garbage collection pauses
- System Stability: Prevents runaway applications from consuming all available memory
- Historical Constraints: Originally designed for browser environments with limited memory
When to Increase max-old-space-size
Consider increasing the memory limit when:
- Processing large datasets or files
- Running memory-intensive operations like image processing
- Building applications with high concurrency requirements
- Working with in-memory caches or databases
- Experiencing frequent out-of-memory crashes
How to Set max-old-space-size
Command Line
The most straightforward way is to use the --max-old-space-size
flag:
# Set to 4GB
node --max-old-space-size=4096 app.js
# Set to 8GB
node --max-old-space-size=8192 app.js
Environment Variables
You can also set this through the NODE_OPTIONS
environment variable:
export NODE_OPTIONS="--max-old-space-size=4096"
node app.js
Package.json Scripts
For consistent deployment, add it to your package.json:
{
"scripts": {
"start": "node --max-old-space-size=4096 app.js",
"dev": "node --max-old-space-size=2048 app.js"
}
}
In DollarDeploy
In the app environment settings, add the NODE_OPTIONS
variable with max memory size, in kilobytes. Avoid adding whole memory on your server, since you need space for operating system and other services, for example for 4Gb RAM server, set 3.2Gb.
Name | Value |
---|---|
NODE_OPTIONS |
--max-old-space-size=3296 |
Best Practices for Memory Management
Monitor Memory Usage
Use the DollarDeploy monitoring agent to get memory use on your server.
Optimize Memory Usage
- Avoid Memory Leaks: Remove event listeners, clear intervals, and nullify references
- Use Streams: Process large files using streams instead of loading everything into memory, directly sending the stream to the browser.
- Implement Pagination: Break large datasets into smaller chunks
- Reuse objects: Reuse common objects instead of creating new ones repeatedly