Fatal error invalid table size allocation failed javascript heap out of memory

TypeScript Version: 3.3.3333 3.3.4000 3.4.5 Version 3.5.0-dev.20190515 Search Terms: "invalid table size": this one is new "Allocation Failed" Code I will continue trying to bui...

TypeScript Version:
3.3.3333
3.3.4000
3.4.5
Version 3.5.0-dev.20190515

Search Terms:

  • «invalid table size»: this one is new
  • «Allocation Failed»

Code
I will continue trying to build a reduced repro, but the code right now is a private React-Native project with Redux. We have ~200 source TS files and ~70 basic redux actions, as well as some thunk actions.

We use a lot of type inference to build a discriminated type union of our redux types, similar to this article. Right now, if I add one additional redux type to our application, it will crash with the below Allocation Failed error

Here is a reasonable facsimile of one of our action files:

// utility helper to get inference of the correct action type (TODO replace w/ `as const`)
export function createAction<T extends string, U extends Action<T>>(action: U) {
  return action;
}

function myReduxActionOne() {
  return createAction({ type: 'some_long_string_constant' });
}
function myReduxActionTwo(data: object) {
  return createAction({ 
    type: 'some_long_string_constant',
    data
  });
}

export type MyReduxActions = ReturnType<
  | typeof myReduxActionOne
  | typeof myReduxActionTwo
  // If I add one more `typeof actionCreator` to this union, 
  // the program will crash with OOM.
>;

These action types are used in segmented reducers, and eventually get combined into one large discriminated union of types near a redux combineReducers() call. I can provide more sample code, and will continue to work on a reduced repro.

Expected behavior:
tsc compiles the codebase without error.

Actual behavior:
tsc crashes with a unique out of memory error:

$ tsc --noEmit --diagnostics

<--- Last few GCs --->

[16153:0x102645000]   147934 ms: Scavenge 2141.2 (2240.4) -> 2126.5 (2240.9) MB, 9.1 / 0.0 ms  (average mu = 0.998, current mu = 1.000) allocation failure 
[16153:0x102645000]   148047 ms: Scavenge 2141.7 (2240.9) -> 2127.0 (2241.4) MB, 8.7 / 0.0 ms  (average mu = 0.998, current mu = 1.000) allocation failure 
[16153:0x102645000]   148160 ms: Scavenge 2142.2 (2241.4) -> 2127.5 (2241.9) MB, 15.1 / 0.0 ms  (average mu = 0.998, current mu = 1.000) allocation failure 


<--- JS stacktrace --->

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

    0: ExitFrame [pc: 0x2c389e8dbe3d]
Security context: 0x1fe24991e6e1 <JSObject>
    1: set [0x1fe249911ea1](this=0x1fe2f27d91d9 <Map map = 0x1fe2a7104359>,0x1fe2ac0b0e59 <String[11]: 545159,4710>,2)
    2: recursiveTypeRelatedTo(aka recursiveTypeRelatedTo) [0x1fe2bf802201] [/Users/mbusby/snip-project-name/node_modules/typescript/lib/tsc.js:~35308] [pc=0x2c389e8f82e5](this=0x1fe23dd826f1 <undefined>,source=0x1fe2a9be4a09 <Type map = 0x1fe2...

FATAL ERROR: invalid table size Allocation failed - JavaScript heap out of memory
 1: 0x10003b125 node::Abort() [/Users/mbusby/.nvm/versions/v10.15.0/bin/node]
 2: 0x10003b32f node::OnFatalError(char const*, char const*) [/Users/mbusby/.nvm/versions/v10.15.0/bin/node]
 3: 0x1001a8e85 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/Users/mbusby/.nvm/versions/v10.15.0/bin/node]
 4: 0x1005742a2 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/Users/mbusby/.nvm/versions/v10.15.0/bin/node]
 5: 0x1006e0756 v8::internal::OrderedHashTable<v8::internal::OrderedHashMap, 2>::Rehash(v8::internal::Handle<v8::internal::OrderedHashMap>, int) [/Users/mbusby/.nvm/versions/v10.15.0/bin/node]
 6: 0x1007a8793 v8::internal::Runtime_MapGrow(int, v8::internal::Object**, v8::internal::Isolate*) [/Users/mbusby/.nvm/versions/v10.15.0/bin/node]
 7: 0x2c389e8dbe3d 

Playground Link: None yet

Related Issues: #31281 looks similar, but the error message was very different.

Other diagnostic info

If I remove the 1 action that puts tsc over the edge, I can get diagnostic info on various versions of typescript:

On 3.3.3333:

Files:            644
Lines:         352690
Nodes:        1075014
Identifiers:   391809
Symbols:       505217
Types:         490478
Memory used: 3475902K
I/O read:       0.15s
I/O write:      0.00s
Parse time:     2.94s
Bind time:      1.13s
Check time:   369.67s
Emit time:      0.00s
Total time:   373.73s

On Version 3.5.0-dev.20190515:

