DEV Community

Edrick Ee
Edrick Ee

Posted on

Adding cluster in my index.js

Adding cluster inside index is easy

  1. Cluster is already in implemented in your system

  2. const cluster = require('cluster');

  3. const totalCPUs = require('os').cpu().length;

  4. 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`);

}

Enter fullscreen mode Exit fullscreen mode

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)