0
0
Node.jsframework~5 mins

When to use workers vs cluster in Node.js

Choose your learning style9 modes available
Introduction
Workers and clusters help Node.js run multiple tasks at the same time to make programs faster and more efficient.
Use workers when you want to run heavy calculations or tasks in the background without stopping the main program.
Use cluster when you want to handle many web requests at once by using multiple CPU cores.
Use workers to split a big job into smaller parts that run separately and then combine results.
Use cluster to improve the performance of a web server by creating copies of the server process.
Use workers when you need to run tasks that do not share memory but can communicate by messages.
Syntax
Node.js
const { Worker } = require('worker_threads');

const worker = new Worker('./worker.js');

worker.on('message', (msg) => {
  console.log('Message from worker:', msg);
});

worker.postMessage('start');
Workers run in separate threads and communicate by sending messages.
Clusters create multiple Node.js processes that share the same server port.
Examples
This cluster example creates one worker per CPU core to handle HTTP requests.
Node.js
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isPrimary) {
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello from worker ' + process.pid);
  }).listen(8000);
}
This worker example runs a small task that processes a message and sends back a result.
Node.js
const { Worker } = require('worker_threads');

const worker = new Worker(`
  const { parentPort } = require('worker_threads');
  parentPort.on('message', (msg) => {
    parentPort.postMessage(msg + ' processed');
  });
`, { eval: true });

worker.on('message', (msg) => console.log(msg));
worker.postMessage('data');
Sample Program
This program uses cluster to create one worker per CPU core. Each worker runs a simple HTTP server that responds with its process ID. The primary process manages workers and logs when they start or stop.
Node.js
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

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

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

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died`);
  });
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Hello from worker ${process.pid}`);
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}
OutputSuccess
Important Notes
Workers are best for CPU-heavy tasks that can run independently.
Clusters are best for scaling network servers to use all CPU cores.
Workers communicate by passing messages; clusters share server ports but run separate processes.
Summary
Workers run code in separate threads for background tasks.
Clusters run multiple processes to handle many requests.
Choose workers for heavy computation and clusters for scaling servers.