CodePark/ questions / Workers, cluster & child processes
START PRACTICINGPRACTICE
Backend question · Node.js › Workers, cluster & child processes

Compare worker_threads, cluster and child_process. When would you use each?

Use worker_threads for CPU-heavy work, cluster to spread an HTTP server across CPU cores, and child_process to run other programs.

worker_threads run JavaScript in extra threads inside the same process. Each worker has its own V8 isolate (a separate JavaScript engine instance with its own memory) and its own event loop. Workers talk to the main thread with postMessage. They can also share memory through a SharedArrayBuffer. Use them for CPU-heavy work such as image processing, parsing or hashing. This keeps the main event loop free to answer requests.

cluster starts (forks) several copies of the same Node process. The copies share one listening port, and the primary process hands out the connections. This spreads an HTTP server across CPU cores. In containers, teams often replace it: they run one process per container and add more container replicas.

child_process starts any program as a separate OS process, Node or not. Examples are running ffmpeg, git or a shell script. fork is the special case for another Node script. It adds an IPC channel (inter-process communication: a way for the two processes to send messages). Processes are fully isolated from each other. But they cost more memory and take longer to start than threads.

  • Workers are threads in one process, each with its own isolate and event loop, used for CPU-heavy work.
  • Workers send messages with postMessage and can share memory through SharedArrayBuffer.
  • Cluster runs several processes that share one port, which spreads a server across CPU cores.
  • child_process runs external programs, and fork starts a Node script with an IPC channel.
  • Processes are better isolated than threads, but they cost more memory and start more slowly.