Open In App

Memory leak with Cluster and ExpressJS

A memory leak is a type of software bug that occurs when a program or application fails to correctly release memory that it no longer needs. This can lead to a gradual decrease in the amount of available memory, which can eventually cause the program or system to slow down or crash.

Reasons for memory leaks can include:



An example of a memory leak in a program would be a simple C++ program that dynamically allocates memory for an array of integers, but never deallocates that memory. Each time a new array is allocated the memory from the previous array is not released, thus gradually allocating more memory, eventually causing the program to crash.

To avoid memory leaks, programmers should:



Steps to Install and Run Ember.js:

Step 1: Run the below command to install the Ember command-line interface:

npm install -g ember-cli

Step 2: Create a new Ember project using the command ember new my-project-name.

ember new <project-name>

Step 3: Navigate to the project directory using the command cd my-project-name.

cd my-project-name

Step 4: Run the development server using the command ember serve.

ember serve

Note: You can also run the code on the node.js command prompt.

Example 1: Event emitters: If an event is emitted and there are no listeners for it, the event will be retained in memory and not garbage collected. This can lead to a memory leak if the event is emitted repeatedly.




const cluster = require('cluster');
const express = require('express');
const app = express();
 
if (cluster.isMaster) {
    let worker = cluster.fork();
    worker.on('message', function (msg) {
        console.log(msg);
    });
    setInterval(function () {
        worker.send('hello');
    }, 1000);
} else {
    process.on('message', function (msg) {
        console.log(msg);
    });
}

Output:

Memory leak with Cluster and ExpressJS

Example 2: Unhandled promise rejections: If a promise is rejected but the rejection is not handled, it will continue to retain resources and cause a memory leak.




const cluster = require('cluster');
const express = require('express');
const app = express();
 
if (cluster.isMaster) {
    let worker = cluster.fork();
    worker.on('message', function (msg) {
        console.log(msg);
    });
    setInterval(function () {
        let promise = new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject(new Error('Error'));
            }, 1000);
        });
        promise.catch(function (error) {
            worker.send(error.message);
        });
    }, 1000);
} else {
    process.on('message', function (msg) {
        console.log(msg);
    });
}

Output:

Memory leak with Cluster and ExpressJS


Article Tags :