Topic 010: Clustering in Node.js
We can implement clustering in Node.js using the built-in cluster
module. Clustering allows you to take advantage of multi-core systems by creating multiple instances of your application to handle incoming requests.
Here’s a basic example of how you can implement clustering in Node.js:
const cluster = require("cluster");
const http = require("http");
const numCPUs = require("os").cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers equal to the number of CPU cores
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on("exit", (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http
.createServer((req, res) => {
res.writeHead(200);
res.end("Hello World\n");
})
.listen(8000);
console.log(`Worker ${process.pid} started`);
}
In this example:
cluster.isMaster
property is used to determine if the current process is the master process.To run this code, save it to a file (e.g., cluster.js
) and run it using Node.js:
node cluster.js
This will start the master process, which will then fork worker processes. You can test it by opening multiple tabs and sending requests to http://localhost:8000
. You should see different worker process IDs handling the requests.