Advanced Node.js Interview QuestionsAdvancedScenario
Node.js · Question 93
How would you offload a CPU-intensive task using worker threads?
Direct answer
Spawn a worker pool with worker_threads, post job data via workerData/postMessage, return result to main thread, terminate or reuse workers — keep HTTP handler async awaiting worker result without blocking the event loop.
Scenario: hash 10k passwords or parse a huge JSON export without freezing the AceDevHub API for other users (Q68–69, Q74).
- Worker file — isolate CPU logic in hash-worker.mjs.
- Pool — fixed N workers; queue jobs in main thread.
- Timeout — worker.terminate() if job exceeds SLA.
- Fallback — BullMQ job for very long tasks instead of inline worker.
scenario-worker-pool.mjs
import { Worker } from "node:worker_threads";
function runCpuJob(payload) {
return new Promise((resolve, reject) => {
const worker = new Worker("./cpu-worker.mjs", { workerData: payload });
const timer = setTimeout(() => {
worker.terminate();
reject(new Error("WORKER_TIMEOUT"));
}, 30_000);
worker.on("message", (result) => { clearTimeout(timer); resolve(result); });
worker.on("error", reject);
});
}
// Route: const hash = await runCpuJob({ password });