Skip to content

What blocks a Node server

Working knowledgeConcept

Your health check normally answers in 3 ms, then one user asks for a report and every request takes two seconds. Node runs all your JavaScript on one thread, so a single handler that computes instead of waiting stalls everyone. Here is why, how to spot it, and how to move the work off that thread.

01 A health check that takes two seconds

Here is a tiny server with one slow route and one fast one. The slow route does two seconds of CPU work, standing in for a big report, image resize or password hash.

server.js
const http = require('node:http');
function busy(ms) {
const end = Date.now() + ms;
while (Date.now() < end) {} // pure CPU work, no await
}
http
.createServer((req, res) => {
if (req.url === '/report') {
busy(2000);
res.end('report done\n');
} else {
res.end('ok\n');
}
})
Shell
$ curl -s -o /dev/null -w 'health alone: %{time_total}s\n' localhost:3000/health
health alone: 0.002704s
$ curl -s localhost:3000/report & sleep 0.1
$ curl -s -o /dev/null -w 'health during report: %{time_total}s\n' localhost:3000/health
health during report: 1.891273s

That is a real run on Node 24. /health does no work at all, yet it waited almost 1.9 seconds: the 2 seconds of the report, minus the 0.1 seconds it started late.

02 One thread runs all your JavaScript

A Node process has one main thread that runs every callback you write: request handlers, timers, promise continuations. The event loop hands that thread one callback at a time, and only takes the next when the current one returns.

Most server work is waiting: for the database, for a file, for another service. Node does that waiting without the thread. You start the I/O, the callback returns, and the thread is free to run other requests until the result comes back. That is how one thread serves thousands of connections.

await db.query(...)Thread free while waitingThe query runs in the database. The handler is parked, and other requests run on the main thread in the meantime.
busy(2000), JSON.parse(huge)Thread busy the whole timeThe work is the JavaScript itself. Nothing else can run until it returns, however many requests are waiting.

03 What happens to the other requests

Follow the three requests from the measurement: one report, then two health checks that arrive while it is computing. The timings are examples that match the run above.

Three requests, one busy thread (example timings)
Step 1 of 10
Main thread · running JS
Empty
Requests waiting
Empty
Responses sent
Empty
  • just arrived or started
  • still running
  • waiting or done

The server is listening. No request has arrived, the main thread is idle, and the event loop is waiting for something to happen.

0 ms clock (example)

Marking a function async does not move its work anywhere. An async handler that loops for two seconds still loops on the main thread; await only frees the thread while it waits for a promise that something else will settle.

04 What counts as blocking

Anything that keeps one callback running for a long time blocks. A rough guide: a few milliseconds per request is fine; tens of milliseconds start to show up in tail latency under load; hundreds stall the server.

Common ways a Node handler hogs the main thread
CulpritWhy it blocksNon-blocking option
JSON.parse / JSON.stringifyLinear in payload size; a body of many MB can take tens of ms or moreLimit body size; stream large data
crypto.pbkdf2Sync, scryptSyncDeliberately slow hashing, on the main threadcrypto.pbkdf2 / scrypt (thread pool)
fs.readFileSync and friendsWaits for the disk on the main threadfs.promises.readFile
zlib.gzipSyncCompression is CPU workzlib.gzip or a stream
Loops over large arrays, big sortsPlain computationPaginate, or a worker thread
A regex with nested quantifiersBacktracking can take exponential time on bad inputRewrite the pattern; limit input length

The *Sync functions are fine at start-up, before the server listens. Inside a request handler, they block every other request for as long as they take.

05 Measure the stall yourself

Node can tell you how late the event loop is running. monitorEventLoopDelay samples how long callbacks wait beyond when they should have run. Here a 300 ms busy loop runs inside a timer:

lag.js
const { monitorEventLoopDelay } = require('node:perf_hooks');
const h = monitorEventLoopDelay({ resolution: 10 });
h.enable();
setTimeout(() => {
const end = Date.now() + 300;
while (Date.now() < end) {}
}, 100);
setTimeout(() => {
h.disable();
console.log(`max delay: ${Math.round(h.max / 1e6)} ms`);
}, 600);
Shell
$ node lag.js
max delay: 307 ms

