Node.js Cluster Module — Scale to Multiple Cores

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Node.js is single-threaded. Clustering uses all CPU cores for scalability.

Clustering

import cluster from "cluster";
import os from "os";
import app from "./app";

if (cluster.isPrimary) {
  const numCPUs = os.cpus().length;

  // Fork workers
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on("exit", (worker) => {
    console.log(`Worker ${worker.process.pid} exited`);
    cluster.fork(); // Restart dead worker
  });
} else {
  // Worker process
  app.listen(3000, () => {
    console.log(`Worker ${process.pid} listening`);
  });
}

With Load Balancer

// nginx.conf
upstream api {
  server localhost:3000;
  server localhost:3001;
  server localhost:3002;
}

server {
  listen 8000;
  location / {
    proxy_pass http://api;
  }
}

FAQ

Q: Cluster vs Worker Threads? A: Cluster for I/O-bound (APIs). Workers for CPU-bound.


Clustering is essential for production Node.js scalability.

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro