Performance: Cluster vs reverse proxy decision
This affects how efficiently a Node.js server handles multiple requests and scales across CPU cores, impacting server response time and throughput.
Jump into concepts and practice - no test required
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 ' + process.pid); }).listen(3000); }
const http = require('http'); http.createServer((req, res) => { // single-threaded server res.end('Hello World'); }).listen(3000);
| Pattern | CPU Utilization | Request Throughput | Response Latency | Verdict |
|---|---|---|---|---|
| Single-threaded Node.js server | Low (1 core) | Low under load | High latency under concurrency | [X] Bad |
| Node.js cluster with multiple workers | High (all cores) | High throughput | Low latency | [OK] Good |
| Direct client connection without proxy | Single server bottleneck | Limited | Potentially high | [X] Bad |
| Reverse proxy load balancing multiple servers | Distributed | High throughput | Low latency | [OK] Good |
cluster in a Node.js application?require('cluster') and workers are created with cluster.fork().proxy module by default, http.listenCluster() and cluster.createServer() are invalid methods.const cluster = require('cluster');
cluster.fork();
require('http').createServer((req, res) => res.end('Hello')).listen(3000);
What is the likely cause?cluster.fork() without checking if (cluster.isMaster). Both master and worker processes fork additional processes and attempt to bind to port 3000, causing port conflicts (EADDRINUSE) and crashes.if (cluster.isMaster) check before forking leads to repeated forking and server creation attempts, causing the crash.