Bird
Raised Fist0
Node.jsframework~10 mins

How cluster module works in Node.js - Visual Walkthrough

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - How cluster module works
Start Master Process
Fork Worker Processes
Workers Listen on Server Port
Master Distributes Incoming Requests
Workers Handle Requests Independently
If Worker Dies
Master Forks New Worker
Continue Serving
The master process starts and forks multiple worker processes. Each worker listens on the same server port. The master distributes incoming requests to workers. If a worker dies, the master replaces it.
Execution Sample
Node.js
import cluster from 'cluster';
import os from 'os';
import http from 'http';

if (cluster.isPrimary) {
  for (let i = 0; i < os.cpus().length; i++) cluster.fork();
} else {
  http.createServer((req, res) => res.end('Hello from worker')).listen(8000);
}
This code creates a master process that forks one worker per CPU core. Each worker runs an HTTP server on port 8000.
Execution Table
StepActionProcess TypeWorkers CountServer ListeningNotes
1Start scriptPrimary0NoMaster process begins
2Check if primaryPrimary0NoTrue, will fork workers
3Fork worker 1Primary1NoFirst worker created
4Fork worker 2Primary2NoSecond worker created
5Fork worker NPrimaryNNoAll workers forked (N = CPU count)
6Workers start serverWorkerNYesEach worker listens on port 8000
7Master distributes requestsPrimaryNNoIncoming requests load balanced
8Worker handles requestWorkerNYesResponds with 'Hello from worker'
9Worker crashesWorkerN-1YesOne worker dies
10Master forks new workerPrimaryNNoWorker count restored
11Continue servingPrimary & WorkersNYesServer runs continuously
💡 Server runs indefinitely until manually stopped
Variable Tracker
VariableStartAfter Fork 1After Fork 2After All ForksAfter Worker CrashAfter Replacement
cluster.isPrimarytruetruetruetruetruetrue
workers count012N (CPU count)N-1N
server listeningNoNoNoYes (in workers)YesYes
Key Moments - 3 Insights
Why do all workers listen on the same port without conflict?
The cluster module uses OS-level load balancing so multiple workers can share the same port safely, as shown in execution_table rows 6 and 7.
What happens if a worker process crashes?
The master detects the crash and forks a new worker to keep the count stable, as seen in rows 9 and 10 of the execution_table.
Is the master process handling requests directly?
No, the master only manages workers and distributes requests. Workers handle requests independently (rows 7 and 8).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step do workers start listening on the server port?
AStep 9
BStep 3
CStep 6
DStep 2
💡 Hint
Check the 'Server Listening' column in execution_table row 6
According to variable_tracker, what happens to the workers count after a worker crashes?
AIt decreases by one
BIt increases
CIt stays the same
DIt becomes zero
💡 Hint
Look at 'workers count' row in variable_tracker after 'After Worker Crash' column
If the master process did not fork new workers after a crash, what would happen to the workers count?
AIt would remain at N
BIt would decrease and not recover
CIt would increase unexpectedly
DIt would reset to zero
💡 Hint
Refer to execution_table rows 9 and 10 about worker crash and replacement
Concept Snapshot
Node.js cluster module lets a master process fork multiple worker processes.
Workers share the same server port using OS load balancing.
Master manages workers and replaces any that crash.
This improves app performance by using multiple CPU cores.
Workers handle requests independently, master only manages.
Full Transcript
The Node.js cluster module works by starting a master process that forks multiple worker processes equal to the number of CPU cores. Each worker runs an HTTP server listening on the same port. The master process distributes incoming requests across these workers using operating system load balancing. If a worker crashes, the master detects this and forks a new worker to maintain the number of active workers. This setup allows Node.js applications to handle more requests concurrently by using all CPU cores efficiently. The master process itself does not handle requests but manages the workers. Workers independently respond to requests, improving performance and reliability.

Practice

(1/5)
1. What is the main purpose of the cluster module in Node.js?
easy
A. To provide a graphical user interface for Node.js apps
B. To manage database connections efficiently
C. To handle file system operations asynchronously
D. To create multiple worker processes to use all CPU cores

Solution

  1. Step 1: Understand the cluster module role

    The cluster module allows Node.js to create multiple worker processes.
  2. Step 2: Recognize the benefit

    These workers use all CPU cores to improve performance by handling requests in parallel.
  3. Final Answer:

    To create multiple worker processes to use all CPU cores -> Option D
  4. Quick Check:

    cluster module = multiple workers for CPU cores [OK]