$ tsc --noEmit --diagnostics
Files:            644
Lines:         353393
Nodes:        1075852
Identifiers:   391910
Symbols:       573963
Types:         537306
Memory used: 3537350K
I/O read:       0.15s
I/O write:      0.00s
Parse time:     2.81s
Bind time:      1.14s
Check time:   262.53s
Emit time:      0.00s
Total time:   266.47s

These numbers were collected with a tsconfig that looks like:

{
    "compilerOptions": {
      "esModuleInterop": true,
      "allowJs": false,
      "target": "es6",
      "lib": ["dom", "es2018"],
      "jsx": "react-native",
      "alwaysStrict": true,
      "strict": false,
      "module": "esnext",
      "moduleResolution": "node",
      "skipLibCheck": true,
      "skipDefaultLibCheck": true,
      "allowSyntheticDefaultImports": true,
      "baseUrl": "./",
      "types": [
        "jest",
        "node"
      ]
    },
    "include": [
      "src"
    ],
    "exclude": [
      "node_modules",
      "android",
      "ios"
    ]
  }

One thing I noticed in comparison to some of my other similar-but-larger projects is that this has a very large number of «Types» in the diagnostic info. This project shows 500k types in 650 files vs the ~80k types in 2000 files I have in another project.

Today I ran my script for filesystem indexing to refresh RAID files index and after 4h it crashed with following error:

[md5:]  241613/241627 97.5%  
[md5:]  241614/241627 97.5%  
[md5:]  241625/241627 98.1%
Creating missing list... (79570 files missing)
Creating new files list... (241627 new files)

<--- Last few GCs --->

11629672 ms: Mark-sweep 1174.6 (1426.5) -> 1172.4 (1418.3) MB, 659.9 / 0 ms [allocation failure] [GC in old space requested].
11630371 ms: Mark-sweep 1172.4 (1418.3) -> 1172.4 (1411.3) MB, 698.9 / 0 ms [allocation failure] [GC in old space requested].
11631105 ms: Mark-sweep 1172.4 (1411.3) -> 1172.4 (1389.3) MB, 733.5 / 0 ms [last resort gc].
11631778 ms: Mark-sweep 1172.4 (1389.3) -> 1172.4 (1368.3) MB, 673.6 / 0 ms [last resort gc].


<--- JS stacktrace --->

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

Security context: 0x3d1d329c9e59 <JS Object>
1: SparseJoinWithSeparatorJS(aka SparseJoinWithSeparatorJS) [native array.js:~84] [pc=0x3629ef689ad0] (this=0x3d1d32904189 <undefined>,w=0x2b690ce91071 <JS Array[241627]>,L=241627,M=0x3d1d329b4a11 <JS Function ConvertToString (SharedFunctionInfo 0x3d1d3294ef79)>,N=0x7c953bf4d49 <String[4]: ,n  >)
2: Join(aka Join) [native array.js:143] [pc=0x3629ef616696] (this=0x3d1d32904189 <undefin...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/usr/bin/node]
 2: 0xe2c5fc [/usr/bin/node]
 3: v8::Utils::ReportApiFailure(char const*, char const*) [/usr/bin/node]
 4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/bin/node]
 5: v8::internal::Factory::NewRawTwoByteString(int, v8::internal::PretenureFlag) [/usr/bin/node]
 6: v8::internal::Runtime_SparseJoinWithSeparator(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/bin/node]
 7: 0x3629ef50961b

Server is equipped with 16gb RAM and 24gb SSD swap. I highly doubt my script exceeded 36gb of memory. At least it shouldn’t

Script creates index of files stored as Array of Objects with files metadata (modification dates, permissions, etc, no big data)

Here’s full script code:
http://pastebin.com/mjaD76c3

I’ve already experiend weird node issues in the past with this script what forced me eg. split index into multiple files as node was glitching when working on such big files as String. Is there any way to improve nodejs memory management with huge datasets?

asked Jul 25, 2016 at 2:45

Lapsio's user avatar

2

If I remember correctly, there is a strict standard limit for the memory usage in V8 of around 1.7 GB, if you do not increase it manually.

In one of our products we followed this solution in our deploy script:

 node --max-old-space-size=4096 yourFile.js

There would also be a new space command but as I read here: a-tour-of-v8-garbage-collection the new space only collects the newly created short-term data and the old space contains all referenced data structures which should be in your case the best option.

Andrey Ermakov's user avatar

answered Jul 25, 2016 at 5:29

Felix's user avatar

FelixFelix

5,2411 gold badge9 silver badges17 bronze badges

8

If you want to increase the memory usage of the node globally — not only single script, you can export environment variable, like this:
export NODE_OPTIONS=--max_old_space_size=4096

Then you do not need to play with files when running builds like
npm run build.

answered Nov 23, 2018 at 8:56

Maksim Luzik's user avatar

Maksim LuzikMaksim Luzik

5,5634 gold badges36 silver badges56 bronze badges

4

Just in case anyone runs into this in an environment where they cannot set node properties directly (in my case a build tool):

NODE_OPTIONS="--max-old-space-size=4096" node ...

You can set the node options using an environment variable if you cannot pass them on the command line.

answered Sep 18, 2018 at 15:55

Kamiel Wanrooij's user avatar

Kamiel WanrooijKamiel Wanrooij

