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.