How Node.js works
Overview
To write fast Node.js code — and to avoid writing very slow Node.js code — you need a mental model of what happens when your program runs. The key idea fits in one sentence:
Your JavaScript runs on a single thread, and everything slow happens somewhere else.
This topic explains what “somewhere else” means, why it makes Node good at servers, and the one mistake that undoes all of it.
One thread, many helpers
When your code calls something slow — read a file, query a database, wait for a timer — Node doesn’t wait. It hands the job off and immediately carries on with your next line:
- Network I/O (HTTP requests, database connections, sockets) is handed to the operating system, which can watch thousands of connections at once using mechanisms like epoll (Linux), kqueue (macOS) or IOCP (Windows).
- File system work, DNS lookups, some crypto and compression go to libuv’s thread pool — by default, four background threads.
- Timers are tracked by the event loop itself.
When a job finishes, its callback (or the promise you’re awaiting) is queued. The event loop takes queued callbacks one at a time and runs them on the main thread.
The important consequence: only one piece of your JavaScript runs at any moment. You never have two functions modifying the same variable at the same time, which makes Node code much simpler to reason about than multi-threaded code.
Why this is fast
A typical API request spends a few microseconds running your code and many milliseconds waiting for a database or another service. With one thread per request, those threads would mostly be idle, each holding memory.
Node turns the waiting into free time:
import { readFile } from 'node:fs/promises';
console.time('three files');
await Promise.all([
readFile('a.txt', 'utf8'),
readFile('b.txt', 'utf8'),
readFile('c.txt', 'utf8'),
]);
console.timeEnd('three files'); // roughly as long as the slowest file, not all three added upBlocking the event loop
The model has one weakness. If your JavaScript itself takes a long time, nothing else can run — not other requests, not timers, not callbacks for I/O that has already finished. This is called blocking the event loop.
There are two common causes.
1. Synchronous APIs
Many Node functions have a …Sync version: readFileSync, writeFileSync, execSync, pbkdf2Sync. They do the work on the main thread and make everyone wait:
// ✗ In a request handler: every other user waits for this disk read
const data = readFileSync('big-report.json', 'utf8');
// ✓ Other requests are served while the file loads
const data = await readFile('big-report.json', 'utf8');Sync APIs are perfectly fine in start-up code (loading config before the server starts) and in small scripts where nothing else is going on. Avoid them in anything that handles requests.
2. Heavy computation
CPU work has nowhere to be handed off. A loop over ten million items, parsing a 200 MB JSON file, or a badly written regular expression all run on the main thread:
app.get('/report', (req, res) => {
let total = 0;
for (let i = 0; i < 5_000_000_000; i++) total += i; // seconds of blocking
res.json({ total });
});While that loop runs, the server can’t respond to anyone. Even a health check from your hosting platform would time out.
Seeing it happen
setInterval(() => console.log('tick', new Date().toISOString()), 100);
setTimeout(() => {
const end = Date.now() + 2000;
while (Date.now() < end) {} // block for 2 seconds
console.log('done blocking');
}, 500);The ticks stop completely for two seconds, then resume. In a server, that gap would be two seconds of every user waiting.
Keeping the loop free
- Use async APIs for files, crypto, compression and child processes.
- Keep per-request work small. Paginate large results instead of loading everything; stream big files instead of reading them whole.
- Move CPU-heavy work off the main thread with worker threads (covered in the Performance & scaling chapter) or a separate job queue.
- Watch out for hidden costs:
JSON.parseandJSON.stringifyon huge objects, sorting very large arrays, and regular expressions with nested quantifiers can all block.
The thread pool size
The thread pool has four threads by default. If your app does lots of concurrent file or crypto work, those four can become a queue. You can raise the limit with an environment variable before Node starts:
UV_THREADPOOL_SIZE=8 node server.jsMost apps never need to change it — network I/O doesn’t use the pool at all.
Single thread, multiple cores
One Node process uses one main thread, so it uses roughly one CPU core for JavaScript. To use every core of a big server, you run several Node processes behind a load balancer — with the cluster module, a process manager, or containers. You’ll do exactly that in Clustering and scaling.
Remember: Node is fast because it never waits. Your job is to make sure your own code never makes it wait either.
Spot the blocking code
This server handler blocks the event loop in two places. Find them and rewrite the handler so it doesn't block.
import { readFileSync } from 'node:fs';
import { pbkdf2Sync } from 'node:crypto';
function handleLogin(password) {
const config = JSON.parse(readFileSync('config.json', 'utf8'));
const hash = pbkdf2Sync(password, config.salt, 600000, 64, 'sha512');
return hash.toString('hex');
}import { readFile } from 'node:fs/promises';
import { pbkdf2 } from 'node:crypto';
import { promisify } from 'node:util';
const pbkdf2Async = promisify(pbkdf2);
// Read config once at start-up, not on every request
const config = JSON.parse(await readFile('config.json', 'utf8'));
async function handleLogin(password) {
const hash = await pbkdf2Async(password, config.salt, 600000, 64, 'sha512');
return hash.toString('hex');
}Summary
- Your JavaScript runs on one main thread; Node hands slow I/O to libuv and the operating system.
- Network I/O uses the OS’s async mechanisms; files, DNS lookups, crypto and zlib use libuv’s thread pool (4 threads by default).
- Non-blocking calls let one process serve many requests while each waits.
- Synchronous I/O and heavy CPU work block the event loop and stall every request.
- Move CPU-heavy work to worker threads or another process.