How-To Guide

How to Move CPU Work Off the Event Loop

Keep a Node.js server responsive: detect blocking work, move it to a worker, and bound the pool so the loop stays free for requests.

On this page

  1. Introduction
  2. Detect the blocking work with loop lag
  3. Move the work to a worker
  4. Bound the worker pool
  5. Consider the alternatives for some work
  6. Measure lag and throughput
  7. Common pitfalls
  8. Conclusion

Introduction

Node.js runs JavaScript on a single thread and uses that thread for both your code and the event loop that dispatches I/O. A CPU-bound operation, such as parsing a large document, hashing, image processing, or a big sort, holds the loop for its duration, so no other request is served, no timer fires, and no I/O callback runs until it finishes. One slow request blocks the whole server, which is why CPU work belongs off the loop.

This tutorial covers detecting blocking work with event loop lag, moving it to a worker thread, bounding the pool, and measuring the difference. The examples use worker threads, and the reasoning applies to any single-threaded async runtime with a way to run work on another thread.

Detect the blocking work with loop lag

The event loop lag is the difference between when a timer should fire and when it does. Measure it by scheduling a timer for a known interval and comparing the actual delay; a growing lag under load means synchronous work is holding the loop. Instrument the lag as a metric and alert on sustained high values, so a newly added blocking operation is caught.

Find the specific operation by timing synchronous functions and looking for one that runs for tens or hundreds of milliseconds. A JSON.parse of a large payload, a crypto hash, a synchronous file read, a large array sort, and a regex over a long string are the usual suspects. The fix is not to make the operation faster in place but to move it off the loop entirely.

let last = Date.now();
setInterval(() => {
  const now = Date.now();
  const lag = now - last - 100;   // interval is 100ms; anything above is lag
  last = now;
  if (lag > 50) metrics.observe('eventloop.lag_ms', lag);
}, 100);

Move the work to a worker

A worker thread runs JavaScript on another thread, so the CPU-bound work no longer holds the main loop. Send the input to the worker, let it compute, and receive the result via a message. The main thread stays free to accept requests and service I/O while the worker computes, so a single CPU-heavy request no longer degrades the others.

Keep the worker’s interface narrow: send the input, receive the output, and avoid sharing mutable state, because workers communicate by message and shared memory is a separate, more complex mechanism. Where the input or output is large, transferring a buffer avoids a copy, but start with the simple message exchange and optimize only if the copy is measured to matter.

// worker.js
import { parentPort } from 'node:worker_threads';
parentPort.on('message', (input) => {
  parentPort.postMessage(heavyCompute(input));   // runs off the main thread
});

// main.js
import { Worker } from 'node:worker_threads';
const worker = new Worker('./worker.js');
function computeInWorker(input) {
  return new Promise((resolve) => {
    worker.once('message', resolve);
    worker.postMessage(input);
  });
}

Bound the worker pool

One worker per request oversubscribes the CPU: more workers than cores add scheduling overhead without adding throughput, and starting a worker per request pays the startup cost each time. Use a fixed pool sized to the number of cores, and queue the work, so the offloaded computation uses the machine fully without oversubscription.

The pool is the same worker-pool structure used for any bounded concurrency: a queue of inputs and a fixed set of workers pulling from it. Size it to the cores minus one to leave a core for the loop and the I/O, and expose the queue depth so saturation is visible. The pool keeps the offloaded work bounded, just as concurrency limits keep a downstream bounded.

class CpuPool {
  private workers: Worker[];
  private queue: { input: unknown; resolve: (v: unknown) => void }[] = [];
  constructor(size = Math.max(1, os.cpus().length - 1)) {
    this.workers = Array.from({ length: size }, () => new Worker('./worker.js'));
    this.workers.forEach((w) => this.attach(w));
  }
  private attach(worker: Worker) {
    worker.on('message', (out) => {
      const job = this.queue.shift();
      if (job) { job.resolve(out); worker.postMessage(job.input); }
      // else worker goes idle
    });
  }
  run(input: unknown): Promise<unknown> {
    return new Promise((resolve) => { this.queue.push({ input, resolve }); this.tryStart(); });
  }
  private tryStart() { /* dispatch queued jobs to idle workers */ }
}

Consider the alternatives for some work

Not every blocking operation needs a worker. A synchronous loop over a large array can be chunked to yield to the loop between chunks, so it runs in pieces without blocking for long. A native library that has an async API should be used through it. Streaming a large file or a large JSON avoids building the whole thing in memory, which also reduces the CPU per event.

Choose the cheapest fix that removes the blocking: a chunked loop for a bounded computation, an async API where available, streaming for a large input, and a worker for genuinely CPU-bound work that cannot be chunked. The worker is the general fallback; reach for it when the others do not fit or do not remove the block.

Measure lag and throughput

Measure event loop lag under CPU load before and after moving the work; assert the lag stays low with the work off the loop, and that it rises when the work is inline. Measure the throughput of a mixed workload, with some CPU-heavy and some light requests, and assert the light requests are not delayed by the heavy ones. This is the property the change buys.

# send a CPU-heavy request and a light request together; the light one must stay fast
curl -s 'http://localhost:3000/heavy' & \
curl -s -o /dev/null -w 'light=%{time_total}s\n' http://localhost:3000/light
# with the work off the loop, the light request remains fast

Common pitfalls

Running CPU-bound work on the main thread so one request blocks all, spawning a worker per request, a worker pool larger than the cores, sharing mutable state between threads, and moving work to a worker when a chunked loop or an async API would have sufficed are the recurring mistakes. Offloading to a fixed pool, sizing it to the cores, a message-passing interface, and choosing the cheapest fix address them.

Conclusion

CPU-bound work belongs off the event loop or it blocks every request. Detect it with event loop lag, move it to a worker thread with a narrow message interface, bound the pool to the cores, and measure the lag and the throughput. Self-check by sending a heavy and a light request together and asserting the light one stays fast. Then a CPU-heavy request costs itself, not the whole server.

Sources: Node.js: Worker threads, Node.js: Don’t block the event loop, Node.js: Event loop and timers.

FAQ

What is event loop lag?
It is the delay between when a timer was scheduled to fire and when it actually fired. A high lag means the loop is busy running synchronous work and cannot service timers, I/O callbacks, or new requests promptly. It is the clearest signal of blocking work.
Worker thread or child process?
A worker thread shares the process memory and is cheaper to start, and fits CPU-bound JavaScript. A child process isolates memory and crash, and fits work that must not share state or that uses a native library not safe in a thread. Choose by isolation and startup cost.

Related Examples