Open In App

How does the cluster module work ?

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:






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-

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

Article Tags :