12.1k6 gold badges36 silver badges43 bronze badges

3

Here are some flag values to add some additional info on how to allow more memory when you start up your node server.

1GB — 8GB

#increase to 1gb
node --max-old-space-size=1024 index.js

#increase to 2gb
node --max-old-space-size=2048 index.js 

#increase to 3gb
node --max-old-space-size=3072 index.js

#increase to 4gb
node --max-old-space-size=4096 index.js

#increase to 5gb
node --max-old-space-size=5120 index.js

#increase to 6gb
node --max-old-space-size=6144 index.js

#increase to 7gb
node --max-old-space-size=7168 index.js

#increase to 8gb 
node --max-old-space-size=8192 index.js 

answered Feb 13, 2019 at 17:12

Nicholas Porter's user avatar

Nicholas PorterNicholas Porter

2,3582 gold badges20 silver badges36 bronze badges

4

I just faced same problem with my EC2 instance t2.micro which has 1 GB memory.

I resolved the problem by creating swap file using this url and set following environment variable.

export NODE_OPTIONS=--max_old_space_size=4096

Finally the problem has gone.

I hope that would be helpful for future.

answered Apr 17, 2020 at 2:57

Bat-Orshikh Baavgaikhuu's user avatar

4

i was struggling with this even after setting —max-old-space-size.

Then i realised need to put options —max-old-space-size before the karma script.

also best to specify both syntaxes —max-old-space-size and —max_old_space_size my script for karma :

node --max-old-space-size=8192 --optimize-for-size --max-executable-size=8192  --max_old_space_size=8192 --optimize_for_size --max_executable_size=8192 node_modules/karma/bin/karma start --single-run --max_new_space_size=8192   --prod --aot

reference https://github.com/angular/angular-cli/issues/1652

answered Jun 22, 2017 at 8:43

duchuy's user avatar

duchuyduchuy

5864 silver badges9 bronze badges

4

I encountered this issue when trying to debug with VSCode, so just wanted to add this is how you can add the argument to your debug setup.

You can add it to the runtimeArgs property of your config in launch.json.

See example below.

{
"version": "0.2.0",
"configurations": [{
        "type": "node",
        "request": "launch",
        "name": "Launch Program",
        "program": "${workspaceRoot}\server.js"
    },
    {
        "type": "node",
        "request": "launch",
        "name": "Launch Training Script",
        "program": "${workspaceRoot}\training-script.js",
        "runtimeArgs": [
            "--max-old-space-size=4096"
        ]
    }
]}

answered Jun 20, 2017 at 1:26

Astr-o's user avatar

Astr-oAstr-o

4954 silver badges10 bronze badges

3

I just want to add that in some systems, even increasing the node memory limit with --max-old-space-size, it’s not enough and there is an OS error like this:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

In this case, probably is because you reached the max mmap per process.

You can check the max_map_count by running

sysctl vm.max_map_count

and increas it by running

sysctl -w vm.max_map_count=655300

and fix it to not be reset after a reboot by adding this line

vm.max_map_count=655300

in /etc/sysctl.conf file.

Check here for more info.

A good method to analyse the error is by run the process with strace

strace node --max-old-space-size=128000 my_memory_consuming_process.js

answered Jan 26, 2020 at 23:55

jbaylina's user avatar

jbaylinajbaylina

4,2881 gold badge29 silver badges39 bronze badges

2

I’ve faced this same problem recently and came across to this thread but my problem was with React App. Below changes in the node start command solved my issues.

Syntax

node --max-old-space-size=<size> path-to/fileName.js

Example

node --max-old-space-size=16000 scripts/build.js

Why size is 16000 in max-old-space-size?

Basically, it varies depends on the allocated memory to that thread and your node settings.

How to verify and give right size?

This is basically stay in our engine v8. below code helps you to understand the Heap Size of your local node v8 engine.

const v8 = require('v8');
const totalHeapSize = v8.getHeapStatistics().total_available_size;
const totalHeapSizeGb = (totalHeapSize / 1024 / 1024 / 1024).toFixed(2);
console.log('totalHeapSizeGb: ', totalHeapSizeGb);

answered Aug 13, 2019 at 15:24

Venkat.R's user avatar

Venkat.RVenkat.R

7,3505 gold badges40 silver badges63 bronze badges

Steps to fix this issue (In Windows) —

  1. Open command prompt and type %appdata% press enter
  2. Navigate to %appdata% > npm folder
  3. Open or Edit ng.cmd in your favorite editor
  4. Add --max_old_space_size=8192 to the IF and ELSE block

Your node.cmd file looks like this after the change:

@IF EXIST "%~dp0node.exe" (
  "%~dp0node.exe" "--max_old_space_size=8192" "%~dp0node_modules@angularclibinng" %*
) ELSE (
  @SETLOCAL
  @SET PATHEXT=%PATHEXT:;.JS;=;%
  node "--max_old_space_size=8192" "%~dp0node_modules@angularclibinng" %*
)

answered Oct 19, 2018 at 5:30

Umang Patwa's user avatar

Umang PatwaUmang Patwa

2,6553 gold badges30 silver badges40 bronze badges

