Advertisement
Intermediate Node.js, Clustering & Worker Threads

What is the difference between the number of CPU cores and the optimal number of cluster workers for a given Node.js application?

Short answer

A common rule of thumb is one worker per CPU core, but the optimal number depends on workload -- a CPU-bound app benefits most from exactly matching cores, while a heavily I/O-bound app might benefit from slightly more workers, since extra workers can progress on other requests…

Save Node.js mock interview
Advertisement
AModel answer
A common rule of thumb is one worker per CPU core, but the optimal number depends on workload -- a CPU-bound app benefits most from exactly matching cores, while a heavily I/O-bound app might benefit from slightly more workers, since extra workers can progress on other requests while some are blocked on I/O.
const numWorkers = process.env.WORKER_COUNT || os.cpus().length;
for (let i = 0; i < numWorkers; i++) cluster.fork();
Real-world example
A CPU-intensive transcoding service settles on exactly one worker per core after benchmarks showed more workers slowed things down, while a mostly I/O-bound API performs best with roughly 1.5x the core count.
Likely follow-ups
  • How would you actually benchmark the optimal worker count for a real workload?
  • Does this intuition apply equally to worker threads used for CPU-bound tasks?
Related topics