AceDevHub
Advanced Node.js Interview QuestionsAdvancedConcept

Node.js · Question 68

What is the difference between worker threads and cluster in Node.js?

Direct answer

Cluster forks multiple Node processes sharing the same server port for CPU parallelism on I/O-bound HTTP; worker_threads run JavaScript in threads within one process for CPU-heavy tasks — cluster scales connections, workers scale compute without full process overhead.

Node's default single main thread handles the event loop — cluster and worker_threads are the two main ways to use multiple cores without blocking request handling.

Why interviewers ask

Aspectcluster moduleworker_threads
UnitSeparate OS processesThreads in one process
MemoryIsolated heap per workerShared process, message passing
Best forHTTP server throughputCPU-bound JS (hashing, parsing, ML)
Port sharingPrimary distributes to workersN/A — not for HTTP listen directly
Crash isolationOne worker dies, others continueThread error can affect process
  • When cluster — multi-core API server behind load balancer or cluster.fork on bare metal.
  • When worker_threads — image resize, bcrypt rounds, large JSON transform off main loop.
  • Not for I/O — extra threads don't speed async pg/redis; event loop already non-blocking.
cluster-vs-worker.mjs
import cluster from "node:cluster";
import { availableParallelism } from "node:os";

if (cluster.isPrimary) {
  for (let i = 0; i < availableParallelism(); i++) cluster.fork();
} else {
  // Each worker runs full Fastify app on shared port
  startServer({ port: 4000 });
}

// CPU task: offload to worker_threads, not cluster