Scaling across cores with cluster and os
scaling single-threaded Node across cores.
os.cpus gives core count, the primary forks one worker per core, all workers share the listening port, the OS load-balances connections.
thinking one Node process uses all cores.
WHAT THIS TESTS This assesses whether you understand that JavaScript execution in Node is single-threaded, so one process pins to one core for CPU work, and how the cluster module spreads load across all cores.
A GOOD ANSWER COVERS You determine the number of logical cores with os.cpus().length. In your entry file you check cluster.isPrimary; if true, you loop that many times calling cluster.fork, which spawns a worker process running the same script. Each worker is a full, independent Node process with its own event loop and memory. When workers call listen on the same port, the cluster module shares the underlying server handle so the operating system or the primary distributes incoming connections among them, letting all cores serve traffic in parallel. The primary process does not handle requests itself; its job is supervision: spawning workers, listening for exit events, and forking replacements when a worker dies, giving you resilience and full CPU utilization.
COMMON WRONG ANSWERS Believing a single Node process already uses all cores for JavaScript. Sharing mutable state directly between workers, forgetting they are separate processes that communicate only via messages. Using cluster for I/O-bound apps where the event loop already handles concurrency well and the extra processes add little.
LIKELY FOLLOW-UPS How do workers share session state without shared memory. When would you prefer worker_threads over cluster. How does this compare to running multiple processes behind a load balancer like PM2.
ONE CONCRETE EXAMPLE On an 8-core box, the primary forks 8 workers each binding port 3000. A CPU-heavy hashing endpoint that saturated one core at full load now runs across 8 cores, roughly multiplying throughput, and if a worker crashes the primary's exit listener forks a fresh one so capacity is restored automatically.
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.