Server

Worker thread

Worker thread is a separate thread, started from the main Node.js process, that runs JavaScript in parallel with its own event loop. It keeps heavy computation from blocking the main one.

How it is measured

Measure the main thread's event loop delay before and after moving work off. Also track the worker's own CPU use, message passing time and memory, since each worker has its own V8 heap and starts in around 30 to 50 ms.

Pools are common, with a size near the core count. Transfer large buffers instead of copying them, as structured-clone copying costs time.

Worked example

An API resizes uploaded images with a pure-JS library taking 250 ms each. Run on the main thread, five concurrent uploads add 1.25 seconds of loop delay, so even /health times out. Moving resizing into a pool of 4 worker threads keeps loop delay under 8 ms.

With the 4-core box fully busy, throughput stays near 16 images per second. Past that, uploads queue in the pool, which is acceptable because the rest of the API stays responsive.

How it differs

A worker thread runs JavaScript in parallel inside one Node process. The event loop is the single thread that handles callbacks and I/O. Worker threads exclude the single-threaded limit, the loop excludes parallel CPU work. A thread pool is a group of threads that may include them. Worker threads help CPU-bound work and give little benefit for I/O-bound work.

Common errors

Using them for database calls that are already async. Spawning a new worker for each request. Passing huge objects by copy. Setting the pool larger than core count. Forgetting error handling, so a crashed worker silently drops jobs.

In practice

Profile first and move only the proven blocking tasks, such as image work, PDF building or large parsing, to a pool of workers. Watch event loop delay as the success measure.

See also

Event loop, Thread pool

Sources

Count this on a real site.

Watch my website