0

Recently, in one of my project ran into same problem. Tried couple of things which anyone can try as a debugging to identify the root cause:

  1. As everyone suggested , increase the memory limit in node by adding this command:

    {
       "scripts":{
          "server":"node --max-old-space-size={size-value} server/index.js"
       }
    }
    

Here size-value i have defined for my application was 1536 (as my kubernetes pod memory was 2 GB limit , request 1.5 GB)

So always define the size-value based on your frontend infrastructure/architecture limit (little lesser than limit)

One strict callout here in the above command, use --max-old-space-size after node command not after the filename server/index.js.

  1. If you have ngnix config file then check following things:

    • worker_connections: 16384 (for heavy frontend applications)
      [nginx default is 512 connections per worker, which is too low for modern applications]

    • use: epoll (efficient method) [nginx supports a variety of connection processing methods]

    • http: add following things to free your worker from getting busy in handling some unwanted task. (client_body_timeout , reset_timeout_connection , client_header_timeout,keepalive_timeout ,send_timeout).

  2. Remove all logging/tracking tools like APM , Kafka , UTM tracking, Prerender (SEO) etc middlewares or turn off.

  3. Now code level debugging: In your main server file , remove unwanted console.log which is just printing a message.

  4. Now check for every server route i.e app.get() , app.post() ... below scenarios:

  • data => if(data) res.send(data) // do you really need to wait for data or that api returns something in response which i have to wait for?? , If not then modify like this:
data => res.send(data) // this will not block your thread, apply everywhere where it's needed
  • else part: if there is no error coming then simply return res.send({}) , NO console.log here.

  • error part: some people define as error or err which creates confusion and mistakes. like this:

    `error => { next(err) } // here err is undefined`
    
     `err => {next(error) } // here error is undefined`
    
     `app.get(API , (re,res) =>{
         error => next(error) // here next is not defined
      })`
    
  • remove winston , elastic-epm-node other unused libraries using npx depcheck command.

  • In the axios service file , check the methods and logging properly or not like :

      if(successCB) console.log("success") successCB(response.data) // here it's wrong statement, because on success you are just logging and then `successCB` sending  outside the if block which return in failure case also.
    
  • Save yourself from using stringify , parse etc on accessive large dataset. (which i can see in your above shown logs too.

  1. Last but not least , for every time when your application crashes or pods restarted check the logs. In log specifically look for this section: Security context
    This will give you why , where and who is the culprit behind the crash.

answered Apr 2, 2021 at 5:02

sidverma's user avatar

sidvermasidverma

1,11412 silver badges22 bronze badges

I will mention 2 types of solution.

My solution : In my case I add this to my environment variables :

export NODE_OPTIONS=--max_old_space_size=20480

But even if I restart my computer it still does not work. My project folder is in d: disk. So I remove my project to c: disk and it worked.

My team mate’s solution : package.json configuration is worked also.

"start": "rimraf ./build && react-scripts --expose-gc --max_old_space_size=4096 start",

answered Aug 10, 2021 at 13:09

cansu's user avatar

cansucansu

84210 silver badges23 bronze badges

1

For other beginners like me, who didn’t find any suitable solution for this error, check the node version installed (x32, x64, x86). I have a 64-bit CPU and I’ve installed x86 node version, which caused the CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error.

answered Sep 22, 2020 at 22:33

Irina Sargu's user avatar

0

if you want to change the memory globally for node (windows) go to advanced system settings -> environment variables -> new user variable

variable name = NODE_OPTIONS
variable value = --max-old-space-size=4096

answered Sep 23, 2019 at 14:38

Ahmed Aboud's user avatar

Ahmed AboudAhmed Aboud

1,16414 silver badges19 bronze badges

0

You can also change Window’s environment variables with:

 $env:NODE_OPTIONS="--max-old-space-size=8192"

answered Oct 17, 2020 at 17:47

FiringBlanks's user avatar

FiringBlanksFiringBlanks

1,9384 gold badges30 silver badges46 bronze badges

--max-old-space-size

Unix (Mac OS)

  1. Open a terminal and open our .zshrc file using nano like so (this will create one, if one doesn’t exist):

    nano ~/.zshrc

  2. Update our NODE_OPTIONS environment variable by adding the following line into our currently open .zshrc file:

    export NODE_OPTIONS=--max-old-space-size=8192 # increase node memory limit

Please note that we can set the number of megabytes passed in to whatever we like, provided our system has enough memory (here we are passing in 8192 megabytes which is roughly 8 GB).

  1. Save and exit nano by pressing: ctrl + x, then y to agree and finally enter to save the changes.

  2. Close and reopen the terminal to make sure our changes have been recognised.

  3. We can print out the contents of our .zshrc file to see if our changes were saved like so: cat ~/.zshrc.

Linux (Ubuntu)

  1. Open a terminal and open the .bashrc file using nano like so:

    nano ~/.bashrc

The remaining steps are similar with the Mac steps from above, except we would most likely be using ~/.bashrc by default (as opposed to ~/.zshrc). So these values would need to be substituted!

Link to Nodejs Docs

answered Feb 14, 2022 at 5:30

JSON C11's user avatar

JSON C11JSON C11

10.8k7 gold badges79 silver badges64 bronze badges

Use the option --optimize-for-size. It’s going to focus on using less ram.

answered May 2, 2021 at 1:15

The epic face 007's user avatar

1

I had this error on AWS Elastic Beanstalk, upgrading instance type from t3.micro (Free tier) to t3.small fixed the error

answered Dec 9, 2021 at 9:31

atazmin's user avatar

atazminatazmin

4,2191 gold badge24 silver badges19 bronze badges

In my case, I upgraded node.js version to latest (version 12.8.0) and it worked like a charm.

Aplet123's user avatar

Aplet123

32.8k1 gold badge28 silver badges54 bronze badges

answered Jun 12, 2020 at 8:06

Angela Rana's user avatar

3

Upgrade node to the latest version. I was on node 6.6 with this error and upgraded to 8.9.4 and the problem went away.

answered Jan 12, 2018 at 7:01

Richard Frank's user avatar

For Angular, this is how I fixed

In Package.json, inside script tag add this

"scripts": {
  "build-prod": "node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng build --prod",
},

Now in terminal/cmd instead of using ng build --prod just use

npm run build-prod

If you want to use this configuration for build only just remove --prod from all the 3 places

answered Mar 12, 2021 at 17:07

R15's user avatar

R15R15

12.5k14 gold badges88 silver badges160 bronze badges

I experienced the same problem today. The problem for me was, I was trying to import lot of data to the database in my NextJS project.

So what I did is, I installed win-node-env package like this:

yarn add win-node-env

Because my development machine was Windows. I installed it locally than globally. You can install it globally also like this: yarn global add win-node-env

And then in the package.json file of my NextJS project, I added another startup script like this:

"dev_more_mem": "NODE_OPTIONS="--max_old_space_size=8192" next dev"

Here, am passing the node option, ie. setting 8GB as the limit.
So my package.json file somewhat looks like this:

{
  "name": "my_project_name_here",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "dev_more_mem": "NODE_OPTIONS="--max_old_space_size=8192" next dev",
    "build": "next build",
    "lint": "next lint"
  },
  ......
}

