Different ways to fix out of memory issues in nodejs heap and process


In this article, Discussed about how to fix out of memory errors in Nodejs Solution of outofmemory issues in Nodejs application

Javascript or nodejs apps throws the below error stack trace

Some times, Running Nodejs application throws an below errors and crashed the application.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed — process out of memory
  • What is Out of memory issue?

An application needs some memory to run javascript programs.

This is error is thrown when an application running and need more memory than the allocated memory .

  • Where this error occurs ?

This error will be shown in any javascript application using nodejs and javascript applications like Angular, Vue and React EmberJS.

when you run one or more below commands

  • ng serve
  • npm start
  • npm install
  • npm run build
  • node application.js

The application getting slowed or stack or crashed because of performance memory issues

By default Memory allocated in Heap is 512MB.

CALL_AND_RETRY_LAST Allocation failed error thrown when an application is allocated with heap size more than the available default free memory in running environment

Solution or Fix for CALL_AND_RETRY_LAST Allocation failed

There are multiple ways to fix it.

In NodeJS , there is command line flag –max-old-space-size and increase to memory less than your physical server RAM.

suppose, You have 4GB RAM, change –max-old-space-size=Upto 4GB RAM. ``markup node –max-old-space-size=4096 app.js


This starts the node process server with allocated memory of 4094 memory and applies to single session.


Other way is to add environment variable NODE_OPTION  with this flag value
```markup
export NODE_OPTIONS=--max_old_space_size=4096

This applies to all sessions with this value.

You can also add in .bashrc file in linux or unix machine during loading user profile startup.

export NODE_OPTIONS=--max_old_space_size=4096

Thrid option is to add to npm scripts in package.json file

   "scripts": {
     "start": "node --max_old_space_size=4096 index.js",
   }

Conclusion

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.