Worker Threads in Node.js: When and How to Use Them
Worker Threads in Node.js: When and How to Use Them Your API hashes a password. The event loop blocks. Every other request waits. Node is single-threaded, but it does not have to be. The Problem CP...

Source: DEV Community
Worker Threads in Node.js: When and How to Use Them Your API hashes a password. The event loop blocks. Every other request waits. Node is single-threaded, but it does not have to be. The Problem CPU-bound work (hashing, image processing, JSON parsing large payloads, compression) blocks the event loop. While Node processes that work, it cannot handle incoming requests, timers, or I/O callbacks. Basic Worker Thread import { Worker, isMainThread, parentPort, workerData } from "worker_threads"; if (isMainThread) { const worker = new Worker(__filename, { workerData: { input: "heavy-task" } }); worker.on("message", (result) => console.log("Result:", result)); worker.on("error", (err) => console.error("Worker error:", err)); } else { // This runs in a separate thread const result = heavyComputation(workerData.input); parentPort?.postMessage(result); } Worker Pool Creating a new worker per request is expensive. Pool them: import { Worker } from "worker_threads"; import os from "os"; clas