← Runtimes
Runtimes

What happens underneath asynchronous I/O?

Separate event-loop progress from worker-pool capacity.

Trace submission, native service, and callback delivery as separate parts of an asynchronous operation.

Outcome

Trace an asynchronous Node operation to where it runs, predict when work queues behind the worker pool, and keep latency-sensitive I/O from waiting behind CPU-heavy pool work.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

libuv
The C library under Node that provides the event loop, operating-system readiness polling and a worker thread pool.
Worker pool
A process-global libuv pool, four workers by default, used by the asynchronous file operations and crypto calls discussed here, plus getaddrinfo-based dns.lookup. Pending requests can outnumber workers.
Readiness polling
A Unix socket mechanism, using facilities such as Linux epoll or macOS kqueue, that notifies the loop about possible progress. Windows uses a completion-based mechanism. This is distinct from assigning a worker to each connection.
UV_THREADPOOL_SIZE
Startup environment setting for libuv pool capacity. The initialized pool does not resize when process.env changes; code-level changes require a controlled process whose pool has not already started.
Head-of-line blocking
A short task waiting in a queue behind long ones.

The resources behind an async API

An asynchronous API lets its caller submit an operation and regain control before its result is delivered. Something still has to perform the operation: the operating system may report readiness or completion, or a native worker may do blocking work on the caller’s behalf. A JavaScript promise exposes the result without describing that machinery.

Separate three stages when diagnosing latency: submission, service by the underlying resource, and delivery of the completion callback. Requests can queue before service begins, and a completed request can wait for JavaScript execution. Event-loop progress and available worker capacity therefore describe different parts of the path.

01Where async work runs

Async does not mean nothing is waiting

During a burst of sign-ups, the heartbeat still ticks but a tiny config read waits behind password hashes. The maintainer has to trace both requests below their JavaScript promises: keeping callbacks responsive and leaving capacity for their work are separate requirements.

This Node program uses one JavaScript agent. On Unix, established socket I/O is normally driven by readiness notifications; Windows uses I/O completion ports. Those paths do not reserve a libuv worker per connection. The async file read/write and crypto.pbkdf2 calls used here do use libuv’s shared pool. A completed worker request still needs the loop to run its JavaScript callback. Name resolution, TLS and other work around a connection can have different costs, so “network request” is too broad a pool classification.

Where common Node async operations run
OperationRuns on
Established net / http socket I/OUnix readiness or Windows completion; JavaScript callbacks on the loop
Async fs.readFile / fs.writeFile (including promises)Worker-pool work; readFile can involve several requests
crypto.pbkdf2, scrypt, randomBytes (async)Worker pool
dns.lookupWorker pool (getaddrinfo)
setTimeout, setImmediateThe event loop itself

02Four threads

The pool runs a fixed number of jobs at once

This program starts eight async pbkdf2 hashes and a 50 ms timer, and prints when each finishes, rounded to 100 ms.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { pbkdf2 } from 'node:crypto';

const start = performance.now();
const elapsed = () => Math.round((performance.now() - start) / 100) * 100;

for (let job = 1; job <= 8; job++) {
  pbkdf2('password', 'salt', 500_000, 32, 'sha256', () => {
    console.log(`hash ${job} done at about ${elapsed()} ms`);
  });
}
setTimeout(() => console.log(`50 ms timer ran at about ${elapsed()} ms`), 50);
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts
In the recorded Linux observation summarized below, how were the eight completions grouped with the default pool?

03Sizing the pool

Pool size is fixed once the pool starts

This lab uses two controls: admit fewer hash requests than the default pool’s capacity, or choose a larger startup pool with room beyond the requested hashes. A per-call cap is insufficient when two handlers overlap: three admitted requests per handler can become six against a four-worker pool. Admission state must be shared at the pool’s scope, and its ownership must cover native completion. Neither reserves a thread against unrelated users of the same process-global pool. libuv’s documented maximum is 1024, but more threads consume resources and do not create more CPU quota. Set UV_THREADPOOL_SIZE in the launch environment for reliable startup configuration. In-process changes are only a controlled experiment when nothing has initialized the pool; Node warns that setting process.env during execution is not generally guaranteed to work.

In a controlled process with the default four-worker pool, fs.promises.writeFile has already initialized it. Code then sets process.env.UV_THREADPOOL_SIZE = "16" and submits 12 hashes, with no other pool users. How many hash jobs can the pool service concurrently?

04Practice

Sign up without stalling

The lab calls native PBKDF2 and real file APIs, with a 20 ms heartbeat. A supplied adapter records completed native calls so the report can match returned key prefixes to each requested password. Fixed salt and abbreviated keys are fixture diagnostics, not a password-storage format. Five heartbeat callbacks indicate some progress; they do not bound the worst event-loop delay. The 100 ms read threshold is an authored feasible fixture target. Startup setup and temporary-file cleanup sit outside that observation window.

The sign-up service

Keep hashing off the JavaScript agent, reserve pool capacity for a config read, then plan startup capacity for a varying burst before the pool is initialized.

  1. easy · R-AIO-V4-1 Hash off the main thread
  2. medium · R-AIO-V4-2 Leave room in the pool
  3. hard · R-AIO-V4-3 A bigger pool
Check this idea later
In a controlled Node process using the default pool, many slow dns.lookup requests overlap unrelated fs.readFile calls. Why can those reads slow down?
On Linux, 10,000 established idle HTTP sockets have completed DNS and setup, with no application work. Roughly how many libuv pool workers do those socket waits themselves occupy?
For launch-time configuration, or the controlled not-yet-initialized pool experiment here, where can UV_THREADPOOL_SIZE take effect?
Sources
In the frontend A server route can combine several users of the same Node pool. Optional

An export route compresses four large report bodies while loading their manifest. Its app-owned report-fixtures module supplies bodies: Buffer[] and manifestPath: string for a real local fixture file. Review where the manifest read can queue when the four gzip requests are already pending. These excerpts assume a Node runtime/adapter.

app/api/export/route.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { gzip as gzipCallback } from 'node:zlib';
import { promisify } from 'node:util';
import { readFile } from 'node:fs/promises';
import { bodies, manifestPath } from '@/lib/server/report-fixtures';

export const runtime = 'nodejs';
const gzip = promisify(gzipCallback);

export async function GET() {
  const compressed = bodies.map((body) => gzip(body));
  const manifest = await readFile(manifestPath, 'utf8');
  await Promise.all(compressed);

  return Response.json({ manifest });
}

Async gzip and async file operations use the Node pool. Starting four compression requests can leave the manifest waiting for pool capacity while JavaScript callbacks remain responsive.

This is a diagnostic route body, not measured compression throughput or proof that increasing thread count improves CPU throughput. The explicit Node runtime matters; these Node APIs are not an Edge-runtime example.

Sources: Node.js: zlib thread-pool usage,Next.js: Route Handlers,SvelteKit: server endpoints.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.