Forking workers per CPU core helps your Node.js app use all the computer's power. It makes your app faster and can handle more users at the same time.
Forking workers per CPU core in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
import cluster from 'cluster'; import os from 'os'; if (cluster.isPrimary) { const cpuCount = os.cpus().length; for (let i = 0; i < cpuCount; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died. Restarting...`); cluster.fork(); }); } else { // Worker code here, e.g., start server }
cluster.isPrimary checks if the current process is the main one that controls workers.
cluster.fork() creates a new worker process.
import cluster from 'cluster'; import os from 'os'; if (cluster.isPrimary) { const cpuCount = os.cpus().length; for (let i = 0; i < cpuCount; i++) { cluster.fork(); } } else { console.log(`Worker ${process.pid} started`); }
import cluster from 'cluster'; import os from 'os'; import http from 'http'; if (cluster.isPrimary) { const cpuCount = os.cpus().length; for (let i = 0; i < cpuCount; i++) { cluster.fork(); } } else { http.createServer((req, res) => { res.writeHead(200); res.end(`Handled by worker ${process.pid}`); }).listen(8000); }
This program uses the cluster module to fork one worker per CPU core. The primary process logs its start and forks workers. Each worker runs an HTTP server that responds with its process ID. If a worker dies, the primary process restarts it automatically.
import cluster from 'cluster'; import os from 'os'; import http from 'http'; if (cluster.isPrimary) { const cpuCount = os.cpus().length; console.log(`Primary process ${process.pid} is running`); console.log(`Forking ${cpuCount} workers`); for (let i = 0; i < cpuCount; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { 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}`); }).listen(8000); console.log(`Worker ${process.pid} started and listening on port 8000`); }
Each worker is a separate process, so they do not share memory directly.
Use cluster to improve performance on multi-core machines.
Restarting workers on exit helps keep your app reliable.
Forking workers lets your app use all CPU cores.
The primary process controls workers and restarts them if needed.
Workers can run servers or other tasks in parallel.
Practice
Solution
Step 1: Understand CPU cores and parallelism
Each CPU core can run one process at a time, so using all cores means better performance.Step 2: Role of forking workers
Forking workers equal to CPU cores lets Node.js run multiple tasks simultaneously, improving speed.Final Answer:
To use all CPU cores and improve performance by running tasks in parallel -> Option BQuick Check:
Fork workers = use all cores = better performance [OK]
- Thinking forking reduces memory usage
- Believing forking slows the app
- Confusing cluster module usage
Solution
Step 1: Check Node.js os module usage
The os module has a method cpus() that returns an array of CPU core info.Step 2: Correct syntax to get core count
Using cpus().length gives the number of CPU cores available.Final Answer:
const cores = require('os').cpus().length; -> Option AQuick Check:
os.cpus() returns array, length gives core count [OK]
- Forgetting parentheses after cpus
- Using non-existent cpuCount method
- Trying to get cores from cluster module
const cluster = require('cluster');
const os = require('os');
if (cluster.isPrimary) {
const numCPUs = os.cpus().length;
console.log(`Primary process is running`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
console.log(`Worker ${process.pid} started`);
}Solution
Step 1: Identify primary and worker behavior
The primary logs once and forks 4 workers (one per CPU core).Step 2: Each worker logs its own process id
Each worker logs "Worker [pid] started" with its unique process id.Final Answer:
Primary process is running Worker 1234 started Worker 1235 started Worker 1236 started Worker 1237 started -> Option AQuick Check:
Primary logs once, 4 workers log with pids [OK]
- Assuming workers log without pid
- Thinking only one worker starts
- Confusing primary and worker logs
const cluster = require('cluster');
const os = require('os');
if (cluster.isPrimary) {
const numCPUs = os.cpus.length;
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
console.log('Worker started');
}Solution
Step 1: Check os module usage
os.cpus is a function, so os.cpus.length is undefined and causes error.Step 2: Correct usage
Use os.cpus().length to get the number of CPU cores correctly.Final Answer:
os.cpus.length is undefined; should be os.cpus().length -> Option DQuick Check:
os.cpus() is function, need parentheses [OK]
- Forgetting parentheses on os.cpus()
- Assuming cluster.fork() is missing
- Thinking else block is required for syntax
Solution
Step 1: Fork one worker per CPU core in primary process
In if (cluster.isPrimary), use const numCPUs = os.cpus().length; for (let i = 0; i < numCPUs; i++) cluster.fork();Step 2: Restart workers on exit event
In primary process, cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} died, restarting...`); cluster.fork(); });Step 3: Worker creates HTTP server
Workers create the HTTP server listening on port 8000, responding with their pid.Final Answer:
forks one worker per CPU core and restarts any worker if it crashes -> Option CQuick Check:
Primary forks os.cpus().length + cluster.on('exit', fork()) + workers create HTTP server [OK]
- Using cluster.isWorker instead of cluster.isPrimary
- Not restarting workers on exit
- Forking workers inside worker process
