Typorithm · medium

Cluster

node-clusternodejsclusterscalingmulti-core
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Cluster

0%

Concurrency

The cluster module forks one process per CPU core, all sharing the same server port — the OS round-robin load-balances connections across them. cluster.isPrimary runs the spawning logic; workers run the server. It scales a single-threaded Node server across all cores.

Node runs your JavaScript on one thread, so a single process only uses one CPU core. The cluster module fixes this by forking one worker process per core, multiplying throughput on a multi-core machine.

The same file runs in every process, branching on cluster.isPrimary: the primary loops over the core count calling cluster.fork() to spawn workers, while each worker creates the HTTP server. All workers listen on the same port, and the OS (round-robin on most platforms) spreads incoming connections across them.

Cluster is about horizontal scaling of a stateless server, not shared computation. Each worker is a separate process with its own memory, so any shared state must live in an external store like Redis rather than in process variables.

01

cluster.fork() spawns one worker process per CPU core.

02

All workers share the port; the OS load-balances connections.

03

cluster.isPrimary vs worker decides which branch runs.

import cluster from "node:cluster";
import http from "node:http";
import { cpus } from "node:os";

if (cluster.isPrimary) {
  for (let i = 0; i < cpus().length; i++) cluster.fork();
} else {
  http.createServer((req, res) => res.end("handled by " + process.pid)).listen(3000);
}

Read the implementation

Connect each part of the code to the concept before you type.

1. The cluster module

The cluster module forks the current process into multiple workers that share server ports.

import cluster from "node:cluster";

2. Primary branch

cluster.isPrimary is true only in the original process, which is responsible for spawning workers.

if (cluster.isPrimary) {

3. One worker per core

cluster.fork() spawns a worker process; forking once per CPU core uses every core of the machine.

for (let i = 0; i < cpus().length; i++) cluster.fork();

4. Shared port

Every worker listens on the same port 3000; the OS load-balances incoming connections across them.

http.createServer((req, res) => res.end("handled by " + process.pid)).listen(3000);

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Cluster: Lesson & Practice · Typorithm | ApplyDjinn