Hint: Cluster = multiple processes for CPU cores [OK]
Common Mistakes:
  • Confusing cluster with database or file system modules
  • Thinking cluster manages UI or frontend
  • Assuming cluster runs code in a single process
2. Which of the following is the correct way to check if the current process is the master in a cluster setup?
easy
A. if (cluster.isMaster) { ... }
B. if (cluster.isPrimary) { ... }
C. if (cluster.isWorker) { ... }
D. if (cluster.isMain) { ... }

Solution

  1. Step 1: Recall the updated property name

    In recent Node.js versions, cluster.isPrimary replaces cluster.isMaster.
  2. Step 2: Identify the correct syntax

    Using cluster.isPrimary correctly checks if the process is the primary (master) process.
  3. Final Answer:

    if (cluster.isPrimary) { ... } -> Option B
  4. Quick Check:

    Primary process check = cluster.isPrimary [OK]
Hint: Use cluster.isPrimary, not isMaster [OK]
Common Mistakes:
  • Using deprecated cluster.isMaster instead of cluster.isPrimary
  • Confusing isWorker with isPrimary
  • Using non-existent properties like isMain
3. Consider this Node.js cluster code snippet:
const cluster = require('cluster');
const http = require('http');

if (cluster.isPrimary) {
  cluster.fork();
  cluster.fork();
} else {
  http.createServer((req, res) => {
    res.end('Worker ' + process.pid);
  }).listen(8000);
}

What will happen when you visit http://localhost:8000 multiple times?
medium
A. You will see responses from different worker process IDs
B. Only one worker will handle all requests
C. The server will crash because of multiple forks
D. You will get a syntax error on startup

Solution

  1. Step 1: Understand cluster.fork creates workers

    Two workers are created, each running the HTTP server on port 8000.
  2. Step 2: Recognize load balancing behavior

    Requests are distributed between workers, so responses show different process IDs.
  3. Final Answer:

    You will see responses from different worker process IDs -> Option A
  4. Quick Check:

    Multiple workers share port, respond with different PIDs [OK]
Hint: Multiple forks = multiple workers respond differently [OK]
Common Mistakes:
  • Thinking only one worker handles all requests
  • Assuming server crashes due to multiple forks
  • Expecting syntax errors from this code
4. What is wrong with this cluster code snippet?
const cluster = require('cluster');
if (cluster.isPrimary) {
  cluster.fork();
} else {
  console.log('Worker running');
}
medium
A. cluster.isPrimary is deprecated, should use isMaster
B. No call to cluster.fork in the worker process
C. Missing server code inside worker
D. No error, code works fine

Solution

  1. Step 1: Check cluster usage

    The primary forks one worker, which only logs a message but does not start a server.
  2. Step 2: Identify missing functionality

    Without server code, the worker does not handle requests, so the cluster setup is incomplete.
  3. Final Answer:

    Missing server code inside worker -> Option C
  4. Quick Check:

    Worker must run server code to handle requests [OK]
Hint: Workers need server code to handle requests [OK]
Common Mistakes:
  • Confusing isPrimary with deprecated isMaster
  • Expecting cluster.fork in worker process
  • Assuming code runs without server in worker
5. You want to create a cluster that automatically restarts a worker if it crashes. Which approach correctly implements this behavior?
hard
A. Listen to the 'exit' event on cluster and fork a new worker inside the handler
B. Use setInterval to fork new workers every second
C. Call cluster.fork() only once at startup and never again
D. Use cluster.disconnect() inside the worker to restart itself

Solution

  1. Step 1: Understand worker crash handling

    The primary process can listen to the 'exit' event when a worker dies.
  2. Step 2: Restart worker on exit

    Inside the 'exit' event handler, calling cluster.fork() creates a new worker to replace the crashed one.
  3. Final Answer:

    Listen to the 'exit' event on cluster and fork a new worker inside the handler -> Option A
  4. Quick Check:

    Restart crashed workers by handling 'exit' event [OK]
Hint: Use 'exit' event to restart workers automatically [OK]
Common Mistakes:
  • Forking workers repeatedly with setInterval causes overload
  • Not restarting workers after crash leads to downtime
  • Using cluster.disconnect() inside worker does not restart it