Because a single Node.js instance utilizes only one CPU core, hosting an unclustered server on a multi-core cloud VM (AWS EC2, Google Cloud, DigitalOcean) wastes computing power. The built-in cluster module enables you to spawn a cluster of worker processes that all share the same network port.
// clusterServer.js
const cluster = require('cluster');
const http = require('http');
const os = require('os');
// Detect total logical CPU cores on machine
const numCPUs = os.cpus().length;
if (cluster.isPrimary) {
console.log(`[PRIMARY MASTER PROCESS ${process.pid}] is running`);
console.log(`Forking cluster across ${numCPUs} available CPU cores...\n`);
// Fork a worker process for each CPU core
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
// Auto-healing: If a worker process crashes, spawn an immediate replacement!
cluster.on('exit', (worker, code, signal) => {
console.error(`[WORKER DIED] Worker process ${worker.process.pid} died. Starting replacement...`);
cluster.fork();
});
} else {
// WORKER PROCESSES - Run HTTP Web Server
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
message: 'Hello from Clustered Node Server!',
handledByWorkerPid: process.pid
}));
}).listen(3000, () => {
console.log(` -> Worker ${process.pid} listening on shared port 3000`);
});
}
When you execute node clusterServer.js on an 8-core computer, you see 8 independent workers launch. If you send 10 HTTP requests, the Master distributes incoming requests across the worker PIDs via round-robin, maximizing throughput.
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Compare multi-processing with multi-threading.
PM2 automates cluster management in production.
Cluster seamlessly shares a single HTTP port.