tezvyn:

Offloading CPU-bound work with Worker Threads

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

knowing the single thread blocks on CPU work.

OUTLINE

synchronous CPU work freezes the loop and all requests; offload to a Worker, communicate via messages or SharedArrayBuffer, use a pool.

RED FLAG

suggesting async I/O fixes CPU blocking.

WHAT THIS TESTS The question separates candidates who understand that Node's asynchrony only helps I/O from those who think wrapping work in a Promise magically parallelizes it. CPU-bound code blocks the one JavaScript thread regardless of async syntax.

A GOOD ANSWER COVERS Node runs your JavaScript on a single thread. A tight CPU loop, such as hashing, image resizing, or large JSON crunching, monopolizes that thread, so the event loop never advances to other phases. Every other in-flight request, timer, and I/O callback is frozen until the computation returns, which destroys throughput and latency. The correct fix is to move the work to a Worker Thread, which has its own V8 instance and event loop. The main thread posts input data with postMessage, the worker computes, and it posts results back. For shared numeric buffers you can use SharedArrayBuffer to avoid copying. In production you maintain a worker pool so spawning cost is amortized and concurrency is bounded.

COMMON WRONG ANSWERS Claiming async/await or wrapping the function in a Promise solves it, since neither yields the thread during synchronous computation. Suggesting the cluster module as the primary tool when the real need is sharing a result for one request, or spawning an unbounded worker per request, which exhausts memory.

LIKELY FOLLOW-UPS Worker pool sizing relative to CPU cores, the cost of structured cloning large payloads, when to prefer a separate microservice or child_process, and how SharedArrayBuffer plus Atomics avoids copies.

ONE CONCRETE EXAMPLE An endpoint generates a PDF that takes two seconds of pure CPU. Inline, those two seconds block all other users. Instead, a pool of four workers each handle one PDF job; the handler posts the document spec to an idle worker, awaits the result message, and responds. The main loop stays free to accept and route other requests throughout.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.