And then I run it like this:

yarn dev_more_mem

For me, I was facing the issue only on my development machine (because I was doing the importing of large data). Hence this solution. Thought to share this as it might come in handy for others.

answered Mar 8, 2022 at 21:44

Akhilesh B Chandran's user avatar

I had the same issue in a windows machine and I noticed that for some reason it didn’t work in git bash, but it was working in power shell

answered Aug 30, 2022 at 10:03

Symeon Mattes's user avatar

Just in case it may help people having this issue while using nodejs apps that produce heavy logging, a colleague solved this issue by piping the standard output(s) to a file.

answered Apr 4, 2018 at 8:39

Adrien Joly's user avatar

Adrien JolyAdrien Joly

4,9104 gold badges28 silver badges43 bronze badges

If you are trying to launch not node itself, but some other soft, for example webpack you can use the environment variable and cross-env package:

$ cross-env NODE_OPTIONS='--max-old-space-size=4096' 
  webpack --progress --config build/webpack.config.dev.js

answered Apr 30, 2019 at 1:50

Piterden's user avatar

PiterdenPiterden

7595 silver badges16 bronze badges

For angular project bundling, I’ve added the below line to my pakage.json file in the scripts section.

"build-prod": "node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/ng build --prod --base-href /"

Now, to bundle my code, I use npm run build-prod instead of ng build --requiredFlagsHere

hope this helps!

answered Oct 4, 2019 at 16:00

rgantla's user avatar

rgantlargantla

1,8888 silver badges16 bronze badges

If any of the given answers are not working for you, check your installed node if it compatible (i.e 32bit or 64bit) to your system. Usually this type of error occurs because of incompatible node and OS versions and terminal/system will not tell you about that but will keep you giving out of memory error.

answered Jun 4, 2021 at 14:01

Shoaib Iqbal's user avatar

Shoaib IqbalShoaib Iqbal

2,2904 gold badges24 silver badges48 bronze badges

None of all these every single answers worked for me (I didn’t try to update npm tho).

Here’s what worked: My program was using two arrays. One that was parsed on JSON, the other that was generated from datas on the first one. Just before the second loop, I just had to set my first JSON parsed array back to [].

That way a loooooot of memory is freed, allowing the program to continue execution without failing memory allocation at some point.

Cheers !

answered Dec 20, 2022 at 20:03

Pierrick Martellière's user avatar

You can fix a «heap out of memory» error in Node.js by below approaches.

  1. Increase the amount of memory allocated to the Node.js process by using the —max-old-space-size flag when starting the application. For example, you can increase the limit to 4GB by running node —max-old-space-size=4096 index.js.

  2. Use a memory leak detection tool, such as the Node.js heap dump module, to identify and fix memory leaks in your application. You can also use the node inspector and use chrome://inspect to check memory usage.

  3. Optimize your code to reduce the amount of memory needed. This might involve reducing the size of data structures, reusing objects instead of creating new ones, or using more efficient algorithms.

  4. Use a garbage collector (GC) algorithm to manage memory automatically. Node.js uses the V8 engine’s garbage collector by default, but you can also use other GC algorithms such as the Garbage Collection in Node.js

  5. Use a containerization technology like Docker which limits the amount of memory available to the container.

  6. Use a process manager like pm2 which allows to automatically restart the node application if it goes out of memory.

