Sub topic 13
The Node.js Event Loop and Its Phases
Earlier chapters described the browser model: run one task, drain the microtask queue, maybe render, repeat. Node.js keeps the same core rules. Code runs to completion on a single thread, and microtasks run before the loop moves on. What changes is how Node.js organizes its tasks. It does not keep one task queue. It splits the work into several phases, and each phase has its own queue of callbacks.
This chapter assumes you know how the call stack, task queue, and microtask queue work, how promises schedule microtasks, and how to run a script with node file.js. The next chapter covers process.nextTick and setImmediate in detail. Here, setImmediate comes up only as the callback type for one phase.
libuv: the Engine Behind the Loop
Node.js runs your JavaScript with V8, but V8 has no event loop of its own. The loop comes from libuv, a C library that provides asynchronous I/O across operating systems. libuv does two jobs:
- It asks the operating system for readiness notifications on sockets, pipes, and similar handles. It uses epoll on Linux, kqueue on macOS, and IOCP on Windows. Network I/O needs no extra threads.
- It runs a thread pool for work the OS cannot do asynchronously in a portable way. This covers most
fscalls,dns.lookup, somecryptofunctions such aspbkdf2andscrypt, andzlibcompression.
In both cases the work happens outside your JavaScript thread. When the work finishes, libuv queues a callback, and the loop runs it on the main thread during the right phase.
The Six Phases
Each full pass through the loop is called a tick or iteration. One iteration visits these phases in a fixed order:
| Phase | What runs there |
|---|---|
| timers | Callbacks from `setTimeout` and `setInterval` whose delay has elapsed |
| pending callbacks | I/O callbacks deferred from the previous iteration, such as some TCP errors (`ECONNREFUSED`) |
| idle, prepare | Internal libuv housekeeping; no user callbacks |
| poll | Retrieves new I/O events and runs their callbacks (file reads, incoming data, new connections) |
| check | Callbacks scheduled with `setImmediate` |
| close callbacks | `'close'` events, such as `socket.on('close')` after `socket.destroy()` |
Only four phases matter in daily work: timers, poll, check, and close. The other two exist, and they explain why a few error callbacks arrive one iteration late.
Microtasks Between Every Callback
In Node.js 11 and later, the microtask rule matches the browser. After each callback finishes, Node.js drains the process.nextTick queue and then the promise microtask queue, before it runs the next callback in the same phase.
setTimeout(() => {
console.log('timeout 1');
Promise.resolve().then(() => console.log('promise inside timeout 1'));
}, 0);
setTimeout(() => {
console.log('timeout 2');
}, 0);
// Output (Node.js 11+):
// timeout 1
// promise inside timeout 1
// timeout 2Both timers expire in the same timers phase. The promise reaction still runs between them, because the microtask queue is drained as soon as the first callback returns.
The Poll Phase: Where Node.js Waits
The poll phase is the only phase where the loop can block, meaning sleep while it waits for the OS. Its logic goes roughly like this:
- Run the callbacks for any I/O events that are already ready, up to a system-dependent limit.
- If the poll queue is now empty:
- If
setImmediatecallbacks are waiting, leave poll right away and go to check. - Otherwise, wait for new I/O events. The wait lasts at most until the nearest timer is due. If no timers exist, the wait has no time limit.
- When the nearest timer's time arrives, wrap around to the timers phase.
This explains why an idle HTTP server uses almost no CPU. It sits in the poll phase while the OS reports nothing new. It also explains why timer delays are a lower bound in Node.js, just as in the browser. A timer fires only after the loop gets back to the timers phase. If a poll callback runs for 50 ms, every timer due during that time waits too.
const fs = require('fs');
const start = Date.now();
setTimeout(() => {
console.log('timer fired after', Date.now() - start, 'ms');
}, 10);
fs.readFile(__filename, () => {
// This I/O callback runs in the poll phase and hogs the thread
const busyUntil = Date.now() + 100;
while (Date.now() < busyUntil) {}
console.log('readFile callback done');
});
// Typical output:
// readFile callback done
// timer fired after ~100+ msWhat Keeps the Loop Alive
A browser tab keeps running until you close it. A Node.js process exits when the loop has nothing left to wait for. After each iteration, libuv checks for active, referenced handles and requests. A handle is a long-lived object such as a timer, a listening server, or an open socket. A request is a one-off operation such as a pending fs.readFile. If none remain, the process exits.
You can tell the loop to ignore a handle by calling unref() on it:
const interval = setInterval(() => console.log('tick'), 1000);
interval.unref();
console.log('script finished');
// Output: script finished
// The process then exits; "tick" never prints,
// because the unref'd interval does not keep the loop alive.This is useful for background jobs, such as a metrics flush or a cache sweep, that should not stop a CLI tool from exiting. ref() undoes it. When a script "hangs" after finishing its work, an open handle is usually the cause: a database pool, a forgotten interval, or a server that was never closed.
The Thread Pool Is Finite
The libuv thread pool has 4 threads by default. If you start more pool-backed operations than that, the extra ones wait in line. The OS-level I/O of the network stack does not use the pool, so this limit applies to fs, dns.lookup, and CPU-heavy crypto and zlib calls.
const crypto = require('crypto');
const start = Date.now();
for (let i = 1; i <= 6; i++) {
crypto.pbkdf2('secret', 'salt', 200000, 64, 'sha512', () => {
console.log(`hash ${i} done at ${Date.now() - start} ms`);
});
}
// Typical shape of the output on a machine with 4+ cores:
// hashes 1-4 finish at about the same time (say ~150 ms)
// hashes 5-6 finish at about double that (~300 ms)You can set the environment variable UV_THREADPOOL_SIZE (maximum 1024) before the process starts, for example UV_THREADPOOL_SIZE=8 node hash.js. A heavily used pool can make unrelated file reads and DNS lookups slow, because they all share the same threads. The JavaScript thread can look idle while the process is still slow.
setTimeout vs setImmediate: A First Look
Because timers and check are separate phases, the order of these two calls depends on where they are scheduled:
- Inside an I/O callback (poll phase),
setImmediatealways runs first, because check comes right after poll. - In the main module, the order is not deterministic.
setTimeout(fn, 0)becomes a 1 ms timer. If the loop reaches the timers phase before 1 ms has passed, the timer is not due yet and the immediate runs first. Otherwise the timer runs first.
The next chapter explains this in detail, along with process.nextTick.
Node.js vs the Browser
| Aspect | Browser | Node.js |
|---|---|---|
| Loop provided by | The browser (HTML spec) | libuv |
| Task organization | Multiple task sources, chosen by the browser | Fixed phases in a fixed order |
| Microtask draining | After each task | After each callback (Node.js 11+), with `nextTick` before promises |
| Rendering step | Yes, with `requestAnimationFrame` | None |
| Where it waits | Between tasks, until there is input or a timer | The poll phase |
| Process lifetime | Lives as long as the page is open | Exits when no referenced handles or requests remain |
| Extra APIs | `requestAnimationFrame`, `MessageChannel` | `setImmediate`, `process.nextTick` |
The main idea carries over unchanged. Your code is never interrupted, and the queue structure decides what runs next. Node.js only spells that structure out in more detail.
Exercise
A Node.js 20 script schedules two zero-delay timers. The first timer's callback calls Promise.resolve().then(() => console.log('P')) and then logs 'T1'. The second timer logs 'T2'. What is printed, and in what order?
Show answer
T1, P, T2. The first callback logs T1 synchronously and queues the promise reaction. When the callback returns, Node.js drains the microtask queue, so P prints before the second timer callback runs in the same timers phase.
Exercise
A CLI script finishes its work but never exits. It created a setInterval for a progress spinner and a database connection pool. Name two ways to make the process exit by itself.
Show answer
Remove the active handles that keep the loop alive. Call clearInterval on the spinner and close the pool (for example pool.end()) when the work is done. If the interval should never keep the process alive, call unref() on it so the loop ignores it.
Exercise
A server hashes passwords with crypto.pbkdf2 and reads templates with fs.readFile. Under load, template reads become slow even though CPU use on the main thread is low. What is the likely cause, and what is one mitigation?
Show answer
Both operations share libuv's thread pool, which has 4 threads by default. Long pbkdf2 jobs take up all the threads, so the file reads wait in line. One mitigation is to raise UVTHREADPOOLSIZE when the process starts. Others are to cache templates in memory or move hashing to worker threads or a separate service.