The Wayback Machine - https://web.archive.org/web/20240626182349/https://www.geeksforgeeks.org/how-does-the-cluster-module-work/
Open In App

How does the cluster module work ?

Last Updated : 06 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn what is cluster modules and how does it works in node.js. Let’s get started.

Node.js is a single-threaded machine that uses javascript as its scripting language. Due to a single thread in node.js, it handles memory more efficiently because there are no multiple threads due to which no thread management is needed. Now to handle workload efficiently and to take advantage of computer multi-core systems, cluster modules are created that provide us the way to make child processes that run simultaneously with a single parent process. Each child process (more specifically worker process) has its own event loop, memory, V8 instance, and shares the same server port.

Syntax: Below is the syntax for including the cluster module in your node application.

const cluster=require('cluster');

Example:

Javascript




const cluster=require("cluster");
const express=require("express");
const app=express();
const total_cpus=require("os").cpus().length;
  
if(cluster.isMaster){
    console.log(`Master process ${process.pid} is running`);
      
    // Fork child processes(workers)
    for(let i=0;i<total_cpus;i++){
       cluster.fork();
    }
      
    cluster.on("exit",(worker,code,signal)=>{
       console.log(`Worker process ${worker.process.pid} died`);
    });
} else {
    console.log(`Worker process ${process.pid} started running`);
      
    const port=2323;
    app.listen(port,(req,res)=>{
      console.log(`server running at port ${port}`);
    });
}


Output:

Master process 2836 is running
Worker process 6272 started running
Worker process 13128 started running
Worker process 13480 started running
server running at port 2323
server running at port 2323
server running at port 2323
Worker process 11172 started running
server running at port 2323

Explanation: In the above demonstration, when the app runs, first we are checking if the process is master process using cluster.isMaster. If the process is master, we will then spawn several worker processes using cluster.fork() method. Worker and Process Id’s are logged to the console.

Below are some of the cluster properties and methods-

  • fork(): This creates a new child process from master.
  • isMaster: This returns true if current process is master or else false.
  • isWorker: This returns true if current process is worker or else false.
  • process : This returns the child process which is global.
  • send(): This sends a message from worker to master or vice versa.
  • kill(): This is use to kill the current worker.
  • isDead: This returns true if current worker is dead or else false.
  • id: This is a unique id for worker.
  • settings: This returns an object containing cluster settings.
  • worker: This returns the current worker process.
  • workers: This returns all the workers of a process.
  • isConnected: This returns true if a current worker is connected to its master or else false.
  • disconnect(): This is to disconnect all workers.

This was all about cluster modules, their uses, implementation, and various properties. 


Similar Reads

Difference between Cluster module and load balancer
Load balancing distributes the workload amongst multiple servers to improve the performances meanwhile server clustering, combines multiple servers to work as a single entity. Cluster module or Clustering: A cluster is a group of resources that attempts to achieve a common objective, and have awareness of one another within the group. Each containe
4 min read
How to export promises from one module to another module node.js ?
JavaScript is an asynchronous single-threaded programming language. Asynchronous means multiple processes are handled at the same time. Callback functions vary for the asynchronous nature of the JavaScript language. A callback is a function that is called when a task is completed, thus helps in preventing any kind of blocking and a callback functio
1 min read
What are the differences between HTTP module and Express.js module ?
HTTP and Express both are used in NodeJS for development. In this article, we'll go through HTTP and express modules separately HTTP: It is an in-build module which is pre-installed along with NodeJS. It is used to create server and set up connections. Using this connection, data sending and receiving can be done as long as connections use a hypert
2 min read
How to allow classes defined in a module that can be accessible outside of the module ?
The TypeScript scripts written by default are in the global scope which means that all the functions, methods, variables, etc. in one file are accessible in all other TypeScript files. This can lead to conflicts in variables, functions as programmers can edit the function/variable name or value without any realization. Therefore, the concept of mod
3 min read
How to allow classes defined in a module to be accessible outside of a module ?
In typescript by using an import statement, a module can be utilized in another module. any variables, classes, methods, or other objects declared in a module are not accessible outside of it. The keyword "export" may be used to construct a module, and the term "import" can be used to import it into another module. Let's demonstrate how to do this.
3 min read
How do you import a module into another module Angular?
Angular applications are modular by design, allowing you to break down complex functionalities into smaller, manageable pieces called modules. One common task in Angular development is importing modules into other modules to make their components, directives, pipes, and services available throughout the application. This article explores the proces
4 min read
How to Work with 'word-count' Module in Node.js ?
The 'work-count' module is a simple and lightweight external NPM module that can count the number of words in a string. This module provides a count() function, which counts the number of words by ignoring any special characters or symbols in the string. Installation: First, we have to install the module using the command given below. Open the term
2 min read
How to work Mongojs module in Node.js ?
Mongojs module is a built-in module in node.js that facilitates the usage of MongoDB with Node.js. It offers almost all the functionality that is provided by the official API of MongoDB and is used extensively by developers across the globe. Follow the steps mentioned below to install mongojs module and get it up and running. Project Setup and Modu
3 min read
How to set up Kubernetes cluster on local machine using minikube ?
Creating a Kubernetes cluster on AWS, Google Cloud, etc, can be a little difficult and cost you a pretty decent amount of money. If you have a Windows machine or a mac then it is easy to create a multi-container cluster using Docker Desktop for windows/mac and use Kubernetes to manage the cluster. Perquisites: Have some basic knowledge of Docker an
3 min read
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: Failing to properly release
3 min read
Article Tags :
three90RightbarBannerImg