WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Node.js · Advanced · question 46 of 100

Explain the differences between ’worker_threads’ and ’cluster’ modules in Node.js for handling concurrency.?

📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

The ‘worker_threads‘ and ‘cluster‘ modules in Node.js are used for handling concurrency and improving the performance of the applications. However, they differ significantly in their approaches and use-cases.

1. **‘worker_threads‘**:

‘worker_threads‘ module was introduced in Node.js v10.5.0, and it is designed to help Node.js applications perform CPU-bound tasks more effectively. Each ‘Worker‘ thread runs in parallel and shares the same memory as the parent, which allows for efficient data exchange, making it ideal for computationally intensive tasks.

const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');

if (isMainThread) {
  // Main thread
  const worker = new Worker(__filename, {
    workerData: { someData: 'example' },
  });

  worker.on('message', (result) => {
    // Receive results from worker thread
    console.log(result);
  });

  worker.on('error', (err) => {
    // Handle errors
    console.error(err);
  });

  worker.on('exit', (code) => {
    // Worker exited
    console.log(`Worker exited with code: ${code}`);
  });
} else {
  // Worker thread
  const { someData } = workerData;
  // Perform CPU-bound task here
  parentPort.postMessage('Result from worker');
}

2. **‘cluster‘**:

‘cluster‘ module creates multiple processes, where each process runs an instance of your Node.js application. The processes are forked from the main process and communicate with it through IPC (Inter-Process Communication). It is more suitable for handling I/O-bound tasks and scaling applications on multi-core systems.

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Main process (master)
  console.log(`Master ${process.pid} is running`);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork(); // Fork a worker process for each CPU
  }

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

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

**Differences**:

1. **Concurrency model**: ‘worker_threads‘ uses threads for concurrency, while ‘cluster‘ uses processes.

2. **Memory sharing**: ‘worker_threads‘ share memory between the main thread and Worker threads, whereas ‘cluster‘ processes do not share memory.

3. **Use-case**: ‘worker_threads‘ is more suitable for CPU-bound tasks, while ‘cluster‘ is more suitable for I/O-bound tasks and scaling applications on multi-core systems.

4. **Communication**: ‘worker_threads‘ communicate via ‘postMessage‘ and ‘parentPort‘, while ‘cluster‘ communicates through IPC (Inter-Process Communication).

In conclusion, choose ‘worker_threads‘ for CPU-bound tasks where sharing memory efficiently is important, and ‘cluster‘ for I/O-bound tasks when scaling the application on multi-core systems is the primary goal.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Node.js interview — then scores it.
📞 Practice Node.js — free 15 min
📕 Buy this interview preparation book: 100 Node.js questions & answers — PDF + EPUB for $5

All 100 Node.js questions · All topics