Understanding the Node.js event loop
Most explanations of the event loop stop at 'Node is single-threaded and non-blocking'.
Most explanations of the event loop stop at “Node is single-threaded and non-blocking”. That’s true, but it doesn’t help much when your logs come out in an order you didn’t expect, or an API slows down under load for no obvious reason. This is the version I find useful in practice.
One thread for your JavaScript
Your JavaScript runs on a single thread. Node does I/O like files, sockets, DNS and some crypto somewhere else, either in the operating system or in a small thread pool inside libuv. When that work is done, a callback is queued, and the event loop runs it on the main thread when it gets there.
So “non-blocking” means Node doesn’t sit and wait for I/O. It doesn’t mean your own code can’t block. If one callback takes 300 ms, nothing else runs for those 300 ms.
The phases
Each turn of the loop goes through these phases, in order:
- timers: setTimeout and setInterval callbacks whose time is up
- pending callbacks: a few system-level callbacks held over from the last turn
- poll: wait for new I/O events and run their callbacks, which is where most of your code runs
- check: setImmediate callbacks
- close callbacks: things like socket.on(‘close’)
There’s also an internal idle/prepare step you never need to think about.
Then there are two queues that aren’t phases at all: process.nextTick callbacks and promise callbacks. They run as soon as the current operation finishes, before the loop moves on. The nextTick queue goes first, then promises.
Putting it to the test
console.log('script start');
setTimeout(() => console.log('setTimeout'), 0);
setImmediate(() => console.log('setImmediate'));
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('script end');
On Node 18 this prints:
script start
script end
nextTick
promise
setTimeout
setImmediate
The last two can swap, though. Run it a few times and you’ll see both orders. In the main script, it depends on whether the timer (a 0 delay really means 1 ms) is already due when the loop checks timers for the first time, and that depends on how fast the process started.
One more catch: that output is for a CommonJS file. Save the same code as order.mjs and promise prints before nextTick. In an ES module, the top-level code is already running inside a promise job, so the promise queue gets drained before Node gets to the nextTick queue.
Inside an I/O callback the order is always the same:
const fs = require('fs');
fs.readFile(__filename, () => {
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
});
This prints immediate first, every time. The callback runs in the poll phase, the check phase comes straight after, and the timer has to wait for the next turn. If you want something to run right after the current I/O work, setImmediate is the dependable option.
nextTick can starve everything else
Node empties the whole nextTick queue before moving on. So a nextTick that schedules another nextTick keeps everything else waiting:
let count = 0;
function again() {
count++;
if (count < 1e6) process.nextTick(again);
}
setTimeout(() => console.log('timer ran after', count, 'ticks'), 0);
again();
timer ran after 1000000 ticks
The timer was ready almost straight away, but it had to wait for a million ticks. Without the limit it would never run. A chain of promises behaves the same way. If you’re splitting up recursive work, setImmediate lets the loop breathe between steps.
What blocking looks like
const crypto = require('crypto');
const start = Date.now();
setTimeout(() => {
console.log(`timer fired after ${Date.now() - start} ms`);
}, 10);
crypto.pbkdf2Sync('secret', 'salt', 600_000, 64, 'sha512');
console.log(`hash done after ${Date.now() - start} ms`);
hash done after 347 ms
timer fired after 348 ms
A 10 ms timer fired after almost 350 ms. In a server, every request that comes in during that time waits too. Switch to the async crypto.pbkdf2(…) and the hashing moves to libuv’s thread pool, so the timer fires on time.
That pool has 4 threads by default, which you can change with the UV_THREADPOOL_SIZE environment variable. It’s shared by fs, dns.lookup, async crypto and zlib. Start 50 async hashes at once and they queue up behind each other, and your file reads queue up behind them. That’s a common reason for “everything gets slow under load” even when the main thread isn’t busy.
Measuring it
Node can tell you how late the loop is running:
const { monitorEventLoopDelay } = require('perf_hooks');
const histogram = monitorEventLoopDelay({ resolution: 20 });
histogram.enable();
setInterval(() => {
console.log(
'event loop delay p99:',
(histogram.percentile(99) / 1e6).toFixed(1), 'ms',
);
histogram.reset();
}, 1000);
With a 250 ms blocking call in the first second, this printed a p99 of 268 ms, and then about 20 ms afterwards, which is just the sampling resolution. Sending this number to your metrics makes blocking code easy to spot. If the delay jumps while CPU looks normal, look for synchronous work in request handlers: JSON.parse on a huge payload, readFileSync, or a big loop.