4 min read

Parallelism in Node.js: what the event loop does not give you

Promise.all is concurrency, not parallelism. What actually runs in parallel in a Node.js process (the libuv pool, worker threads, shared memory), measured by the number a market-data gateway cares about: event-loop delay.


A Node.js process that fans market data out to a few hundred WebSocket clients has one number that matters more than throughput: how late the event loop is. Every tick, heartbeat and order acknowledgement waits behind whatever JavaScript is currently running. Promise.all, async/await and the old async.parallel() do nothing about that. They interleave waiting; they never run two pieces of JavaScript at once.

This note separates the three things that get called "parallelism" in Node.js and shows which of them moves the number.

Concurrency is not parallelism

One isolate executes one JavaScript call stack. Promise.all([a(), b()]) starts both operations and then waits; if a and b are network calls, the waiting overlaps, which is concurrency. If either of them spends 50 ms parsing a snapshot or recomputing a risk grid, everything else in the process is 50 ms late, however the code is spelled.

That is the whole reason a single slow handler shows up as a latency spike on every unrelated client connection at the same time.

What already runs in parallel

Two pieces of the runtime are parallel without any effort:

  • Network I/O is handled by the kernel through epoll, kqueue or IOCP. Sockets do not consume threads, which is why one loop can hold thousands of connections.
  • The libuv thread pool runs the operations that have no non-blocking kernel interface: file system calls, dns.lookup(), the asynchronous crypto functions (pbkdf2, scrypt, randomBytes) and zlib. The pool has four threads by default and is sized with UV_THREADPOOL_SIZE.

The pool is shared. Four concurrent pbkdf2 calls from a login burst occupy all four threads, and a file write for the audit log queues behind them. If a gateway both authenticates users and writes to disk, size the pool deliberately or move one of the two elsewhere.

Neither mechanism runs your JavaScript in parallel.

Worker threads

node:worker_threads gives each worker its own isolate, heap, garbage collector and event loop. That last part matters as much as the CPU: a major GC in a worker does not pause the main thread.

The cost is the boundary. postMessage copies its argument with the structured clone algorithm, so shipping a large object graph to a worker and back can cost more than the work itself. Three ways around it, in increasing order of effort:

  1. Transfer an ArrayBuffer (second argument of postMessage). Ownership moves; nothing is copied; the sender's reference is detached.
  2. Share a SharedArrayBuffer and coordinate with Atomics. Nothing crosses the boundary per message. This only works for data laid out as numbers in typed arrays, which is the natural shape of ticks and book levels anyway.
  3. Keep the whole pipeline in the worker: socket in, decode, aggregate, socket out. The main thread never sees the data.

For CPU-bound steps that are not worth a shared-memory design, a small fixed pool of long-lived workers is the usual answer. Starting a worker costs milliseconds and a new heap, so spawning one per request moves the stall instead of removing it.

Measuring it

perf_hooks.monitorEventLoopDelay() samples how late a timer fires. The script below runs the same CPU work (five rounds of pbkdf2Sync, about 200 ms each) on the main thread and then in a worker.

import { monitorEventLoopDelay } from "node:perf_hooks";
import {
  Worker,
  isMainThread,
  parentPort,
  workerData,
} from "node:worker_threads";
import { pbkdf2Sync } from "node:crypto";
import { setTimeout as sleep } from "node:timers/promises";

const work = () => pbkdf2Sync("secret", "salt", 400_000, 64, "sha512");

if (!isMainThread) {
  for (let i = 0; i < workerData; i++) work();
  parentPort.postMessage("done");
} else {
  const measure = async (label, run) => {
    const h = monitorEventLoopDelay({ resolution: 1 });
    h.enable();
    await run();
    h.disable();
    const ms = (ns) => (ns / 1e6).toFixed(1).padStart(7);
    console.log(
      `${label.padEnd(14)} p50 ${ms(h.percentile(50))} ms   p99 ${ms(h.percentile(99))} ms   max ${ms(h.max)} ms`,
    );
  };

  await measure("idle", () => sleep(1000));
  await measure("main thread", async () => {
    for (let i = 0; i < 5; i++) {
      work();
      await sleep(50);
    }
  });
  await measure(
    "worker thread",
    () =>
      new Promise((resolve) =>
        new Worker(new URL(import.meta.url), { workerData: 5 }).once(
          "message",
          resolve,
        ),
      ),
  );
}

On Node.js 22 on a 4-vCPU Linux VM:

idle           p50     1.1 ms   p99     1.2 ms   max     3.2 ms
main thread    p50     1.1 ms   p99   213.6 ms   max   217.4 ms
worker thread  p50     1.1 ms   p99     1.2 ms   max     1.6 ms

The median is identical in all three rows. A dashboard that plots average loop delay would show nothing wrong while every client received its ticks 200 ms late, five times. Alert on the tail.

Try it

A browser's main thread is the same kind of loop, with requestAnimationFrame standing in for the timers. The figure draws one bar per frame, as tall as the time since the previous frame. Block the thread for 200 ms and one bar spikes while the marker freezes and jumps. Run the identical function in a worker and the frames do not notice.

This interactive figure needs JavaScript.

Frame gaps on this page's main thread. Both buttons run the same 200 ms busy loop; only where it runs differs.

Processes

cluster and plain child processes give isolation that threads do not: separate address spaces, separate crash domains, and the option to pin each process to a core. The natural partition for a feed gateway is by instrument group or by client shard, with no shared state between shards. Use threads when the stages must share memory; use processes when one stage must survive another one crashing.

Choosing

Symptom Mechanism
Many slow network calls Plain async; they already overlap
File, DNS, crypto or zlib calls queueing Size UV_THREADPOOL_SIZE, or move the work
CPU work stalls the loop Worker pool; transfer or share buffers
GC pauses on the thread that owns sockets Move allocation-heavy work to a worker
One client or feed can take down the rest Separate processes per shard

The loop that owns the sockets should do nothing except move bytes. Everything else belongs on another thread or in another process, and the event-loop delay histogram tells you whether that is still true after the next release.