tezvyn:

Purpose of the Node.js cluster module

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

Knowing Node is single-threaded per process and how to use all cores.

OUTLINE

cluster forks worker processes sharing one listening port, so requests spread across CPU cores via the OS, raising throughput and adding resilience.

WHY IT EXISTS: A Node.js process executes your JavaScript on a single event-loop thread, so by default one process saturates only one CPU core. On a multi-core server most of the hardware would sit idle. The cluster module exists to run multiple Node processes that cooperate to serve traffic, using all cores.

THE MENTAL MODEL: Think of one primary (master) process that forks several worker processes, each a full Node instance with its own memory and event loop. The workers share a single server port: the primary creates the listening socket and the operating system, or Node's distribution, hands incoming connections to workers. It is multi-process parallelism, not multi-threading, so workers do not share memory and must communicate via messages.

HOW IT WORKS: The primary calls cluster.fork once per core, typically based on os.cpus().length. Each worker calls listen on the same port; under the hood the primary owns the socket and distributes connections (round-robin on most platforms). Because each connection is handled entirely within one worker's event loop, throughput scales roughly with core count for IO-bound workloads. The primary can listen for worker exit events and fork a replacement, adding fault tolerance.

WHEN IT MATTERS: Use cluster (or a process manager like PM2 that wraps it) for IO-bound HTTP servers that need to use all cores and survive worker crashes. It does not speed up a single CPU-bound request; for that you need worker_threads. State that must be shared across workers (sessions, caches) belongs in an external store like Redis, since memory is not shared.

ONE CONCRETE EXAMPLE: On an 8-core box, the primary forks 8 workers all listening on port 3000. Eight concurrent requests can be handled in parallel across cores instead of queueing behind one event loop, roughly multiplying throughput, and if one worker crashes the primary forks a fresh one so the server keeps serving.

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.