ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Node.js Tutorial• 8 min read

EventEmitter & Multiprocessing with Cluster

Building decoupled architectures and taking full advantage of multi-core CPUs

Node.js is single-threaded per process. To maximize throughput on modern servers with 16, 32, or 64 CPU cores, Node includes the cluster module to fork worker processes that share the same server port.

EventEmitter and Cluster Scaling

EventEmitter: A publisher/subscriber pattern class in node:events allowing objects to emit named events that trigger registered listener functions.

cluster.isPrimary: Designates the master process responsible for spawning and monitoring worker processes with cluster.fork().

Zero-downtime restarts: If a child worker crashes due to an unhandled exception, the primary process can immediately spawn a replacement.

Multi-Core Server with Node Cluster
import cluster from 'node:cluster';
import http from 'node:http';
import { availableParallelism } from 'node:os';

const numCPUs = availableParallelism();

if (cluster.isPrimary) {
  console.log(`Primary Master ${process.pid} is running. Forking ${numCPUs} workers...`);

  // Fork workers matching hardware CPU core count
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.warn(`Worker ${worker.process.pid} died. Forking replacement...`);
    cluster.fork();
  });
} else {
  // Workers share the TCP connection on port 8000
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Handled by worker process ID: ${process.pid}\n`);
  }).listen(8000);

  console.log(`Worker ${process.pid} listening on port 8000`);
}
The cluster module distributes incoming TCP connections across all available CPU cores.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What method spawns a new worker process in Node.js cluster module?