Skip to content

Lesson 4 of 9 · 26m

The Event Loop and Worker Threads

What the event loop is good at, where it fails, and how to move CPU-bound work to worker threads without turning concurrency into a debugging lottery.

Node’s scalability story is often repeated backwards. The event loop does not make JavaScript fast at computation; it makes one thread very good at waiting on thousands of sockets. The failure mode appears the first time someone resizes an image, verifies a bcrypt hash, parses a giant JSON document, or renders PDF in the request path. Every connection waits behind that computation.

One loop, many waiting operations

A typical server is mostly idle inside its own process:

const server = createServer(async (req, res) => {
  const rows = await db.query("select id, total from invoices where account_id = $1", [id]);
  res.end(JSON.stringify(rows));
});

The database call is asynchronous because the thread does not sit there spinning. It registers interest, returns to the loop, and resumes when the result arrives. That is why one process can manage thousands of mostly I/O-bound connections.

The loop is phases — timers, pending callbacks, poll, check, close — but memorizing phase order is less important than recognizing starvation. A synchronous 200 ms block means every timer, socket, keepalive, and downstream request in that process is delayed by at least 200 ms.

Measure blocking before redesigning

Use the event-loop delay monitor built into perf hooks:

import { monitorEventLoopDelay } from "node:perf_hooks";
const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();

setInterval(() => {
  console.log({
    p50: histogram.percentile(50),
    p99: histogram.percentile(99),
    max: histogram.max,
  });
  histogram.reset();
}, 10_000);

If p99 event-loop lag climbs while CPU is also high, you have a starvation problem. If lag is low but latency is high, look downstream — database, network, locks, or queueing outside the process.

Worker threads are for CPU, not convenience parallelism

// hash-worker.js
import { parentPort, workerData } from "node:worker_threads";
import bcrypt from "bcrypt";

const hash = await bcrypt.hash(workerData.password, 12);
parentPort.postMessage({ hash });
import { Worker } from "node:worker_threads";

export function hashPassword(password) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(new URL("./hash-worker.js", import.meta.url), {
      workerData: { password },
    });
    worker.once("message", resolve);
    worker.once("error", reject);
    worker.once("exit", code => {
      if (code !== 0) reject(new Error(`hash worker exited ${code}`));
    });
  });
}

Creating a worker per tiny operation is expensive. Use a pool for repeated work, cap concurrency near CPU count, and define a timeout. A worker that never answers is still a hung request unless you design cancellation.

Shared memory is a loaded weapon

SharedArrayBuffer plus Atomics can share memory between threads. It can also create data races that JavaScript developers are not trained to see. Use it for specialized throughput problems, not as a first resort. Structured-clone message passing is slower but safer and easier to reason about.

Transferable objects are the middle ground: large ArrayBuffers can be transferred without copying, after which the sender no longer owns them.

Some operations already leave the loop

Node’s crypto, zlib, and fs implementations use internal thread pools or asynchronous OS facilities depending on the operation. crypto.pbkdf2, bcrypt native bindings, compression, and many file operations are not necessarily occupying the JS thread while active. Know which work is already offloaded before building a worker architecture around it.

Field notes

  • setTimeout(fn, 0) does not mean zero milliseconds in production; timer behavior and loop load both apply.
  • process.nextTick can starve the loop if recursively scheduled; prefer setImmediate for deferring after I/O.
  • Workers share process memory limits but not ordinary JavaScript objects. Messages are copied unless transferred or shared.
  • Size worker pools deliberately. Sixty-four workers on a four-core container mostly create scheduling overhead and memory pressure.
  • CPU-bound endpoints need backpressure and admission control too; worker threads do not make unbounded work safe.

Was this lesson helpful?

Sign in to rate