Increase Node application maximum memory usage

0
1793
Increase Node application maximum memory usage
Increase Node application maximum memory usage

If your Node application fails due to Javascript heap out of memory error, it means it doesn’t have enough memory to execute, and you need to increase Node application maximum memory usage to make it work again.

“Old space” is the biggest and most configurable section of V8’s managed (aka garbage-collected) heap (i.e. where the JavaScript objects live), and the –max-old-space-size flag controls its maximum size. As memory consumption approaches the limit, V8 will spend more time on garbage collection in an effort to free unused memory.

If heap memory consumption (i.e. live objects that the GC cannot free) exceeds the limit, V8 will crash your process (for lack of alternative), so you don’t want to set it too low. Of course, if you set it too high, then the additional heap usage that V8 will allow might cause your overall system to run out of memory (and either swap or kill random processes, for lack of alternative).

In summary, on a machine with 2GB of memory I would probably set –max-old-space-size to about 1.5GB to leave some memory for other uses and avoid swapping.StackOverflow

So, on a machine with 2GB of memory, we should start Node app with about 1.5GB memory for old space section, which can by done by assigning --max-old-space-size option:

$ node --max-old-space-size=1536 index.js

The flag can be difficult to ensure that it is being used, especially when node processes are forked. The best way to ensure this setting will be picked up by all node processes within the environment is to apply this setting directly to an environment variable, which can be done using Node. 8 or higher:

NODE_OPTIONS=--max-old-space-size=4096

You can verify the default maximum heap memory usage for a node application by checking it on the shell:

$ node
Welcome to Node.js v18.0.0.
Type ".help" for more information.
> v8.getHeapStatistics().heap_size_limit / 1024 ** 3
4.046875

or, using one-liner:

$ node -e 'console.log(`> heap limit = ${require("v8").getHeapStatistics().heap_size_limit / (1024 ** 3)} Gb`)'
> heap limit = 4.046875 Gb

In summary, whenever your Node application runs out of memory, make sure to increase Node application maximum memory usage.