What are Worker Threads in Node.js?
Learn how Node.js worker threads run CPU-heavy work in parallel without blocking the event loop, how they pass messages, share memory, and differ from cluster.
Expected Interview Answer
Worker threads let Node.js run JavaScript in parallel on multiple threads within a single process, so CPU-intensive work can happen off the main thread without blocking the event loop.
The worker_threads module spawns real OS threads, each with its own V8 isolate and event loop, that run inside the same process as the main thread. Threads communicate by passing messages through a MessagePort, and unlike separate processes they can share raw memory via SharedArrayBuffer and hand off large buffers with zero-copy transfer. Worker threads are meant for CPU-bound tasks like image processing, encryption, or heavy computation — I/O-bound work is already handled efficiently by the asynchronous event loop and does not need them.
- Runs CPU-heavy work without blocking the event loop
- True parallelism within one process
- Can share memory via SharedArrayBuffer
- Lower overhead than spawning full processes
- Zero-copy transfer of large buffers between threads
AI Mentor Explanation
During a long innings the main batter shouldn't also mark the scorebook — it slows the game. A dedicated scorer works in parallel and passes updates back. Worker threads are that scorer: the main thread keeps facing deliveries while a worker handles heavy tallying alongside it and reports results through messages.
Step-by-Step Explanation
Step 1
Import worker_threads
Require Worker, isMainThread, parentPort and workerData from node:worker_threads.
Step 2
Create a worker
In the main thread, new Worker('./worker.js', { workerData }) spawns a thread running that script.
Step 3
Send input
Pass data via workerData at creation or worker.postMessage() during its lifetime.
Step 4
Do CPU work in the worker
The worker script runs the heavy computation off the main event loop, using its own isolate.
Step 5
Return results
The worker uses parentPort.postMessage(result); the main thread listens on worker.on('message').
Step 6
Clean up
Handle 'error' and 'exit' events, and terminate or pool workers to avoid unbounded thread creation.
What Interviewer Expects
- Knows worker_threads gives true parallelism inside one process
- Explains message passing via MessagePort/postMessage
- Understands they suit CPU-bound, not I/O-bound, work
- Aware of SharedArrayBuffer and transferable buffers
- Can contrast worker_threads with the cluster module
- Mentions worker pools to limit overhead
Common Mistakes
- Using worker threads for I/O-bound work the event loop already handles
- Assuming threads share all variables by default (they don't, except SharedArrayBuffer)
- Creating a new worker per task instead of pooling
- Confusing worker_threads (threads) with cluster (processes)
- Forgetting to handle worker error and exit events
Best Answer (HR Friendly)
“Worker threads let a Node.js app do heavy calculations on separate threads so the main program stays responsive. They are useful for tasks like processing images or big computations, where doing the work directly would otherwise freeze the app.”
Code Example
// main.js
const { Worker } = require('node:worker_threads');
function runHeavyTask(input) {
return new Promise((resolve, reject) => {
const worker = new Worker('./worker.js', { workerData: input });
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0) reject(new Error(`Worker stopped with code ${code}`));
});
});
}
runHeavyTask(42).then((result) => {
console.log('Result:', result); // main thread never blocked
});
// worker.js
const { workerData, parentPort } = require('node:worker_threads');
let sum = 0;
for (let i = 0; i < 1e9; i++) sum += i % workerData;
parentPort.postMessage(sum);Follow-up Questions
- When would you choose worker threads over the cluster module?
- How do worker threads communicate and share memory?
- Why are worker threads not recommended for I/O-bound tasks?
- What is a worker pool and why use one?
- What is the difference between transferring and cloning data between threads?
MCQ Practice
1. What kind of workload are worker threads best suited for?
Worker threads offload CPU-intensive work; async I/O is already handled efficiently by the event loop.
2. How do worker threads primarily communicate with the main thread?
Threads exchange data through MessagePorts using postMessage; memory is not shared unless using SharedArrayBuffer.
3. What is a key difference between worker_threads and the cluster module?
worker_threads create threads within a single process that can share memory; cluster forks separate processes with isolated memory.
Flash Cards
What are worker threads in Node.js? — Real threads within one process that run JavaScript in parallel, keeping CPU work off the main event loop.
When should you use worker threads? — For CPU-bound work (encryption, image processing, heavy math) — not for I/O the event loop already handles.
How do worker threads share memory? — Via SharedArrayBuffer, or transfer buffers zero-copy; otherwise they pass copies through postMessage.
worker_threads vs cluster? — worker_threads = threads in one process (can share memory); cluster = separate processes with isolated memory.