answered Jan 12 at 16:00

Anupam Chaplot's user avatar

javascript heap out of memory

Ошибка «Heap out of memory» в JavaScript возникает когда приложению недостаточно памяти. В этой статье мы разберемся как быстро исправить эту ошибку.

Самый быстрый способ — увеличить количество памяти в Node.js. Начиная с версии v8 вы можете устанавливать ограничение в мегабайтах с помощью флага  --max-old-space-size:

node --max-old-space-size=4096 index.js

Вы можете установить любое ограничение, но не используйте всю доступную память, иначе может произойти крэш системы.

Аналогичного эффекта можно добиться с помощью другого флага:

NODE_OPTIONS="--max-old-space-size=4096" node index.js

Изменение ограничения памяти для всей среды Node.js

Чтобы изменить лимит памяти для всей среды, нужно установить значение переменной NODE_OPTIONS в конфигурационном файле (его расширение .bashrc, bash_profile или .zshrc и т. п.).

export NODE_OPTIONS=--max_old_space_size=4096

«Heap out of memory» во время nmp install

Если во время установки пакетов с помощью npn или yarn у вас появляется эта ошибка, вы можете увеличить лимит памяти на время установки.

node --max-old-space-size=4096 $(which npm) install -g nextawesomelib

Что означает эта ошибка?

По умолчанию в Node.js установлен лимит памяти, который не позволяет программе занять слишком много памяти и уронить всю систему. Лимит отличается на разных версиях Node.js и архитектурах (32бита или 64бита).

Ограничения памяти на разных версиях Node.js

Эти значения не объявлены официально, но с помощью небольшой программы можно получить такие значения для 64 битной архитектуры.

Лимиты памяти на разных версиях Node.js

4GB памяти в куче будет достаточно для большинства случаев

Чтобы проверить лимит памяти вашей системы, создайте файл index.js и добавьте в него следующий код:

const array = [];
while (true) {
  // увеличение массива на каждой итерации
  array.push(new Array(10000000));

  const memory = process.memoryUsage();
  console.log((memory.heapUsed / 1024 / 1024 / 1024).toFixed(4), 'GB');
}

Как избежать недостатка памяти в Node.js

Увеличение лимита памяти поможет быстро исправить проблему, но этого может быть недостаточно. В следующий раз память системы может закончиться. В любом случае стоит выяснить источник проблемы.

Вот три альтернативных решения, которые позволят уменьшить потребление памяти.

Обработка данных по частям

Иногда нужно обработать большой набор данных. Например, вы пишите программу, которая принимает данные из CSV файла, очищает их и добавляет в БД (это называется ETL: извлечение, трансформация, загрузка).

Если в такой ситуации программе начинает не хватать памяти, попробуйте разделить данные на несколько частей.

# split -l numberoflines filename
split -l 1000000 users.csv

Подробнее о том, как сделать это в MongoDB в этом ответе на StackOverflow.

Избегайте утечек памяти

В этой статье объясняется, как работает управление памятью в JavaScript, и как избежать большинства возможных утечек.

Её содержание сводится к тому, что большинство утечек, которые можно отследить, вызваны неудалёнными ссылками на объекты, которые больше не нужны. Это может случиться, когда вы забыли удалить interval, timer или чрезмерно используете глобальные переменные.

Профилирование

Профилирование помогает обнаружить утечки памяти. На фронтенде это можно сделать в Chrome в Инструментах разработчика во вкладке Memory.

В Node.js начиная с версии 6.3.0 также можно использовать Chrome для отладки использования памяти.

Во-первых, запустите приложение в режиме проверки:

node --inspect index.js

Затем откройте страницу в Chrome, введите адрес chrome://inspect и нажмите на кнопку Open dedicated DevTools for Node.

После этого откроется окно, в котором вы сможете подключиться к вашему Node.js приложению.

Devtools Node.js

Перезапуск процессов

Допустим, ваша программа работает на компьютере с ограниченным объёмом памяти, например Raspberry Pi.

Мы будем использовать cluster и библиотеки node v8.

Cluster даёт возможность воспользоваться преимуществами многоядерных систем и запускать кластер из процессов Node.js.

V8 предоставляет API для конкретной версии V8, используемой в Node.js.

Давайте разделим программу на две сущности: master и worker.

Master будет перезапускать worker`ов в случае, если они перестанут работать из-за переполнения кучи. Worker`ы будут отвечать за основную логику (в нашем случае запускать тяжёлую функцию heavyHeapConsumer).

const cluster = require('cluster');
const v8 = require('v8');

let heavyHeapConsumer = () => {
  let arrays = [];
  setInterval(() => {
    arrays.push(new Array(1000000));
  }, 100);
};

