Master and worker processes help your Node.js app use multiple CPU cores. This makes your app faster and able to handle more tasks at the same time.
Master and worker processes in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
import cluster from 'node:cluster'; import { cpus } from 'node:os'; if (cluster.isPrimary) { // Master process code const cpuCount = cpus().length; for (let i = 0; i < cpuCount; i++) { cluster.fork(); // Create worker processes } cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} died. Restarting...`); cluster.fork(); }); } else { // Worker process code // Your server or task code here }
The cluster.isPrimary property tells if the current process is the master.
Use cluster.fork() to create worker processes that run the same code.
if (cluster.isPrimary) { cluster.fork(); } else { console.log('Worker running'); }
const cpuCount = cpus().length; for (let i = 0; i < cpuCount; i++) { cluster.fork(); }
cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} died.`); cluster.fork(); });
This program uses the cluster module to create one worker per CPU core. Each worker runs a simple HTTP server that replies with its process ID. The master process manages workers and restarts any that crash.
import cluster from 'node:cluster'; import http from 'node:http'; import { cpus } from 'node:os'; if (cluster.isPrimary) { const cpuCount = cpus().length; console.log(`Master ${process.pid} is running`); for (let i = 0; i < cpuCount; i++) { cluster.fork(); } cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} died. Restarting...`); cluster.fork(); }); } else { http.createServer((req, res) => { res.writeHead(200); res.end(`Hello from worker ${process.pid}\n`); }).listen(8000); console.log(`Worker ${process.pid} started`); }
Each worker runs the same code but has its own process ID.
Workers share the same server port, so the OS balances incoming requests between them.
Use cluster to improve performance on multi-core machines.
Master process creates and manages worker processes.
Workers run the app code and handle tasks or requests.
Cluster module helps use all CPU cores for better performance.
Practice
Solution
Step 1: Understand the master process role
The master process is responsible for creating and managing worker processes in the cluster module.Step 2: Differentiate master from worker tasks
Workers run the app code and handle requests, while the master only manages them.Final Answer:
To create and manage worker processes -> Option AQuick Check:
Master manages workers [OK]
- Thinking master handles requests directly
- Confusing master with worker process
- Assuming master runs app code
Solution
Step 1: Recall cluster module properties
The cluster module provides isMaster and isWorker boolean properties to identify process roles.Step 2: Identify correct syntax
To check if current process is master, use cluster.isMaster, not process properties.Final Answer:
if (cluster.isMaster) { ... } -> Option DQuick Check:
Use cluster.isMaster to check master process [OK]
- Using process.isMaster which does not exist
- Confusing isWorker with isMaster
- Using wrong object for the check
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?Solution
Step 1: Identify which process creates the server
The else block runs in worker processes, which create the HTTP server listening on port 8000.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.Final Answer:
You get response 'Worker <pid>' from one of the two workers -> Option AQuick Check:
Workers handle requests, master does not listen [OK]
- Thinking master handles requests
- Assuming master listens on port
- Believing no server is created
const cluster = require('cluster');
if (cluster.isMaster) {
cluster.fork();
cluster.fork();
} else {
console.log('Worker started');
}Why might the workers never start properly?
Solution
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.Step 2: Understand cluster.fork usage
cluster.fork() is correctly called in master block, so workers start but exit quickly.Final Answer:
Because the workers have no code to keep them alive -> Option BQuick Check:
Workers exit if no server or event loop runs [OK]
- Thinking missing http require stops workers
- Confusing cluster.fork placement
- Assuming cluster.isMaster is always false
Solution
Step 1: Use all CPU cores with cluster.fork()
Fork one worker per CPU core by looping over the number of CPUs.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.Final Answer:
Use cluster.fork() for each CPU core and listen to 'exit' event to fork a new worker -> Option CQuick Check:
Fork per CPU + restart on exit [OK]
- Forking only once and expecting auto-restart
- Restarting workers inside workers themselves
- Not handling worker crashes properly
