Courses / Node.js: From First Script to Production / Chapter 13
Module 6 · Inside the runtime · Chapter 13 of 27
The libuv Thread Pool and Blocking Work
Builds on Core Modules: Files, Paths, Buffers, Crypto and util, Building a Basic Web Server with node:http, Advanced Topics: Child Processes, Worker Threads, Cluster and Debugging and Inside the Event Loop: Phases, Timers and setImmediate. Next up: Streams in Depth: Custom Streams, Backpressure and Pipelines.
Part 1 · What runs on the pool and what does not
One thread for JavaScript, a few more behind it
Node is called single-threaded, yet a file read does not stop your JavaScript, and a password hash can run beside a request. The extra threads are real, and knowing which work lands on them explains many slow servers.
JavaScript runs on one thread, but Node's C++ side has helpers. libuv, the C library under Node, keeps a thread pool: a small, fixed set of worker threads that take jobs from a shared queue. A job is a function that would block, such as reading a file or computing a hash. A pool thread runs it, and when it is done the result goes to the poll queue of the event loop, where the callback you passed gets its turn. The event loop chapter showed that handover from the loop's side.
The libuv documentation says the pool is used for file system operations and for getaddrinfo and getnameinfo requests, and that you can run your own work on it from C++. Node builds more on that:
| Work | On the pool? |
|---|---|
fs calls such as readFile, stat, writeFile | yes |
dns.lookup, which http and net use for host names | yes |
crypto.pbkdf2, crypto.scrypt, crypto.randomBytes with a callback | yes |
async zlib compression | yes |
| TCP and UDP sockets, HTTP traffic | no, the operating system tells the loop when data is ready |
dns.resolve4 and the other dns.resolve* calls | no, they query the network directly |
Proving which work shares the pool
The pool is shared, and it has a queue. If something fills it, every other job that needs the pool waits. The next script starts four slow hashes and then, while they run, starts four other operations at the same time: a host name lookup, a file read, a TCP connection to a local server, and a 1 ms timer. It first measures them with an idle pool, as a baseline.
import crypto from 'node:crypto'; import dns from 'node:dns/promises'; import fs from 'node:fs/promises'; import net from 'node:net'; import { setTimeout as sleep } from 'node:timers/promises'; async function timed(fn) { const start = performance.now(); await fn(); return Math.round(performance.now() - start); } const server = net.createServer().listen(0, '127.0.0.1'); await new Promise((resolve) => server.once('listening', resolve)); const { port } = server.address(); const jobs = { 'dns.lookup': () => dns.lookup('localhost'), 'fs.readFile': () => fs.readFile(import.meta.filename), 'tcp connect': () => new Promise((resolve) => { net.connect(port, '127.0.0.1').on('connect', function () { this.destroy(); resolve(); }); }), 'timer 1 ms': () => sleep(1), };
The second half starts the hashes, runs the four operations together under a busy pool, and prints both sets of timings.
function hashes(n) { const work = []; for (let i = 0; i < n; i++) { work.push(new Promise((resolve) => { crypto.pbkdf2('pw', 'salt', 600_000, 64, 'sha512', resolve); })); } return Promise.all(work); } async function runAll() { const names = Object.keys(jobs); const times = await Promise.all(names.map((n) => timed(jobs[n]))); return Object.fromEntries(names.map((n, i) => [n, times[i]])); } const quiet = await runAll(); const pending = hashes(4); await sleep(20); const busy = await runAll(); await pending; console.log('operation idle pool pool busy'); for (const name of Object.keys(jobs)) { const a = String(quiet[name]).padStart(6); const b = String(busy[name]).padStart(6); console.log(`${name.padEnd(14)} ${a} ms ${b} ms`); } server.close();
operation idle pool pool busy dns.lookup 5 ms 249 ms fs.readFile 4 ms 249 ms tcp connect 3 ms 1 ms timer 1 ms 1 ms 1 ms
Node 24.18.0 on Windows. The busy-pool numbers vary from run to run.
With an idle pool every operation finished in a few milliseconds. With the four hashes running, dns.lookup and fs.readFile took about 250 ms. They did not run slowly. They waited for a free thread, and they got one only when a hash finished. The TCP connection and the timer did not care, since neither uses the pool.
Other calls that use the pool
The scripts below check two more calls. Five async scrypt calls and five async randomBytes calls each run in two groups, four and then one.
scrypt 2 done at 78 ms scrypt 3 done at 81 ms scrypt 1 done at 81 ms scrypt 4 done at 86 ms scrypt 5 done at 148 ms randomBytes 4 done at 64 ms randomBytes 3 done at 65 ms randomBytes 2 done at 65 ms randomBytes 1 done at 65 ms randomBytes 5 done at 128 ms
Node 24.18.0. Each call starts at once, five of them, with the pool at its default size of four.
In both cases four calls finished together and the fifth finished later. That is a pool of four threads at work. Compression works through the same pool, though in many small jobs. The script below runs one gzip with an idle pool and one while four hashes run.
gzip, idle pool 5 ms gzip, 4 hashes running 330 ms
Node 24.18.0. The same pool, the same wait.
The Node documentation for dns says that dns.lookup is implemented as a synchronous getaddrinfo call on libuv's threadpool, which can have surprising negative performance implications. A slow resolver that makes getaddrinfo take seconds ties up one thread per lookup, and four such lookups can stop every file read in the process.
Why does a server with thousands of open sockets not need thousands of threads?
- Sockets do not use the pool. One thread asks the operating system which sockets are ready, and the loop runs their callbacks.
Four hashes occupy the pool. Which of these is delayed: fs.readFile, a TCP connect, or a setTimeout?
- Only
fs.readFile. It needs a pool thread. A TCP connection and a timer do not use the pool.
Which DNS call uses the pool, dns.lookup or dns.resolve4?
dns.lookup, since it calls the system'sgetaddrinfoon a pool thread.dns.resolve4queries the network directly without the pool.
Part 2 · Four threads by default
The default size and what it means
The pool has four threads unless you change it. That number decides how much pool work can run at once.
The libuv documentation gives the default as 4 and the maximum as 1024. The libuv documentation says the size can be changed at startup time with the environment variable UV_THREADPOOL_SIZE. The pool is created the first time something needs it, so a program that never touches it never pays for it, and its size cannot change after that.
Five hashes started at the same moment give the clearest picture. Each of the first four gets a thread. The fifth waits in the queue and starts when one of the four is free. Look at it in the scene.
Watch for the fifth hash waiting while four threads are busy
Read it as steps
The pool runs four hashes at once. The fifth waits for a free thread and finishes in a second wave.
Two waves in a real run
The script starts five pbkdf2 hashes at the same moment and prints when each finishes. Each hash takes about 220 ms of processor time on this machine.
import crypto from 'node:crypto'; const start = performance.now(); for (let id = 1; id <= 5; id++) { crypto.pbkdf2('pw', 'salt', 600_000, 64, 'sha512', () => { const ms = Math.round(performance.now() - start); console.log(`hash ${id} finished at ${ms} ms`); }); }
hash 1 finished at 286 ms hash 3 finished at 349 ms hash 2 finished at 427 ms hash 4 finished at 441 ms hash 5 finished at 592 ms
Node 24.18.0 on Windows, default pool size. The order of hashes 1 to 4 varies.
The first four finished between 286 and 441 ms. The fifth finished at 592 ms, well after the others. The shape is plain: four together, then one on its own.
Now the same script with UV_THREADPOOL_SIZE set to 5. The first part of the command is Git Bash syntax. In PowerShell you would set $env:UV_THREADPOOL_SIZE = 5 first.
UV_THREADPOOL_SIZE=5 node l2-waves.mjshash 1 finished at 274 ms hash 2 finished at 302 ms hash 4 finished at 324 ms hash 5 finished at 330 ms hash 3 finished at 353 ms
Node 24.18.0 on Windows, with UV_THREADPOOL_SIZE=5.
All five finished within about 80 ms of each other, in a single wave. And with a size of 1 the hashes ran one after another.
hash 1 finished at 220 ms hash 2 finished at 425 ms hash 3 finished at 656 ms hash 4 finished at 881 ms hash 5 finished at 1105 ms
Node 24.18.0 on Windows, with UV_THREADPOOL_SIZE=1.
Each hash added about the same time to the previous one. The pool queue is first in, first out, and one thread serves it.
Setting the size
Set the variable in the environment of the process: in a service file, a container setting, or on the command line, as above. That is the reliable way. The Node documentation says that setting process.env.UV_THREADPOOL_SIZE from inside the program is not guaranteed to work, because the pool may already have been created before your code runs. In these runs it worked when the assignment came before anything used the pool, as the next script shows.
process.env.UV_THREADPOOL_SIZE = '5'; const { default: crypto } = await import('node:crypto'); const start = performance.now(); for (let id = 1; id <= 5; id++) { crypto.pbkdf2('pw', 'salt', 600_000, 64, 'sha512', () => { const ms = Math.round(performance.now() - start); console.log(`hash ${id} at ${ms}`); }); }
hash 5 at 226 hash 1 at 236 hash 3 at 262 hash 2 at 292 hash 4 at 311
Node 24.18.0 on Windows. All five run in one wave.
The same assignment fails once the pool is in use. The next script reads a file asynchronously first, which creates the pool with four threads, and only then sets the variable to 5.
import fs from 'node:fs'; fs.statSync('.'); await new Promise((resolve) => { fs.readFile(import.meta.filename, resolve); }); process.env.UV_THREADPOOL_SIZE = '5'; const start = performance.now(); for (let id = 1; id <= 5; id++) { const { pbkdf2 } = await import('node:crypto'); pbkdf2('pw', 'salt', 600_000, 64, 'sha512', () => { const ms = Math.round(performance.now() - start); console.log(`hash ${id} at ${ms}`); }); }
hash 3 at 234 hash 4 at 267 hash 1 at 299 hash 2 at 312 hash 5 at 502
Node 24.18.0 on Windows. Hash 5 finished well after the others, so the size was still 4. Linux gave the same shape.
A program that depends on this assignment depends on nothing else having used the pool first, and a later change to the code can break it without any error. Put the variable in the environment.
A bigger pool is not a general fix. The pool is only as fast as the processor behind it. Hashes are processor work, so more threads than there are free cores do not make a hash faster. They make more hashes run at once and each one slower. The size should follow how many blocking calls you want in flight, not how many requests you receive. Remember also that all pool work shares it: raising the size to speed up hashing also lets more file reads and lookups run, which may be what you want or may not.
Part 3 · Blocking the loop
Synchronous work holds the thread
The pool protects you only if you use the asynchronous form of a call. The Sync forms, and some plain JavaScript, run on the thread that serves every request.
Most blocking in real services is not a bad algorithm. It is an ordinary call used on the main thread: a Sync function in a request handler, a big JSON.parse, a regular expression with nasty input. While it runs, no timer fires, no socket is read, and no other request moves. Four of them are easy to measure. The script below runs each one and records how long a 10 ms timer had to wait for the stack to be free.
import crypto from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; const rows = Array.from({ length: 400_000 }, (_, i) => { return { id: i, n: i }; }); const json = JSON.stringify(rows); const file = path.join(os.tmpdir(), 'blocking-demo.bin'); fs.writeFileSync(file, Buffer.alloc(200 * 1024 * 1024)); const mb = Math.round(json.length / 1e6); const cases = { 'pbkdf2Sync, 600,000 rounds': () => { crypto.pbkdf2Sync('pw', 'salt', 600_000, 64, 'sha512'); }, [`JSON.parse of ${mb} MB`]: () => JSON.parse(json), 'readFileSync of 200 MB': () => fs.readFileSync(file), 'regex /^(a+)+$/ on 24 chars': () => { /^(a+)+$/.test('a'.repeat(24) + 'b'); }, };
for (const [label, work] of Object.entries(cases)) { const asked = performance.now(); const timer = new Promise((resolve) => setTimeout(resolve, 10)); work(); await timer; const late = Math.round(performance.now() - asked); console.log(`${label.padEnd(28)} timer ran after ${late} ms`); } fs.rmSync(file);
pbkdf2Sync, 600,000 rounds timer ran after 203 ms JSON.parse of 10 MB timer ran after 39 ms readFileSync of 200 MB timer ran after 51 ms regex /^(a+)+$/ on 24 chars timer ran after 690 ms
Node 24.18.0 on Windows. These timings are from this machine and vary.
Each line says how long the whole process was unavailable. A hash computed with pbkdf2Sync held the thread for about 200 ms. The same 600,000 rounds started with the asynchronous pbkdf2 leave the loop free, as the next lessons show.
JSON.parse of a 10 MB string took about 40 ms. That is quick, but parsing cannot be paused halfway, so the cost grows with the size of what the client sent. A body twenty times larger blocks for many times longer.
A regular expression that never ends
The last line is the dangerous one. The pattern ^(a+)+$ has nested repetition. On input that almost matches, a string of a characters followed by one b, the engine tries every way of splitting the run of a characters between the inner and the outer group, and the number of ways doubles with each extra character.
This is called regular expression denial of service, or ReDoS, and the OWASP project documents it. It is worth checking every pattern that runs on user input for nested repetition and alternations that overlap. A single request carrying a crafted string can make a server unresponsive, and nothing in the error logs will say why.
The doubling, measured
The next script times one match in a new process for each length. The numbers below are one run on Windows, and the Linux run showed the same doubling.
const n = Number(process.argv[2]); const input = 'a'.repeat(n) + 'b'; const start = performance.now(); /^(a+)+$/.test(input); const ms = Math.round(performance.now() - start); console.log(`${n} a's then b, first run in a new process: ${ms} ms`);
20 a's then b, first run in a new process: 42 ms 22 a's then b, first run in a new process: 165 ms 24 a's then b, first run in a new process: 668 ms 25 a's then b, first run in a new process: 1350 ms 26 a's then b, first run in a new process: 3142 ms 27 a's then b, first run in a new process: 5949 ms
Node 24.18.0 on Windows, one run per line, each in a new process (the loop was `for n in 20 22 24 25 26 27`).
Each extra character roughly doubled the time. If the doubling goes on, around 34 characters would take more than ten minutes. That figure is an extrapolation and was not run. Run the same pattern again inside one process and it gets faster, because V8 compiles a pattern to machine code after repeated use. In a warm process the 24 character case took 74 ms. A first request with crafted input meets the slow case.
| Blocking cause | Typical fix |
|---|---|
*Sync call in a handler | use the callback or promise form |
huge JSON.parse or stringify | limit the body size, or stream the data |
| long loop over a big array | split into chunks, or use a worker |
| nested-repetition regex on user input | rewrite the pattern, cap the input length |
To test a pattern, run it on a string of the form 'a'.repeat(n) + 'b' for growing n and watch the time. If it doubles with each step, the pattern is unsafe on user input. Safer choices are to avoid nested repetition, to limit the input length before matching, or to use a parser for the format instead of a regular expression.
Part 4 · Measuring the damage
Two requests, one slow
You have seen a timer wait. A server shows the same thing as slow responses. Two routes and the loop's own numbers make it measurable.
The server below has three routes. /hash-sync hashes with pbkdf2Sync, /hash-async hashes with the asynchronous pbkdf2 through promisify, and every other path answers at once. Its loop delay is recorded with monitorEventLoopDelay, as the event loop chapter explained.
import crypto from 'node:crypto'; import http from 'node:http'; import { execFile } from 'node:child_process'; import { monitorEventLoopDelay } from 'node:perf_hooks'; import { promisify } from 'node:util'; const pbkdf2 = promisify(crypto.pbkdf2); const histogram = monitorEventLoopDelay({ resolution: 10 }); const server = http.createServer(async (req, res) => { if (req.url === '/hash-sync') { crypto.pbkdf2Sync('pw', 'salt', 600_000, 64, 'sha512'); } else if (req.url === '/hash-async') { await pbkdf2('pw', 'salt', 600_000, 64, 'sha512'); } res.end('ok'); });
The second half runs the two routes in turn, one client process each, and prints what the client saw and the loop delay.
function client(route) { return new Promise((resolve) => { execFile(process.execPath, ['l4-client.mjs', route], (err, out) => { resolve(out.trim()); }); }); } server.listen(55620, '127.0.0.1', async () => { for (const route of ['/hash-sync', '/hash-async']) { histogram.reset(); histogram.enable(); const line = await client(route); histogram.disable(); const max = Math.round(histogram.max / 1e6); console.log(`${line}, loop delay max ${max} ms`); } server.close(); server.closeAllConnections(); });
A second script is the client. It is a separate process, so it does not block with the server. It starts a request to the hash route, waits 20 ms, and then times a request to /ping.
const route = process.argv[2]; const base = 'http://127.0.0.1:55620'; const slow = fetch(base + route).then((r) => r.text()); await new Promise((resolve) => setTimeout(resolve, 20)); const start = performance.now(); await fetch(base + '/ping').then((r) => r.text()); const ms = Math.round(performance.now() - start); await slow; console.log(`${route.padEnd(12)} /ping answered in ${ms} ms`);
Reading the signals
The scene and the numbers agree, and so should your monitoring. Three readings tell you the loop is being held.
- The event loop delay maximum or p99 is far above its idle value. The idle value is the baseline, about 15 ms on this Windows machine and 10 ms on Linux, as the event loop chapter showed.
- Event loop utilisation sits near 1 while the processor of the whole machine is not busy. The loop is saturated even though the machine is not.
- Latency rises for every route at once, including the cheapest, and the rise has the same size as one slow handler.
The third sign is the easiest to spot in dashboards. If only one route is slow, look at that route's own code. If every route has a slow spot at the same moment, something is blocking the loop. A profile then tells you what. The profiling chapter shows how to take one.
An asynchronous call is not always a cheap one
The asynchronous hash left the loop free, but it still used a pool thread for the whole of its time. Moving work off the main thread is only half the job. The pool must have room for the next job, as the first lesson showed with dns.lookup and readFile waiting behind hashes. A server that starts hundreds of hashes at once makes every file read wait. The cure is to limit how many run together, which the next lesson covers.
/ping answers in 5 ms when the hash route uses pbkdf2 and in 165 ms when it uses pbkdf2Sync. What explains the difference?
- The synchronous call holds the loop for the whole hash, so
/pingcannot start. The asynchronous call runs on a pool thread and the loop stays free.
All routes get slow at the same moment. What does that suggest?
- Something is blocking the event loop, since a slow route's own code would not slow the others.
Event loop utilisation is near 1, yet the machine's processor is mostly idle. What do you conclude?
- The single JavaScript thread is saturated. The machine has capacity, but one thread cannot use it.
Part 5 · Fixing it
Four ways to keep the loop free
Once you know a piece of work blocks, there are four standard ways to deal with it, and they are best tried in this order. The script after the list compares three of them on the same job.
- Use the asynchronous API.
pbkdf2instead ofpbkdf2Sync,readFileinstead ofreadFileSync. This costs nothing and fixes most cases. - Cap the input. Reject request bodies and uploads above a limit and test patterns on short strings. Work that cannot grow without bound cannot block without bound.
- Split the work. Process a chunk, then give the loop a turn with
setImmediate, and continue. This suits JavaScript loops over big arrays. - Move it to a worker thread. A worker has its own event loop. The main thread hands it the job and keeps serving. This suits long computations that cannot be split, and the advanced topics chapter showed how to start one.
One job, three ways
The job counts the prime numbers below three million by trial division. It is pure processor work. The first helper file is shared by the three ways.
export function isPrime(n) { if (n < 2) return false; for (let d = 2; d * d <= n; d++) if (n % d === 0) return false; return true; } export function countPrimes(from, to) { let count = 0; for (let n = from; n < to; n++) if (isPrime(n)) count++; return count; }
import { parentPort, workerData } from 'node:worker_threads'; import { countPrimes } from './l5-primes.mjs'; parentPort.postMessage(countPrimes(0, workerData.limit));
The main script runs the job in one of three modes, and a heartbeat timer ticking every 10 ms records the longest pause between its ticks.
import { Worker } from 'node:worker_threads'; import { countPrimes } from './l5-primes.mjs'; const LIMIT = 3_000_000; const modes = { blocking: async () => countPrimes(0, LIMIT), chunked: async () => { let total = 0; for (let from = 0; from < LIMIT; from += 50_000) { total += countPrimes(from, Math.min(from + 50_000, LIMIT)); await new Promise((resolve) => setImmediate(resolve)); } return total; }, worker: () => new Promise((resolve, reject) => { const w = new Worker(new URL('./l5-worker.mjs', import.meta.url), { workerData: { limit: LIMIT }, }); w.once('message', resolve); w.once('error', reject); }), };
let last = performance.now(); let longest = 0; const heartbeat = setInterval(() => { const now = performance.now(); longest = Math.max(longest, now - last); last = now; }, 10); const mode = process.argv[2]; const start = performance.now(); const primes = await modes[mode](); const ms = Math.round(performance.now() - start); await new Promise((resolve) => setTimeout(resolve, 30)); clearInterval(heartbeat); const pause = Math.round(longest); console.log(`${mode}: ${primes} primes, ${ms} ms,`, `longest pause ${pause} ms`);
blocking: 216816 primes, 856 ms, longest pause 856 ms chunked: 216816 primes, 651 ms, longest pause 23 ms worker: 216816 primes, 791 ms, longest pause 22 ms
Node 24.18.0 on Windows, one run of each mode.
All three found the same 216,816 primes in 0.65 to 0.86 s. The totals differ from run to run by more than they differ between modes (a re-run took 0.53 to 0.61 s), so do not read them as a ranking. The difference is the heartbeat. In blocking mode the longest pause was as long as the job itself, 856 ms. In chunked mode the job gave the loop a turn after each 50,000 numbers, and the longest pause was 23 ms. In worker mode the main thread did nothing but wait, with a longest pause of 22 ms. Chunking adds only the cost of the loop turns. A worker must also start a thread and load the code, so it pays off when the job is long.
When there are many jobs
Starting a new worker for every request is wasteful, because starting a thread and loading the code costs time and memory. For a steady stream of processor-heavy jobs, keep a small set of workers and hand each job to a free one. Worker pool libraries exist for this, for example piscina, which this course did not run, so read its documentation before you rely on it. For processor-bound jobs the number of workers should not be more than the number of processors, which os.availableParallelism() reports. The same sizing logic applies to the libuv pool. Limit how many heavy jobs run at once, whichever mechanism runs them.
What not to do
Raising UV_THREADPOOL_SIZE does not fix this particular blocking. The prime loop runs on the main thread, not on the pool. And for jobs that do run on the pool, a bigger pool only lets more of them run at once, each one slower if the processors are shared.
Do not rely on a timeout either. A setTimeout cannot interrupt a synchronous loop, because the callback runs only after the loop ends. A worker, by contrast, can be stopped from outside with worker.terminate().
| Term | Meaning |
|---|---|
| Thread pool | libuv's fixed set of threads for blocking jobs, four by default |
| Blocking the loop | holding the JavaScript thread so no other callback can run |
| ReDoS | a regular expression that takes exponential time on crafted input |
| Chunking | splitting long work into pieces with a loop turn between them |
A request handler loops over 50 lakh records. List two ways to stop it freezing the server.
- Split the loop into chunks with a
setImmediatebetween them, or move the work to a worker thread. Capping the number of records is a third.
In the prime-counting runs, why is chunking not much slower than the blocking run?
- The only extra work was the loop turns between chunks, which are very cheap compared with 50,000 trial divisions, so the total time was about the same as the blocking run.
Will raising UV_THREADPOOL_SIZE stop a long for loop from blocking the loop?
- No. A
forloop in your callback runs on the main thread. The pool is used only by operations that hand work to it.
All chapters · Previous: process.nextTick, Promise Jobs and the Microtask Queue