if (cluster.isMaster) {
  cluster.fork();
  cluster.on('exit', (deadWorker, code, signal) => {
    // Перезапуск worker`а
    let worker = cluster.fork();
    
    // Сохранение id процесса
    let newPID = worker.process.pid;
    let oldPID = deadWorker.process.pid;
    
    // Логгирование
    console.log('worker ' + oldPID + ' died.');
    console.log('worker ' + newPID + ' born.');
  });
} else { // worker
  const initialStats = v8.getHeapStatistics();
  
  const totalHeapSizeThreshold = 
    initialStats.heap_size_limit * 85 / 100;
  console.log("totalHeapSizeThreshold: " + totalHeapSizeThreshold);
  
  let detectHeapOverflow = () => {
    let stats = v8.getHeapStatistics();
    
    console.log("total_heap_size: " + (stats.total_heap_size));
    
    if ((stats.total_heap_size) > totalHeapSizeThreshold) {
      process.exit();
    }
  };
  setInterval(detectHeapOverflow, 1000);
  
  // выполнение основной логики
  heavyHeapConsumer();
}

При первом запуске приложения создается worker и подписка на событие exit, при срабатывании которой создаётся новый worker, и событие логгируется.

total_heap_size — размер кучи, который можно увеличить.

heap_size_limit — максимально возможный размер кучи.

