Performance: How cluster module works
MEDIUM IMPACT
This affects how Node.js handles multiple CPU cores to improve server throughput and responsiveness.
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 |