Concept:

Node.js is single-threaded by default, but it supports parallelism through:

These help utilize multi-core systems, a common limitation in vanilla Node.js apps.


Real-World Use Case:

CLUSTER

You’re running an API that handles millions of HTTP requests daily. A single-threaded process can’t use all CPU cores. You spin up a cluster of worker processes to handle load in parallel.

WORKER

If you’re doing CPU-heavy operations like image processing or JSON parsing of large payloads, you delegate to a worker thread to avoid blocking the event loop.


Tough Interview Questions:

How is cluster.fork() different from child_process.fork()?

How would you share data/state between workers?


Cluster Example (Basic):

const cluster = require('cluster');
const http = require('http');
const os = require('os');

if (cluster.isPrimary) {
  const numCPUs = os.cpus().length;
  console.log(`Master ${process.pid} is running`);

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

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died`);
    // Optional: cluster.fork(); // to respawn
  });
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Handled by worker ${process.pid}`);
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}


Worker Threads Example: