How do I determine the correct "max-old-space-size" for node.js?

Borjante picture Borjante · Jan 22, 2018 · Viewed 72.9k times · Source

I'm having some trouble to understand how Node.js acts based on the parameter max-old-space-size.

In my case, for example, I'm running two t2.small AWS instances (2GB of RAM).

Not sure why, but I did set max-old-space-size=4096 (4GB). What does node do in this case? Could this configuration lead to a possible memory allocation failure?

How do I determine the correct value of max-old-space-size based on the server resources?

My application is constantly growing the memory usage and I'm trying to understand everything about node internals.

Answer

jmrk picture jmrk · Jan 23, 2018

"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.