MyInternships.in

Core Modules

Node.js Cluster and Scaling

The cluster module forks the application into several processes that share one listening port, so a multi-core machine can use all its cores instead of one. In production this is usually delegated to PM2.


What is Cluster and Scaling in Node.js?

The cluster module forks the application into several processes that share one listening port, so a multi-core machine can use all its cores instead of one. In production this is usually delegated to PM2.

Cluster and Scaling example

One worker per core
JavaScript
import cluster from 'node:cluster';
import os from 'node:os';

if (cluster.isPrimary) {
  const cores = os.cpus().length;
  for (let i = 0; i < cores; i++) cluster.fork();

  cluster.on('exit', worker => {
    console.error(`Worker ${worker.process.pid} died — restarting`);
    cluster.fork();
  });
} else {
  startServer();   // each worker runs the app
}

The same thing with PM2

Terminal
pm2 start src/index.js -i max --name api
pm2 logs api
pm2 reload api        # zero-downtime restart
pm2 save && pm2 startup

Key points to remember

  • Workers share nothing — in-memory state and sessions must move to Redis or a database.
  • PM2 or a container orchestrator handles this better than hand-written cluster code.
  • It multiplies throughput; it does not make a single slow request faster.

Common mistakes with Cluster and Scaling

  • Keeping sessions or caches in process memory, so behaviour depends on which worker answers.
  • Running more workers than cores, which adds context switching for no gain.

Node.js Cluster and Scaling— Interview Questions & FAQs

How do I use all CPU cores with Node.js?+

Run one process per core, either with the cluster module or with pm2 start app.js -i max. They share the listening port and the operating system distributes connections between them.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships