Node.js is single-threaded by default, which means long-running tasks can block the event loop and degrade performance. To solve this, Node.js introduced Worker Threads, enabling multi-threading and background task processing.

What are Worker Threads?

Worker Threads allow you to run JavaScript in parallel on multiple threads. They are useful for CPU-intensive operations, large data processing, and background tasks that would otherwise block the main thread.

When to Use Worker Threads

  • CPU-bound tasks (e.g., heavy calculations, image processing)
  • Parsing large files
  • Performing concurrent non-I/O operations

Setting Up Worker Threads

You need to use the worker_threads module available in Node.js v10.5.0 and above (stable from v12).

Basic Example

main.js

const { Worker } = require('worker_threads');

const worker = new Worker('./worker.js');

worker.on('message', (msg) => {
  console.log('Message from worker:', msg);
});

worker.on('error', (err) => {
  console.error('Worker error:', err);
});

worker.on('exit', (code) => {
  if (code !== 0) console.log(`Worker stopped with exit code ${code}`);
});

worker.js

const { parentPort } = require('worker_threads');

// Simulate heavy task
let sum = 0;
for (let i = 0; i < 1e9; i++) {
  sum += i;
}

parentPort.postMessage(`Sum is ${sum}`);

Sharing Data Between Threads

Use SharedArrayBuffer or MessageChannel for shared memory or messaging:

const { Worker, MessageChannel } = require('worker_threads');

const { port1, port2 } = new MessageChannel();

const worker = new Worker('./worker.js');
worker.postMessage({ port: port2 }, [port2]);

port1.on('message', (msg) => {
  console.log('Message from worker:', msg);
});

Performance Tips

  • Avoid using Worker Threads for I/O tasks—use async I/O instead.
  • Use a worker pool for handling multiple tasks.
  • Offload only CPU-heavy operations to keep the main thread responsive.

Conclusion

Worker Threads provide a powerful way to scale Node.js applications by leveraging multi-threading for intensive tasks. Understanding and using them properly can significantly improve performance without compromising the non-blocking nature of Node.js.

Have you tried using Worker Threads in your projects? Share your experience below! 🚀