Performance: Forking workers per CPU core
This pattern affects server-side request handling speed and responsiveness by utilizing multiple CPU cores to handle concurrent tasks.
Jump into concepts and practice - no test required
import cluster from 'cluster'; import http from 'http'; import os from 'os'; 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('Hello World'); }).listen(8000); }
import cluster from 'cluster'; import http from 'http'; if (cluster.isMaster) { // Fork only one worker cluster.fork(); } else { http.createServer((req, res) => { res.writeHead(200); res.end('Hello World'); }).listen(8000); }
| Pattern | CPU Utilization | Request Concurrency | Response Delay | Verdict |
|---|---|---|---|---|
| Single worker process | Low (uses 1 core) | Low (serial requests) | High (requests queue) | [X] Bad |
| One worker per CPU core | High (uses all cores) | High (parallel requests) | Low (fast responses) | [OK] Good |
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`);
}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');
}