tezvyn:

worker_threads versus cluster: when to use each

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

Matching the concurrency tool to the workload.

OUTLINE

worker_threads offloads CPU-bound compute within one process with shared-memory transfer; cluster forks processes to scale IO-bound request throughput across cores.

WHAT THIS TESTS: Whether you understand the difference between offloading CPU work and horizontally scaling request handling, and can map each Node primitive to the workload it fits.

A GOOD ANSWER COVERS: worker_threads creates additional threads inside one Node process, sharing the process and able to pass data efficiently via message passing, transferList, or SharedArrayBuffer. It is the right tool for CPU-bound tasks you want to run without blocking the main event loop, where you may also want to share memory or move large buffers cheaply. cluster forks multiple independent Node processes that each run their own event loop and memory and share a listening socket; the OS or primary distributes incoming connections among them. It is the right tool for scaling an IO-bound server to use all cores and to gain crash isolation, since one worker process dying does not take down the others. Rule of thumb: reach for worker_threads to offload computation; reach for cluster to multiply concurrent IO-bound request capacity. They can be combined. Because cluster processes do not share memory, shared state goes in an external store like Redis.

COMMON WRONG ANSWERS: Treating them as interchangeable; using cluster to speed up a single CPU-heavy computation (it does not, it just runs more processes); using worker_threads to scale HTTP throughput when the bottleneck is IO concurrency; forgetting that cluster gives process isolation while threads share a crash domain.

LIKELY FOLLOW-UPS: Why is a single worker crash riskier with threads than with cluster? How do you share data between worker_threads efficiently? Can you nest worker_threads inside cluster workers? When does a process manager like PM2 replace hand-rolled cluster?

ONE CONCRETE EXAMPLE: worker_threads fits CPU-bound work like resizing an uploaded image or computing a bcrypt/Argon2 hash, run off the main thread so requests are not blocked. cluster fits an IO-bound API serving thousands of concurrent requests across an 8-core box by forking 8 workers on one port, multiplying throughput and isolating crashes.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.