Lesson 19 / 30

CPU-Bound Work & Worker Threads

Keep the event loop responsive by moving CPU-heavy work to worker threads, and know when to scale with clusters or processes.

Blocking the event loop

Non-blocking I/O is fast, but a long synchronous computation (image resizing, hashing, big JSON parsing) blocks every other request. CPU-bound work belongs off the main thread.

Worker threads

worker_threads runs a script in a separate thread and exchanges messages with it.

// main.js
import { Worker } from "node:worker_threads";

const worker = new Worker(new URL("./heavy.js", import.meta.url), { workerData: 40 });
worker.on("message", (result) => console.log("fib:", result));
worker.on("error", console.error);

// heavy.js
import { parentPort, workerData } from "node:worker_threads";
const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
parentPort.postMessage(fib(workerData));

Use workers for CPU-bound jobs, not for I/O, which is already async. For multi-core scaling of a server, run several processes (cluster or a process manager) behind a load balancer.