How to solve “Process out of Memory Exception” in Node.js?


"Process out of Memory" is an error that occurs when a Node.js program tries to use more memory than the system has available. This can happen when the program grows too big or runs for too long and can cause the system to stop working properly. To prevent this error, we may need to limit the amount of memory our program uses or find ways to optimize its performance.

In this tutorial, we will learn about the "Process out of Memory Exception" in Node.js, what causes it to occur, and how to solve it. We will also explore some practical examples of how to identify and fix memory leaks in Node.js applications.

Steps to Avoid "Process out of Memory Exception" in Node.js

In general, a "Process out of Memory Exception" can occur when the Node.js process uses more memory than the system can allocate to it. To avoid this exception, it's important to monitor the memory usage of our Node.js application, identify potential memory leaks, and optimize the code accordingly.

Users can follow the steps below to solve "Process out of Memory Exception" in Node.js −

Monitor memory usage

The first step in preventing the "Process out of Memory Exception" is to monitor the memory usage of our Node.js application. This can be done by using the process.memoryUsage() method, which returns an object that contains information about the process's memory usage, including the heap size, the resident set size, and the amount of memory used by the application.

console.log(process.memoryUsage()); 

Identify memory leaks

By understanding the memory usage, we can locate any memory leaks in the code.

A memory leak is when memory is allocated but never released, even when it is no longer needed. This can cause our process to use more memory than the system is able to allocate, leading to an error.

Optimise code

To use less memory, we should review our code and find ways to improve it, like reducing unnecessary data structures or fixing cyclical references.

Increase memory allocation

If the memory usage is consistently high, we may need to allocate more memory to the Node.js process by setting the --max-old-space-size option when starting our Node.js application.

Use a process manager

Using a process manager like PM2 can help restart the Node.js process if it encounters a "Process out of Memory Exception" error.

Solve "Process out of Memory Exception" by fixing a memory leak

Here's an example of how we can solve "Process out of Memory Exception" in Node.js by identifying and fixing a memory leak.

Step 1 − First, we need to monitor the memory usage of our Node.js process. We can do this by using the "process.memoryUsage()" method.

Step 2 − Next, we run the application and keep an eye on the memory usage over time. If we see that memory usage is increasing, it may indicate a memory leak.

Step 3 − Now, we need to identify the source of the memory leak. We can use a tool like the heapdump package. This package allows us to take a snapshot of the heap and analyse it using tools like Chrome DevTools.

To use heapdump, we need to add this line to our code −

let heapdump = require("heapdump"); 

Step 4 − We also need to send the SIGUSR2 signal to the Node.js process to take a heap dump. This can be done by running the command “kill -s SIGUSR2 ” where is the process ID of the Node.js process.

Step 5 − We then analyze the heap dump using Chrome DevTools and look for objects that are growing in size. This will help us identify the cause of the memory leak.

Step 6 − Finally, we need to fix the memory leak by refactoring our code. For example, if we are using an event emitter and not removing listeners, we can fix the leak by removing the listeners when they are no longer needed.

Here is an example of how to do this −

let EventEmitter = require("events");
let emitter = new EventEmitter();
let listener = function () {
   console.log("Event fired!");
};
emitter.on("event", listener);

// Remove the listener when it is no longer needed
emitter.removeListener("event", listener); 

Example

In the example below, we show how to monitor the memory usage of a Node.js process −

Step 1 − We start a setInterval method that will run every second.

Step 2 − Within the setInterval, we call the process.memoryUsage() method to get information about the memory usage of our application.

Step 3 − The memoryUsage object that is returned by process.memoryUsage() has three properties: rss, heapTotal, and heapUsed.

Step 4 − The rss property tells us how much memory is being held in RAM, while heapTotal and heapUsed tell us the total and used sizes of the JavaScript heap.

Step 5 − We log the memory usage statistics to the console every second, so we can see how the memory usage changes over time

Here's an example of how we can use process.memoryUsage() −

setInterval(() => {
   const memoryUsage = process.memoryUsage();
   console.log(`RSS: ${memoryUsage.rss} Heap Total: ${memoryUsage.heapTotal} Heap Used: ${memoryUsage.heapUsed}`);
}, 1000);

Output

In this tutorial, Users learned about the "Process out of Memory Exception" in Node.js and how to prevent it from happening. Users also learned that monitoring the memory usage of their Node.js application and identifying potential memory leaks is key to avoid this exception.

By following these steps in this tutorial, we can avoid "Process Out of Memory Exception" and ensure our Node.js application runs smoothly.

Updated on: 28-Feb-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements