Blocking vs non-blocking I/O
What blocks Node's event loop, the libuv thread pool and its four-thread default, sync APIs to avoid, and how to measure event-loop delay.
Blocking vs non-blocking I/O
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A request has two kinds of work: CPU work (your code running) and I/O work (waiting for a disk, network or database). Node is fast at the second because waiting does not use the JavaScript thread, and slow at the first because there is only one.
- Anything that runs on the JavaScript thread for a long time blocks every other callback, so every other request. That includes `*Sync` APIs, large `JSON.parse` calls, heavy loops, and regular expressions with catastrophic backtracking.
- Some async APIs are not truly asynchronous at the operating-system level. Node runs file-system calls, `dns.lookup`, `zlib` and CPU-heavy `crypto` functions on libuv's thread pool, which has four threads by default (`UV_THREADPOOL_SIZE`). More concurrent calls than threads queue up.
- Sync APIs are fine at startup (loading config before the server listens) and in scripts and CLIs. They are a bug inside a request handler.
- Measure rather than guess: `perf_hooks.monitorEventLoopDelay()` records how late the loop's timer fires, and `performance.eventLoopUtilization()` tells you how busy the loop is.
Two kinds of work
Think about what a typical request actually does. It parses a header (microseconds of CPU), queries a database (milliseconds of waiting), maybe calls another service (more waiting), and formats a response (microseconds of CPU). The waiting dominates. The video for this lesson makes exactly that split: CPU work, where code is running, and I/O work, where something is waiting for the outside world.
A thread-per-request server spends threads on the waiting. Node does not. It starts the I/O, moves on, and picks the result up later, as the event loop delivers it. That is why one thread can keep thousands of connections going.
The same split explains the failure mode. The one JavaScript thread can only do CPU work for one request at a time. While it computes, nothing else runs.
What blocks the loop
A callback blocks the loop when it runs for a long time without yielding. The usual suspects:
- Sync APIs:
fs.readFileSync,crypto.pbkdf2Sync,child_process.execSync, and anything else ending inSync. - Large data work:
JSON.parseorJSON.stringifyon tens of megabytes. Parsing a 61 MB array on the test machine took well over 50 ms, during which nothing else ran. - Heavy loops: image resizing, big sorts, report generation, naive
fibonacci(45). - Catastrophic regular expressions:
/^(a+)+$/.test('a'.repeat(28) + 'b')takes over 100 ms for 28 characters, and the time roughly doubles per extra character. User-supplied input into a pattern like that is a denial-of-service hole. See regular expressions.
You can see the effect directly. This runs a 10 ms interval while a synchronous hash is computed, then again with the async version:
import { pbkdf2, pbkdf2Sync } from 'node:crypto';
let ticks = 0;
const iv = setInterval(() => ticks++, 10);
pbkdf2Sync('pw', 'salt', 1_500_000, 64, 'sha512');
console.log('ticks during sync call:', ticks); // 0
await new Promise(r => pbkdf2('pw', 'salt', 1_500_000, 64, 'sha512', r));
console.log('ticks during async call:', ticks); // more than 5
clearInterval(iv);
During the sync call the interval cannot fire at all: zero ticks. The async version does the same work on another thread, so the loop keeps ticking.
When are *Sync calls acceptable? At startup, before the server begins listening, where nothing else is waiting on you. And in scripts and CLIs, where there is no concurrency to protect. Inside a request handler, they are a bug.
“Async” does not always mean “on the network”
An asynchronous API starts work and calls back later. Where the work runs differs:
- Network I/O (accepting connections, reading sockets) uses the operating system’s own async mechanisms. No thread is parked waiting.
- Files, DNS lookups via
dns.lookup,zlibcompression and the CPU-heavy parts ofcryptohave no equivalent portable OS mechanism, so libuv runs them on its thread pool.
The pool has four threads by default, set by the environment variable UV_THREADPOOL_SIZE. Eight concurrent hashes on a Node 26.13.1 laptop with ten cores:
import { pbkdf2 } from 'node:crypto';
const t = Date.now();
for (let i = 0; i < 8; i++) {
pbkdf2('pw', 'salt', 300000, 64, 'sha512', () => console.log(`hash ${i} at ${Date.now() - t} ms`));
}
Four finish at about 62 ms and the other four at about 124 ms. Two waves, one per four threads, even though the machine had spare cores. Run it with UV_THREADPOOL_SIZE=8 node file.js and they finish in one wave. The variable must be set before the pool is first used, so set it in the process environment, not partway through your program. A busy pool is a quiet cause of slow file reads and slow DNS in a server that does lots of hashing.
The video does not mention the pool by name, per its description. The lesson’s point still holds: the thread pool is where the “async but still costs a thread” work lives, and Bryan Hughes’ talk under “go deeper” covers it.
Fixes for CPU-bound work
- Use the async version of the API if one exists.
- Break the work into chunks and yield between them with
setImmediate, so the loop can service other callbacks. - Move heavy computation to a worker thread: worker threads.
- Move it to another process or service: child processes.
Measuring event-loop delay
You can measure whether the loop is being blocked with perf_hooks:
import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay({ resolution: 10 });
h.enable();
setTimeout(() => { const end = Date.now() + 200; while (Date.now() < end) {} }, 50);
setTimeout(() => {
h.disable();
console.log('max delay ms:', Math.round(h.max / 1e6)); // at least 150
}, 500);
The histogram samples how late a recurring timer fires. A loop with nothing blocking stays near the resolution value; one with a 200 ms stall shows a maximum delay in the hundreds of milliseconds. Export h.percentile(99) as a metric and alert on it. performance.eventLoopUtilization() returns { idle, active, utilization }, a number between 0 and 1 for how busy the loop is. Profiling and finding bottlenecks shows how to find which code is responsible.
What the video covers
Studying With Alex, from March 2021, explains blocking versus asynchronous I/O in friendly terms and the difference between CPU work and I/O work, and why that makes a single-threaded server viable. It is conceptual and uses no Node code, per its description. The thread-pool numbers, the sync-versus-async experiment and the event-loop-delay code come from the prose and were all run on Node 26.13.1. No transcript was available.
Where this fits
This closes the “how Node runs” part of the roadmap. Next come modules: how code is split into files and loaded, starting with CommonJS modules. The streaming APIs that avoid loading whole files into memory are in why streams.
Check yourself
A request handler calls `fs.readFileSync` on a 5 ms read. Why does that matter if 5 ms is short?
While the call runs, no other callback can run. At 200 requests per second, 5 ms of blocking per request is a full second of blocking per second, so latency climbs without bound. The async version lets other requests make progress during the read.
You start eight `crypto.pbkdf2` calls at once and they finish in two groups of four. Why?
`pbkdf2` runs on libuv's thread pool, which has four threads by default. Four calls run in parallel, and the other four wait for a free thread. Setting `UV_THREADPOOL_SIZE` before the pool is first used changes the size.
Which of these use the thread pool: `fs.readFile`, an HTTP server accepting a connection, `crypto.randomUUID()`, `zlib.gzip`?
`fs.readFile` and `zlib.gzip` use the pool. Network I/O such as accepting connections uses the operating system's async facilities directly, not the pool. `randomUUID()` is a fast synchronous call that draws from a prefilled entropy cache and does not need the pool.
How would you detect in production that something is blocking the event loop?
Record event-loop delay with `monitorEventLoopDelay` and alert when the high percentiles climb, and watch `eventLoopUtilization`. Rising delay with flat CPU on a single core points to long synchronous work on the main thread.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.