Performance: Why worker threads matter
This concept affects how Node.js handles CPU-intensive tasks without blocking the main event loop, improving responsiveness and throughput.
Jump into concepts and practice - no test required
const http = require('http'); const { Worker } = require('worker_threads'); http.createServer((req, res) => { const worker = new Worker(` const { parentPort } = require('worker_threads'); let count = 0; for (let i = 0; i < 1e9; i++) count += i; parentPort.postMessage(count); `, { eval: true }); worker.on('message', (count) => res.end(`Count is ${count}`)); worker.on('error', (err) => { res.statusCode = 500; res.end('Worker error'); }); }).listen(3000);
const http = require('http'); http.createServer((req, res) => { // Heavy computation blocking main thread let count = 0; for (let i = 0; i < 1e9; i++) count += i; res.end(`Count is ${count}`); }).listen(3000);
| Pattern | Event Loop Blocking | CPU Utilization | Responsiveness | Verdict |
|---|---|---|---|---|
| Synchronous CPU task on main thread | Blocks event loop fully | Single core maxed | Poor, high input delay | [X] Bad |
| CPU task in worker thread | No blocking of main event loop | Multiple cores utilized | Good, low input delay | [OK] Good |
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', msg => console.log('From worker:', msg));
worker.postMessage('Hello');
} else {
parentPort.on('message', msg => {
parentPort.postMessage(msg + ' World');
});
}const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.on('message', (msg) => console.log(msg));
worker.postMessage('Start');