Skip to the page

How Node runs your code · senior

worker_threads vs child_process vs cluster

Use worker_threads for CPU-heavy JavaScript inside one process, child_process to run other programs or separate Node processes, and cluster (or simply more containers) to run several copies of a server across CPU cores.

The notes

What you must know

  • worker_threads: real threads, each with its own V8 instance and event loop. They talk with postMessage (data is copied by structured clone), or transfer ArrayBuffers, or share a SharedArrayBuffer with Atomics. Use a pool (e.g. Piscina), not one worker per request.
  • child_process: spawn (streams output, no shell), exec (runs a shell, buffers output, maxBuffer limit; dangerous with user input), execFile (no shell), fork (a new Node process with an IPC channel for messages).
  • cluster: the primary process forks workers that share one server port; the primary hands out connections (round-robin by default except on Windows). Each worker has its own memory, so in-memory sessions and caches are not shared.
  • In containers and Kubernetes the usual design is one Node process per container and more replicas behind a load balancer. PM2 cluster mode is common on plain VMs.
  • Workers do not make I/O faster: I/O is already non-blocking. They help only with CPU-bound JavaScript.
  • Workers and child processes cost start-up time and memory (each has its own heap), so create them once and reuse them.

The red pen

Common traps: mistake → fix

  • Mistake: Use worker threads to speed up database calls

    Fix: DB calls are I/O and already non-blocking; workers help CPU-bound JavaScript only.

  • Mistake: cluster workers share memory

    Fix: they are separate processes; share state through Redis or a database.

  • Mistake: exec('convert ' + userInput) is fine if I escape it

    Fix: use execFile or spawn with an argument array and no shell.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you use all 8 CPU cores with Node?
  2. worker_threads vs child_process vs cluster: when do you use each?
  3. How do workers share data? What is copied and what can be shared?
  4. In Kubernetes, would you still use cluster mode? Why or why not?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview