How to Quickly Increase the Memory Limit in Node.js

How to Quickly Increase the Memory Limit in Node.js

Fix process out of memory errors in Node
Ferenc Almasi β€’ Last updated 2021 November 11 β€’ Read time 2 min read
You can use the --max-old-space-size CLI flag in your terminal when you start a node process in order to increase the memory limit.
  • twitter
  • facebook
JavaScript

Running Node.js applications come with a default memory limit. This means that memory-intensive applications can run out of memory by allocating more than the available resource. This results in an error message similar to the one below:

FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory

How to Increase the Memory Limit

Luckily, the fix is fairly simple. Use the --max-old-space-size flag when running a Node.js application to increase the available memory heap.

node --max-old-space-size=1024 app.js # Increase limit to 1GB
node --max-old-space-size=2048 app.js # Increase limit to 2GB
node --max-old-space-size=3072 app.js # Increase limit to 3GB
node --max-old-space-size=4096 app.js # Increase limit to 4GB
node --max-old-space-size=5120 app.js # Increase limit to 5GB

Note that the flag needs to come before calling the file with the node command.

Of course, keep in mind that you won't be able to increase the memory limit above the physical memory of the machine you are running the Node.js application on. Nonetheless, using the --max-old-space-size flag is a quick way to fix memory errors in Node.


How to Test Out the Memory Limit

To quickly reach the memory limit and reproduce the error, we can use a while loop without an exit condition, like the one below:

Copied to clipboard! Playground
const array = [];

while (true) {
    for (let i = 0; i < 100000; i++) {
        array.push(i);
    }

    console.log(process.memoryUsage());
}

In this code example, we just keep pushing elements to an array that allocates memory, but we never free up that memory, which results in an out-of-memory error. During the execution of your Node.js application, you can use the process.memoryUsage method in order to get a clear picture of how much memory is used by your Node.js app.

Copied to clipboard! Playground
{
  rss: 19030016,     
  heapTotal: 4468736,
  heapUsed: 2579432, 
  external: 855863,  
  arrayBuffers: 9898
}
The output of the process.memoryUsage call
  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.