Performance: When to use workers vs cluster
This concept affects how Node.js handles CPU-intensive tasks and concurrent connections, impacting server responsiveness and throughput.
Jump into concepts and practice - no test required
const { Worker } = require('worker_threads');
const worker = new Worker('./heavyTask.js');
worker.on('message', result => console.log(result));const cluster = require('cluster'); if (cluster.isMaster) { for (let i = 0; i < require('os').cpus().length; i++) { cluster.fork(); } } else { // CPU-heavy task directly in worker process while(true) { /* heavy computation */ } }
| Pattern | CPU Utilization | Event Loop Blocking | Load Balancing | Verdict |
|---|---|---|---|---|
| Single process with CPU-heavy tasks | Low (1 core) | High (blocks event loop) | None | [X] Bad |
| Cluster for HTTP server scaling | High (all cores) | Low (separate processes) | Built-in | [OK] Good |
| Workers for CPU tasks | High (all cores) | None (offloads work) | N/A | [OK] Good |
| Workers used for server scaling | High (all cores) | Low | None (manual) | [!] OK |
worker_threads in Node.js instead of cluster?const cluster = require('cluster');
if (cluster.isPrimary) {
cluster.fork();
cluster.fork();
} else {
console.log('Worker process started');
}
What will be the output when you run this code?const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.on('message', (msg) => console.log(msg));
worker.postMessage('start');
What is the likely problem here?