mediumSystem Design

What are Worker Threads in Node.js and when would you use them?

1.1k views
01

Understand the problem

This question explores understanding of Node.js's approach to CPU-bound tasks and parallelism.

worker threadsconcurrencyperformancecpu-bound
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Offload a CPU task to a worker
// main.js
import { Worker } from 'node:worker_threads';
const w = new Worker('./hash-worker.js', { workerData: bigInput });
w.on('message', (digest) => console.log('hash:', digest));

// hash-worker.js
import { parentPort, workerData } from 'node:worker_threads';
import crypto from 'node:crypto';
const digest = crypto.createHash('sha256').update(workerData).digest('hex');
parentPort.postMessage(digest);   // runs off the main thread
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.