What if your server could magically use every CPU core to handle more users without extra hassle?
Why Forking workers per CPU core in Node.js? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a Node.js server that handles many user requests at once, but it runs on a single CPU core.
When many users connect, the server slows down and some requests wait a long time.
Using just one core means your server can only do one thing at a time.
This causes delays and poor performance when traffic is high.
Trying to manage multiple tasks manually is complex and error-prone.
Forking workers per CPU core lets Node.js create multiple processes, one for each core.
Each worker handles requests independently, making full use of all CPU cores.
This improves speed and reliability without complicated manual management.
const http = require('http'); http.createServer((req, res) => { res.end('Hello World'); }).listen(8000);
const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { for (let i = 0; i < numCPUs; i++) { cluster.fork(); } } else { http.createServer((req, res) => { res.end('Hello from worker'); }).listen(8000); }
This approach enables your server to handle many requests quickly by using all CPU cores efficiently.
A busy online store uses forking workers to serve thousands of shoppers at once without slowing down during sales.
Single-core servers struggle with many requests.
Forking creates multiple workers, one per CPU core.
This improves performance and reliability easily.
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
