WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Node.js · Intermediate · question 29 of 100

What is the role of ’cluster’ module in Node.js, and why is it used?

📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

The ‘cluster‘ module in Node.js is used to enable an application to run across multiple CPU cores on a single server, thus improving performance and resource utilization. It essentially creates multiple instances (workers) of the Node.js application, each of which can run on a separate CPU core. This allows for efficient load balancing and parallel processing of incoming requests, leading to better throughput and reducing the risk of bottlenecks.

Node.js is single-threaded by default, which means it can utilize only one CPU core at a time. While this is suitable for handling I/O-bound tasks, CPU-bound tasks can lead to performance degradation. By using the ‘cluster‘ module, the application can take advantage of all available CPU cores and handle a larger number of simultaneous connections.

Here’s an example of how to use the cluster module:

const cluster = require('cluster'); // Require cluster module
const http = require('http');
const numCPUs = require('os').cpus().length; // Get number of CPU cores

if (cluster.isMaster) {
  // This is the master process
  console.log(`Master process with id ${process.pid} is running`);

  // Fork a worker for each CPU core
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  // Listen for workers to be online
  cluster.on('online', (worker) => {
    console.log(`Worker ${worker.process.pid} is online`);
  });

  // Listen for workers to exit
  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} exited with code ${code} and signal ${signal}`);
    console.log('Starting a new worker');
    cluster.fork(); // Replace the dead worker
  });

} else {
  // This is a worker process
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello from worker!');
  }).listen(8000);

  console.log(`Worker process with id ${process.pid} started`);
}

In this example, the ‘cluster‘ module is used to create a simple HTTP server. First, we check if this process is the master process. If it is, we fork a worker for each CPU core available. We also listen for ’online’ and ’exit’ events to track when a worker is online or when it exits, respectively. If a worker exits, we fork a new one to ensure maximum utilization of CPU cores.

If the process is not the master, it means we are in a worker process. In this case, we create an HTTP server, which listens on port 8000. Each worker process handles incoming requests independently and runs on a separate CPU core, making efficient use of available resources.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Node.js interview — then scores it.
📞 Practice Node.js — free 15 min
📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

All 100 Node.js questions · All topics