Performance: How cluster module works
This affects how Node.js handles multiple CPU cores to improve server throughput and responsiveness.
Jump into concepts and practice - no test required
import cluster from 'node:cluster'; import http from 'http'; import os from 'node:os'; if (cluster.isPrimary) { const cpus = os.cpus().length; for (let i = 0; i < cpus; i++) { cluster.fork(); } } else { http.createServer((req, res) => { // heavy synchronous task for (let i = 0; i < 1e9; i++) {} res.end('Done'); }).listen(3000); }
import http from 'http'; const server = http.createServer((req, res) => { // heavy synchronous task for (let i = 0; i < 1e9; i++) {} res.end('Done'); }); server.listen(3000);
| Pattern | CPU Utilization | Event Loop Blocking | Request Throughput | Verdict |
|---|---|---|---|---|
| Single process server | Uses 1 core | High under load | Low | [X] Bad |
| Cluster with multiple workers | Uses all cores | Low per process | High | [OK] Good |
cluster module in Node.js?cluster.isPrimary replaces cluster.isMaster.cluster.isPrimary correctly checks if the process is the primary (master) process.const cluster = require('cluster');
const http = require('http');
if (cluster.isPrimary) {
cluster.fork();
cluster.fork();
} else {
http.createServer((req, res) => {
res.end('Worker ' + process.pid);
}).listen(8000);
}http://localhost:8000 multiple times?const cluster = require('cluster');
if (cluster.isPrimary) {
cluster.fork();
} else {
console.log('Worker running');
}