В коде worker`а устанавливается total_heap_size равный 85% от heap_size_limit. Затем worker каждую секунду проверяет не превышен ли лимит. Если лимит превышен, то процесс worker убивает себя.

Лимит (85%) и интервал проверки (1 секунда) нужно выбирать для каждого конкретного случая. Здесь функция heavyHeapConsumer увеличивает кучу каждые 100мс. Если в вашем варианте увеличение будет происходить каждые 10мс, то следует уменьшить лимит и увеличить интервал проверки.

Полный код примера доступен на GitHub.

Источники JavaScript Heap Out Of Memory Error,
Detect heap overflow on Node.js: JavaScript heap out of memory

Photo from Unsplash

When running JavaScript process using Node, you may see an error that stops the running process.

The fatal error says JavaScript heap out of memory as seen below:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

Sometimes, it also has alternative error message like this:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

Both errors above occur when JavaScript has a lot of processes to handle, and the default allocated memory by Node is not enough to finish the running process.

An example of this error can be found when you have to build the packages you installed using npm install with the node-gyp library.

The default Node memory limit varies from version to version, but the latest Node version 15 still has a memory limit below 2GB.

Solve JavaScript heap out of memory error

To fix JavaScript heap out of memory error, you need to add the --max-old-space-size option when running your npm command.

Here’s an example of increasing the memory limit to 4GB:

node --max-old-space-size=4096 index.js

If you want to add the option when running the npm install command, then you can pass the option from Node to npm as follows:

node --max-old-space-size=4096 `which npm` install

If you still see the heap out of memory error, then you may need to increase the heap size even more. The memory size starts from 1024 for 1GB:

--max-old-space-size=1024 # increase memory to 1GB
--max-old-space-size=2048 # increase memory to 2GB
--max-old-space-size=3072 # increase memory to 3GB
--max-old-space-size=4096 # increase memory to 4GB
--max-old-space-size=8192 # increase memory to 8GB

Alternatively, you can also set the memory limit for your entire environment using a configuration file.

Set Node memory limit using configuration file

You can set the default memory limit using your terminal client’s configuration file.

If you’re using Bash, then add the following line to your .bashrc file:

export NODE_OPTIONS=--max_old_space_size=4096 #4GB

When you’re using ZSH, then add the line above to the .zshrc file.

Don’t forget to check the available memory in your machine before increasing the memory limit.

Too much memory allocated for Node may cause your machine to hang.

Why JavaScript heap out of memory occurs?

Before the creation of Node, JavaScript’s role in web development is limited to manipulating DOM elements in order to create an interactive experience for the users of your web application.

But after the release of Node, JavaScript suddenly had a back-end architecture, where you can run complex database queries and other heavy processing before sending data back to the front-end.

JavaScript also saw the rise of npm that allows you to download libraries and modules like React and Lodash.

Many modules downloaded from npm have lots of dependencies on other modules, and some may need to be compiled before they can be used.

Node memory usage will increase as you have more tasks to process. This is why JavaScript may have a heap out of memory error today.

Table of Contents
Hide
  1. What is fatal error: ineffective mark-compacts near heap limit allocation failed – javascript heap out of memory?
  2. How to fix fatal error: ineffective mark-compacts near heap limit allocation failed – javascript heap out of memory?
    1. Solution 1 – Install Latest Node Version
    2. Solution 2 – Increase the Memory Size using export
    3. Solution 3 – Set the memory through NODE_OPTIONS
  3. Conclusion 

The fatal error: ineffective mark-compacts near heap limit allocation failed – javascript heap out of memory occurs if there is any memory leak or the application consumes a lot of memory.

In this article, we will look at what exactly is the fatal error: ineffective mark-compacts near heap limit allocation failed – javascript heap out of memory means and how to resolve this error.

If you are building and running the application on Node.JS version 10, and if you have any kind of memory leak in the code, it can lead to javascript heap out of memory.

It can also happen if the application consumes too much memory and mainly while processing extensive data.

The memory management in Node V10 is entirely different when compared to the latest version, and by default, 512 MB of memory/heap size is allocated in Node 10. If the application crosses this size, it will result in a javascript heap out of memory.

How to fix fatal error: ineffective mark-compacts near heap limit allocation failed – javascript heap out of memory?

We can resolve this issue by installing the latest Node version or by increasing the default allocated memory size. Also, you need to check if there is any memory leak in the application.

Solution 1 – Install Latest Node Version

The Node 10 has a different way of memory allocation, and by default, the max size set is 512MB. Hence you can install the latest LTS Node 12/16 to resolve the issue.

Solution 2 – Increase the Memory Size using export

Increasing the default memory size will fix the issue; you could increase the memory allocation by running the below command.

The size can be of any number according to the needs, the below command is just an indicative examples on how to increase the memory size.

export NODE_OPTIONS="--max-old-space-size=5120" # Increases to 5 GB
export NODE_OPTIONS="--max-old-space-size=6144" # Increases to 6 GB
export NODE_OPTIONS="--max-old-space-size=7168" # Increases to 7 GB
export NODE_OPTIONS="--max-old-space-size=8192" # Increases to 8 GB

Solution 3 – Set the memory through NODE_OPTIONS

We can change the default memory size using the set NODE_OPTIONS as shown below.

set NODE_OPTIONS=--max_old_space_size=4096

Note: All the solution above works effectively, but you should always ensure there is no memory leak on your application first before changing these values and also ensure you have the free memory space left.

Conclusion 

The fatal error: ineffective mark-compacts near heap limit allocation failed – javascript heap out of memory happens when you run the application with Node 10 version, and your application consumes more than 512MB memory.

We can resolve the issue by upgrading to the latest version of Node as the memory allocation is managed efficiently. Alternatively, we can increase the default memory size using the NODE_OPTIONS

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

A common problem while working on a JavaScript Node.js project is the “JavaScript heap out of memory” error. This error usually occurs when the default memory allocated by your system to Node.js is not enough to run a large project.

The error is common whether you run your project on Windows, macOS, or a Linux distribution like Ubuntu. Luckily, there are a few easy fixes that can help resolve the “JavaScript heap out of memory” error.

What Is Heap Memory?

Before you look at fixing the error, it’s useful to understand what heap memory is and how programs use it.

shape of skull in computer code

Memory allocated on the system heap is also called dynamically allocated memory. It’s up to the programmer to use the available memory as they see fit. More importantly, the heap size for a program depends on the available virtual memory allocated to it.

If you’re running a relatively-large project, it may require more memory than the default allocated chunk. This may cause your project to crash and log the “JavaScript heap out of memory” error.

How to Fix JavaScript Heap Out of Memory on Windows

Regardless of your IDE, the “JavaScript heap out of memory” fix is identical.

You can add an environment variable through Control Panel to increase the memory allocated to a Node.js project.

  1. Open the Start menu, search for Advanced System Settings, and select the Best match.
  2. From the dialog box, click on Environment Variables, then click on New from either System variables or User variables. The former applies to all users on your computer, while the latter affects just your current account
  3. In the Variable name field enter NODE_OPTIONS. In the Variable value field enter —max-old-space-size=4096. This value will allocate 4GB of virtual memory to Node.js. To set a different value, multiply the amount you require in GB by 1024 (the variable value needs to be in MB).
    A Windows dialog showing a new environment variable with fields for name and value
  4. Click on OK to save your changes, then click Apply and finally click OK once more. Restart your project for the changes to take effect.

You can also set an environment variable through a Windows PowerShell terminal.

Launch a PowerShell terminal, type the below command and press Enter:

 $env:NODE_OPTIONS="--max-old-space-size=4096" 

If you only want to increase the heap memory temporarily, run the below command in a PowerShell terminal before running your project:

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

Once you’ve entered this command, you can deploy/run your project using npm run dev or your own script.

Remember always to enter the required memory size in MB. Not doing so can cause unexpected behavior in your program. It is also vital not to allocate your entire available memory as this can cause a significant system failure.

How to Fix JavaScript Heap Out of Memory Error on macOS and Linux

On macOS and Linux, the heap memory fix is very similar. You should export an environment variable that specifies the amount of virtual memory allocated to Node.js.

In your terminal, before you run your project, enter the following command and press Enter:

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

This will allocate 4GB of virtual memory to the execution space of Node.js. To set a different amount of memory, replace 4096 with the required amount in MB.

You can add the above command to your configuration file to avoid repeating the process. To do so, follow the same process for setting your PATH variable.

Avoid JavaScript Heap Out of Memory Error

You can avoid this error by ensuring your program is free of memory leaks. Proper memory management is crucial when writing your programs, especially in a low-level language.

While increasing the allocated memory will temporarily fix the problem, you should find the root cause and fix it.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error insufficient shared memory reg ru
  • Fatal error insufficient power configured
  • Fatal error in vertex shader compilation
  • Fatal error in twain device driver
  • Fatal error in object unshallow

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии