Bird
Raised Fist0
Node.jsframework~10 mins

Master and worker processes in Node.js - Step-by-Step Execution

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 - Master and worker processes
Start Master Process
Fork Worker Processes
Master Listens for Messages
Workers Run Tasks
Workers Send Results to Master
Master Aggregates Results
Master Handles Worker Exit
End
The master process starts and creates worker processes. Workers run tasks and send results back. The master listens and manages workers until all finish.
Execution Sample
Node.js
import cluster from 'cluster';
import os from 'os';

if (cluster.isPrimary) {
  for (let i = 0; i < os.cpus().length; i++) cluster.fork();
  cluster.on('message', (worker, msg) => {
    // Master receives message
  });
  cluster.on('exit', (worker) => {
    // Master handles worker exit
  });
} else {
  process.send('worker done');
  process.exit(0);
}
This code forks one worker per CPU core. Each worker sends a message back to the master when done.
Execution Table
StepProcess TypeActionState ChangeMessage Sent/Received
1MasterCheck if masterTrue - proceed to forkNone
2MasterFork worker 1Worker 1 createdNone
3MasterFork worker 2Worker 2 createdNone
4Worker 1Run taskTask runningNone
5Worker 2Run taskTask runningNone
6Worker 1Send message to masterMessage sent'worker done'
7MasterReceive message from worker 1Message received'worker done'
8Worker 2Send message to masterMessage sent'worker done'
9MasterReceive message from worker 2Message received'worker done'
10MasterHandle worker exitWorker processes closedNone
11MasterAll workers doneMaster endsNone
💡 All workers have sent completion messages and exited; master process finishes managing workers.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 6After Step 9Final
workerCount012222
messagesReceived000122
workersAlive012220
Key Moments - 3 Insights
Why does the master process fork multiple workers instead of running tasks itself?
The master forks workers to run tasks in parallel, using multiple CPU cores. This is shown in execution_table steps 2 and 3 where workers are created.
How does the master know when a worker has finished its task?
Workers send messages back to the master (steps 6 and 8). The master listens and updates state when it receives these messages (steps 7 and 9).
What happens if a worker crashes or exits unexpectedly?
The master handles worker exit events (step 10) to clean up or restart workers if needed, ensuring the system stays stable.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does the master receive the first message from a worker?
AStep 6
BStep 8
CStep 7
DStep 9
💡 Hint
Check the 'Message Sent/Received' column for when the master receives messages.
According to variable_tracker, how many workers are alive after step 9?
A0
B2
C1
D3
💡 Hint
Look at the 'workersAlive' row and the value under 'After Step 9'.
If the master did not fork any workers, what would happen to 'messagesReceived' in variable_tracker?
AIt would stay at 0
BIt would increase to 2
CIt would become negative
DIt would be undefined
💡 Hint
Without workers, no messages can be sent or received; check initial values in variable_tracker.
Concept Snapshot
Master process controls worker processes.
Master forks workers to run tasks in parallel.
Workers send messages back to master.
Master listens and manages worker lifecycle.
Useful for using multiple CPU cores efficiently.
Full Transcript
In Node.js, the master process starts and forks multiple worker processes, usually one per CPU core. Each worker runs its own task independently. When a worker finishes, it sends a message back to the master process. The master listens for these messages to know when workers complete their tasks. It also handles worker exits to keep the system stable. This setup allows Node.js to use multiple CPU cores by running tasks in parallel across workers. The execution table shows each step: master forking workers, workers running tasks, sending messages, and master receiving them. The variable tracker shows how counts of workers and messages change over time. This helps beginners see how master and worker processes interact step-by-step.

Practice

(1/5)
1. What is the main role of the master process in Node.js cluster module?
easy
A. To create and manage worker processes
B. To handle HTTP requests directly
C. To run the application code
D. To listen on network ports

Solution

  1. Step 1: Understand the master process role

    The master process is responsible for creating and managing worker processes in the cluster module.
  2. Step 2: Differentiate master from worker tasks

    Workers run the app code and handle requests, while the master only manages them.
  3. Final Answer:

    To create and manage worker processes -> Option A
  4. Quick Check:

    Master manages workers [OK]
Hint: Master only manages workers, does not run app code [OK]
Common Mistakes:
  • Thinking master handles requests directly
  • Confusing master with worker process
  • Assuming master runs app code
2. Which of the following is the correct way to check if the current process is the master in a Node.js cluster?
easy
A. if (process.isWorker) { ... }
B. if (cluster.isWorker) { ... }
C. if (process.isMaster) { ... }
D. if (cluster.isMaster) { ... }

Solution

  1. Step 1: Recall cluster module properties

    The cluster module provides isMaster and isWorker boolean properties to identify process roles.
  2. Step 2: Identify correct syntax

    To check if current process is master, use cluster.isMaster, not process properties.
  3. Final Answer:

    if (cluster.isMaster) { ... } -> Option D
  4. Quick Check:

    Use cluster.isMaster to check master process [OK]
Hint: Use cluster.isMaster, not process properties [OK]
Common Mistakes:
  • Using process.isMaster which does not exist
  • Confusing isWorker with isMaster
  • Using wrong object for the check
3. Consider this Node.js cluster code snippet:
const cluster = require('cluster');
const http = require('http');

if (cluster.isMaster) {
  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?
medium
A. You get response 'Worker <pid>' from one of the two workers
B. You get response 'Worker <pid>' from the master process
C. The server crashes because master listens on port
D. No response because no server is created

Solution

  1. Step 1: Identify which process creates the server

    The else block runs in worker processes, which create the HTTP server listening on port 8000.
  2. Step 2: Understand request handling

    Requests are handled by one of the two worker processes forked by the master, each responding with its process ID.
  3. Final Answer:

    You get response 'Worker <pid>' from one of the two workers -> Option A
  4. Quick Check:

    Workers handle requests, master does not listen [OK]
Hint: Only workers create servers and respond [OK]
Common Mistakes:
  • Thinking master handles requests
  • Assuming master listens on port
  • Believing no server is created
4. Given this code snippet:
const cluster = require('cluster');
if (cluster.isMaster) {
  cluster.fork();
  cluster.fork();
} else {
  console.log('Worker started');
}

Why might the workers never start properly?
medium
A. Because the master process forgot to require('http')
B. Because the workers have no code to keep them alive
C. Because cluster.fork() is called inside the else block
D. Because cluster.isMaster is always false

Solution

  1. Step 1: Analyze worker code behavior

    The workers only log 'Worker started' and then exit immediately because no server or event loop keeps them alive.
  2. Step 2: Understand cluster.fork usage

    cluster.fork() is correctly called in master block, so workers start but exit quickly.
  3. Final Answer:

    Because the workers have no code to keep them alive -> Option B
  4. Quick Check:

    Workers exit if no server or event loop runs [OK]
Hint: Workers need active code (like server) to stay alive [OK]
Common Mistakes:
  • Thinking missing http require stops workers
  • Confusing cluster.fork placement
  • Assuming cluster.isMaster is always false
5. You want to create a Node.js cluster that uses all CPU cores and restarts any worker that crashes. Which approach correctly implements this?
hard
A. Create workers manually without cluster module and restart them with setInterval
B. Use cluster.fork() once and rely on master to restart automatically
C. Use cluster.fork() for each CPU core and listen to 'exit' event to fork a new worker
D. Use cluster.isWorker to fork new workers inside each worker process

Solution

  1. Step 1: Use all CPU cores with cluster.fork()

    Fork one worker per CPU core by looping over the number of CPUs.
  2. Step 2: Restart crashed workers by listening to 'exit'

    Listen to the 'exit' event on cluster to detect worker crashes and fork a new worker to replace it.
  3. Final Answer:

    Use cluster.fork() for each CPU core and listen to 'exit' event to fork a new worker -> Option C
  4. Quick Check:

    Fork per CPU + restart on exit [OK]
Hint: Fork per CPU and restart on 'exit' event [OK]
Common Mistakes:
  • Forking only once and expecting auto-restart
  • Restarting workers inside workers themselves
  • Not handling worker crashes properly