Adding cluster inside index is easy
Cluster is already in implemented in your system
const cluster = require('cluster');
const totalCPUs = require('os').cpu().length;
don't write app = express() until we hit else statement
if (cluster.isMaster) {
console.log(`Number of CPUs is ${totalCPUs}`);
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < totalCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
console.log("Let's fork another worker!");
cluster.fork();
});
} else {
const app = express();
console.log(`Worker ${process.pid} started`);
}
We can now write all the necessary get request & app.listen inside of else statement to run it under cluster
Here is useful link: https://blog.appsignal.com/2021/02/03/improving-node-application-performance-with-clustering.html
Top comments (0)