[Node.js] JavaScript heap out of memory can be resolved with --max-old-space-size

Tadashi Shigeoka ·  Tue, December 4, 2018

When JavaScript heap out of memory error occurs in Node.js, besides fixing the root cause, it can also be resolved with the —max-old-space-size option.

Nodejs | ノード・ジェイエス

Heap out of memory error message

Below is the JavaScript heap out of memory error message:

<--- Last few GCs --->

  541658 ms: Mark-sweep 1061.2 (1437.1) -> 1061.2 (1437.1) MB, 732.4 / 0.0 ms [allocation failure] [GC in old space requested].
  542389 ms: Mark-sweep 1061.2 (1437.1) -> 1061.2 (1437.1) MB, 730.3 / 0.0 ms [allocation failure] [GC in old space requested].
  543177 ms: Mark-sweep 1061.2 (1437.1) -> 1075.1 (1421.1) MB, 788.0 / 0.0 ms [last resort gc].
  543967 ms: Mark-sweep 1075.1 (1421.1) -> 1089.0 (1421.1) MB, 789.4 / 0.0 ms [last resort gc].


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x378b61e3fa99 
    1: /* anonymous */ [/home/nodejs/myapp/node_modules/mongoose/lib/document.js:1361] [pc=0x2ca819399afa] (this=0xa607c53d1a9 ,key=0x35b4d29cb931 )
    2: arguments adaptor frame: 3->1
    3: InnerArrayForEach(aka InnerArrayForEach) [native array.js:~935] [pc=0x2ca815571dd8] (this=0x378b61e04241 ,bq=0xaadfd215041 

How to fix heap out of memory error

When running test cases with grunt using the following command, a JavaScript heap out of memory error occurred on CircleCI:

$(npm bin)/grunt test:container1

As a temporary solution, since —max-old-space-size defaults to 512 MB, I increased it to 2048 MB to prevent the JavaScript heap out of memory error:

node --max-old-space-size=2048 $(npm bin)/grunt test:container1

Ideally, I should find and fix the root cause of the JavaScript heap out of memory error, but since this was a test running in CI, I settled for this solution.

That’s all from the Gemba where I resolved Node.js JavaScript heap out of memory error with —max-old-space-size.