In production, export h.percentile(99) as a metric. A p99 event-loop delay that climbs with traffic is the clearest sign of a blocking handler. Now compare a sync and an async password hash, each with a 10 ms timer set just before:

pbkdf2Sync
setTimeout(() => log('timer'), 10);
crypto.pbkdf2Sync('pw', 'salt', 600000, 32, 'sha256');
// sync hash took 47 ms
// timer fired after 47 ms
pbkdf2 (callback)
setTimeout(() => log('timer'), 10);
crypto.pbkdf2('pw', 'salt', 600000, 32, 'sha256', done);
// timer fired after 13 ms
// async hash took 46 ms

Real runs, Node 24 on an Apple laptop; your milliseconds will differ. The hash costs the same either way. The difference is where it runs: the async version hands it to libuv’s thread pool, so the main thread is free to fire the timer on time.

06 Getting the work off the main thread

There are three standard moves, from least to most effort:

  • Use the async API when one exists. crypto, zlib, fs and DNS lookups have versions that run on libuv’s thread pool, which has 4 threads by default (set UV_THREADPOOL_SIZE to change it). Four slow hashes at once fill the pool, and the fifth waits.
  • Split the work into chunks and yield between them with setImmediate. Each chunk is short, so other requests run in the gaps. The total time grows a little, but nothing stalls for long.
  • Run it on a worker thread with worker_threads, or in a separate process or job queue. The computation moves to another thread with its own event loop; the main thread only waits for a message.

Here is the same server with the report on a worker thread:

server.js
const http = require('node:http');
const { Worker } = require('node:worker_threads');
function runReport() {
return new Promise((resolve, reject) => {
const w = new Worker('./report-worker.js');
w.once('message', resolve);
w.once('error', reject);
});
}
http
.createServer(async (req, res) => {
if (req.url === '/report') {
res.end(await runReport());
} else {
report-worker.js
const { parentPort } = require('node:worker_threads');
const end = Date.now() + 2000;
while (Date.now() < end) {} // same CPU work, other thread
parentPort.postMessage('report done\n');
Shell
$ curl -s localhost:3000/report & sleep 0.1
$ curl -s -o /dev/null -w 'health during report: %{time_total}s\n' localhost:3000/health
health during report: 0.001672s

A real run: the report still takes about 2 seconds, but /health answers in under 2 ms while it runs. Starting a worker costs some milliseconds and memory, so for many small jobs keep a pool of workers instead of one per request; for long jobs a queue such as the one in Background jobs is often simpler.

07 When it bites

app.post('/import', async (req, res) => { const rows = JSON.parse(req.body); rows.sort(byDate); });async on a CPU-heavy handlerasync changes the return type, not the thread. The parse and the sort still run on the main thread. Bound the input size, or move the work to a worker.
bcrypt.hashSync(password, 12);Sync password hashing on loginHashes are slow on purpose; a sync call blocks the whole server once per login. Use the async version so it runs off the main thread.
for (const user of await db.allUsers()) { render(user); }Loading everything, then loopingWaiting for the query is fine; the loop over a million rows is not. Page through results, or stream them and process in chunks.
/^(a+)+$/.test(input);A regex that backtracksOn input like many as followed by !, this pattern can take exponential time, and a single request freezes the server. Avoid nested quantifiers on user input and cap its length.
UV_THREADPOOL_SIZE=16 node server.jsA small thread pool under loadAsync crypto, zlib and fs share 4 threads by default. Under many concurrent hashes they queue for the pool: the main thread stays free, but those requests still slow down.

08 Check yourself

Question

A handler is async and does await sleep(2000) (a promise-based timer). Does it block other requests for 2 seconds?

Question

You change busy(2000) into async function busy() with the same loop inside, and await busy(2000) in the handler. What happens to /health?

Question

Which change keeps /health fast while a 2-second report is computed?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?