Chapter 06: libuv & async IO said that libuv does the waiting so JavaScript doesn't have to. This chapter shows how, using two very different tools: a small thread pool for files and CPU-heavy crypto, and the operating system's epoll/kqueue for network connections. You'll also learn the golden rule of Node.js performance: don't block the main thread.
In this chapter you'll learn
- what libuv's thread pool is and which operations use it
- why the pool has 4 threads, and how to change that
- why network requests don't use the thread pool
- how
epoll/kqueuelet one thread watch thousands of connections - what blocks the main thread, and how to avoid it (including worker threads)
Before you start: read Chapter 06: libuv & async IO and Chapter 09: libuv & event loop. The example is in Code/ThreadPool.js.
What is a thread pool?
A thread pool is a fixed group of worker threads that take jobs from a shared queue. Think of a bank with 4 counters: customers (jobs) wait in one line, and each free counter takes the next customer.
libuv keeps such a pool for operations that can't be done asynchronously by the operating system, or that are CPU-heavy. When your JavaScript calls one of them, the job goes to the pool and the main thread carries on immediately.
What uses the thread pool
| Uses the thread pool | Does not use it |
|---|---|
almost all fs.* file system calls (readFile, writeFile, stat...) | network: http, https, net, TCP/UDP sockets |
dns.lookup() (which http.get("example.com") uses to find the IP) | dns.resolve*() (uses its own async library) |
crypto.pbkdf2, crypto.scrypt, async crypto.randomBytes | timers (setTimeout...), handled by the event loop |
zlib async compression (gzip...) | your own JavaScript code |
When a pool thread finishes a job, it hands the result back to the event loop, and the callback runs on the main thread, in the poll phase (Chapter 09: libuv & event loop).
The pool has 4 threads by default
Let's prove it. crypto.pbkdf2 is a deliberately slow password-hashing function (more on why in Chapter S2 09: Encrypting Passwords), and it runs on the thread pool. Start five at once:
The examples in this chapter use ES Modules (import), the modern standard. To run them, add "type": "module" to your package.json or name the files .mjs. The CommonJS form is const crypto = require("node:crypto"); see the CommonJS → ES Modules cheat sheet.
// pool.js
import crypto from "node:crypto";
const start = Date.now();
for (let i = 1; i <= 5; i++) {
crypto.pbkdf2("password", "salt", 2000000, 50, "sha512", () => {
console.log(`hash ${i} done after ${Date.now() - start} ms`);
});
}// pool.js
import crypto from "node:crypto";
const start = Date.now();
for (let i = 1; i <= 5; i++) {
crypto.pbkdf2("password", "salt", 2000000, 50, "sha512", () => {
console.log(`hash ${i} done after ${Date.now() - start} ms`);
});
}With the default pool of 4 threads (real output; exact times vary with your machine):
hash 2 done after 1513 ms
hash 1 done after 2104 ms
hash 3 done after 2445 ms
hash 4 done after 2802 ms
hash 5 done after 3569 ms ← had to WAIT for a free thread, so it finishes lasthash 2 done after 1513 ms
hash 1 done after 2104 ms
hash 3 done after 2445 ms
hash 4 done after 2802 ms
hash 5 done after 3569 ms ← had to WAIT for a free thread, so it finishes lastNow with a pool of 5:
UV_THREADPOOL_SIZE=5 node pool.jsUV_THREADPOOL_SIZE=5 node pool.jshash 4 done after 1724 ms
hash 5 done after 1894 ms
hash 3 done after 2068 ms
hash 1 done after 2187 ms
hash 2 done after 2197 ms ← all five ran at the same time and finished togetherhash 4 done after 1724 ms
hash 5 done after 1894 ms
hash 3 done after 2068 ms
hash 1 done after 2187 ms
hash 2 done after 2197 ms ← all five ran at the same time and finished togetherWith 4 threads, only four hashes run at once; the fifth waits in the queue. With 5 threads, all five run in parallel (on a machine with enough CPU cores).
Notice also that the hashes don't finish in order: each one runs on its own thread, and whichever finishes first gets its callback queued first.
Changing the pool size
UV_THREADPOOL_SIZE=8 node app.jsUV_THREADPOOL_SIZE=8 node app.js- libuv reads
UV_THREADPOOL_SIZEonce, when the pool is first used. Set it as an environment variable before starting Node.js. (The course example setsprocess.env.UV_THREADPOOL_SIZEat the very top of the script, which works only because the pool hasn't been created yet at that point. The environment variable is the reliable way.) - The maximum is 1024.
- More threads help only if you run many
fs/crypto/zlib jobs at once and have CPU cores to spare. They do nothing for network-heavy apps, and too many threads just compete for the same cores.
Network I/O: no thread pool, no thread per connection
A web server might have 10,000 open connections at once. One thread each would need gigabytes of memory, which is the old Apache problem from Chapter 01: Introduction to NodeJs. So how does Node.js do it?
Sockets and file descriptors
Every network connection is a socket. The operating system identifies each open socket (and each open file) by a small number called a file descriptor (FD). The name says "file", but it's used for sockets too.
A naive server would call a blocking read on each socket, which needs one thread per connection, because each thread sits waiting on its own socket. Node.js does not work that way.
epoll, kqueue and IOCP
Modern operating systems offer an event notification mechanism:
- epoll on Linux
- kqueue on macOS and BSD
- IOCP (I/O Completion Ports) on Windows
libuv registers all your sockets with this mechanism in one go and asks: "Tell me when any of these has something to do." The kernel (the core of the operating system) watches all of them and reports back the ones that are ready, such as "socket 42 has new data". That check happens in the event loop's poll phase.
The result: one thread can watch tens of thousands of connections. Each idle connection costs only a small entry in the kernel's list, not a whole thread.
Data structures behind the scenes
- epoll keeps the set of watched file descriptors in a red-black tree (a self-balancing tree), so adding and removing sockets stays fast even with thousands of them.
- libuv keeps timers in a min-heap, a structure where the timer that expires soonest is always on top and can be found instantly.
You don't need to implement either, but they show why picking the right data structure matters.
The golden rule: don't block the main thread
Everything above only works if your JavaScript keeps the main thread free. All your callbacks, for every user, run on that one thread. If one callback takes 2 seconds, everyone waits 2 seconds.
Things that block the main thread:
- Sync APIs inside request handlers:
readFileSync,pbkdf2Sync,execSync... - Huge JSON:
JSON.parse/JSON.stringifyon very large objects (megabytes) is synchronous. - Complex regular expressions on user input. Some patterns take exponential time on certain strings (called ReDoS, Regular expression Denial of Service).
- Heavy calculations: big loops, image resizing, sorting millions of items.
- Infinite or very long loops, of course.
What to do instead
- Use the async versions of APIs (
fs.promises.readFile,crypto.pbkdf2). - Stream large files and responses instead of loading them all at once (
fs.createReadStream). - Move CPU-heavy work to worker threads (the
worker_threadsmodule), which run JavaScript on separate threads:
// main.js
import { Worker } from "node:worker_threads";
// new URL(..., import.meta.url) finds heavy.js next to THIS file, wherever you run node from
const worker = new Worker(new URL("./heavy.js", import.meta.url), { workerData: 40 });
worker.on("message", (result) => console.log("fib(40) =", result));
console.log("Main thread is still free!");// main.js
import { Worker } from "node:worker_threads";
// new URL(..., import.meta.url) finds heavy.js next to THIS file, wherever you run node from
const worker = new Worker(new URL("./heavy.js", import.meta.url), { workerData: 40 });
worker.on("message", (result) => console.log("fib(40) =", result));
console.log("Main thread is still free!");// heavy.js
import { parentPort, workerData } from "node:worker_threads";
const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
parentPort.postMessage(fib(workerData)); // slow, but not on the main thread// heavy.js
import { parentPort, workerData } from "node:worker_threads";
const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
parentPort.postMessage(fib(workerData)); // slow, but not on the main thread- For bigger systems, move heavy jobs to a background queue and a separate service.
Key takeaways
- libuv's thread pool (4 threads by default) runs file system,
dns.lookup, some crypto and zlib jobs. - Change it with the
UV_THREADPOOL_SIZEenvironment variable (max 1024), set before Node.js starts. - Network I/O doesn't use the pool. libuv uses the OS's epoll / kqueue / IOCP so one thread can watch thousands of sockets.
- Sockets and files are identified by file descriptors.
- Never block the main thread: avoid sync APIs, giant JSON, dangerous regexes and heavy loops in request handlers. Use async APIs, streams and worker threads.
Interview questions
Q1. What is the libuv thread pool, and what is its default size?
It's a pool of worker threads that libuv uses for operations the OS can't do asynchronously, or that are CPU-heavy: most file system calls, dns.lookup, crypto.pbkdf2/scrypt/randomBytes and zlib. The default size is 4, configurable with the UV_THREADPOOL_SIZE environment variable (up to 1024).
Q2. Do HTTP requests use the thread pool?
No. Network sockets are non-blocking and are monitored with the operating system's event notification mechanism (epoll on Linux, kqueue on macOS, IOCP on Windows). One exception to remember: resolving a hostname with dns.lookup (which http.get uses by default) does use the pool.
Q3. What happens if you start 5 crypto.pbkdf2 calls at the same time?
With the default pool of 4 threads, four hashes run in parallel and the fifth waits in the queue until a thread is free, so it finishes noticeably later. Setting UV_THREADPOOL_SIZE=5 lets all five run at once (given enough CPU cores).
Q4. How can Node.js handle 10,000 concurrent connections on one thread?
It doesn't wait on each connection. libuv registers all sockets with epoll/kqueue, and the kernel reports which ones are ready. The event loop then runs only the callbacks that have work to do. Idle connections cost a small kernel entry, not a thread, so memory use stays low. This is the event-driven model that solved the C10K problem.
Q5. What is the difference between worker threads and the libuv thread pool?
The thread pool is internal to libuv and runs C++ tasks that Node.js itself sends it (file I/O, crypto); you can't put your own JavaScript there. Worker threads (worker_threads module) let you run JavaScript on separate threads, each with its own V8 instance and event loop, communicating with messages. Use them for CPU-heavy JavaScript.
Q6. What is the difference between the cluster module and worker threads?
cluster starts multiple processes (each a full Node.js instance with its own memory) that share one server port. It's used to use all CPU cores for handling requests. Worker threads are threads inside one process, which can share memory (SharedArrayBuffer). They're used for CPU-heavy tasks. In production, process managers like PM2 (Chapter S3 02: Nginx and Backend Node App Development) can run a cluster for you.
Q7. How would you find out if something is blocking the event loop?
Signs: response times jump for all endpoints at once, and timers fire late. Measure it with perf_hooks.monitorEventLoopDelay(), profile with node --prof or Chrome DevTools (node --inspect), and look for sync calls, giant JSON operations, slow regexes or long loops in hot code paths.
What's next
That's the end of Node.js internals. Now let's use them. In Chapter 11: Creating the Server you'll build an HTTP server with nothing but Node.js's built-in http module, and learn what servers, ports and sockets really are.