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
| Aspect | cluster module | worker_threads |
|---|---|---|
| Unit | Separate OS processes | Threads in one process |
| Memory | Isolated heap per worker | Shared process, message passing |
| Best for | HTTP server throughput | CPU-bound JS (hashing, parsing, ML) |
| Port sharing | Primary distributes to workers | N/A — not for HTTP listen directly |
| Crash isolation | One worker dies, others continue | Thread 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