Difficulty: Intermediate
How does the Node.js event loop work, what are its phases, and how is it different from the browser event loop?
The Node.js event loop is a loop run by libuv on the main thread that repeatedly picks up completed I/O and timer events and runs their JavaScript callbacks, one at a time. Your JavaScript runs on a single thread, but the actual I/O (sockets, files, DNS, crypto) is done by the operating system or by libuv's thread pool, so one Node process can juggle thousands of concurrent connections without blocking.
Each pass through the loop (a "tick") visits these phases in order, and each phase has its own FIFO queue of callbacks:
setTimeout and setInterval whose threshold has passed.setImmediate callbacks, right after poll.socket.on('close').Between every individual callback, Node drains the microtask queues: first the process.nextTick queue, then the Promise queue (.then, await continuations, queueMicrotask). That is why a resolved Promise always runs before the next timer, and why a recursive process.nextTick can starve the loop completely.
Since Node 20 (libuv 1.45), timers are checked only after the poll phase rather than both before and after it. This rarely changes application code, but it is why old blog posts sometimes describe slightly different ordering.
dns.lookup, crypto.pbkdf2, zlib and a few others run on libuv's thread pool, which has 4 threads by default (change it with UV_THREADPOOL_SIZE, max 1024).| Aspect | Node.js | Browser |
|---|---|---|
| Implemented by | libuv | The browser (per HTML spec) |
| Macrotask structure | Six named phases | Task queues chosen by the browser |
| Extra queues | process.nextTick, setImmediate | requestAnimationFrame, rendering steps |
| Rendering | None | Paint can happen between tasks |
| Microtasks | Drained between each callback | Drained after each task |
The big practical difference: browsers interleave rendering with tasks, so a long task causes visible jank. Node has no rendering, so a long task instead causes latency spikes and timeouts for every concurrent request.
setTimeout(fn, 0) vs setImmediate(fn) in the main module: the order is not guaranteed, because it depends on how fast the loop starts. Inside an I/O callback, setImmediate always runs first.process.nextTick. In CommonJS, nextTick wins.fs.readFileSync, crypto.pbkdf2Sync, a huge JSON.parse) block the loop. Use the async version, stream, or move CPU work to worker_threads.perf_hooks.monitorEventLoopDelay(); a rising p99 delay is often the first sign of a blocking bug.// order.cjs (run with: node order.cjs)
const fs = require('node:fs');
console.log('1: sync');
setTimeout(() => console.log('timeout (main)'), 0);
setImmediate(() => console.log('immediate (main)'));
process.nextTick(() => console.log('2: nextTick'));
Promise.resolve().then(() => console.log('3: promise'));
console.log('1b: sync');
// Inside an I/O callback the order IS deterministic
fs.readFile(__filename, () => {
setTimeout(() => console.log('5: timeout (in I/O)'), 0);
setImmediate(() => console.log('4: immediate (in I/O)'));
});
Synchronous code runs first, then the nextTick queue, then Promise microtasks. Inside an I/O callback the check phase comes before the next timers phase, so setImmediate reliably beats setTimeout there.
const express = require('express');
const app = express();
// BAD: blocks the event loop for ALL users
app.get('/hash', (req, res) => {
const crypto = require('crypto');
// This takes ~500ms and blocks everything
const hash = crypto.pbkdf2Sync(
'password', 'salt', 100000, 64, 'sha512'
);
res.json({ hash: hash.toString('hex') });
});
// GOOD: non-blocking with async version
app.get('/hash-async', async (req, res) => {
const crypto = require('crypto');
const hash = await new Promise((resolve, reject) => {
crypto.pbkdf2(
'password', 'salt', 100000, 64, 'sha512',
(err, key) => err ? reject(err) : resolve(key)
);
});
res.json({ hash: hash.toString('hex') });
});
A synchronous pbkdf2 with 100,000 iterations blocks the loop, so every other request waits. The async version runs on libuv's thread pool and the main thread keeps serving traffic.
// main.js
const { Worker } = require('worker_threads');
function runWorker(data) {
return new Promise((resolve, reject) => {
const worker = new Worker('./worker.js', {
workerData: data,
});
worker.on('message', resolve);
worker.on('error', reject);
});
}
// worker.js
const { workerData, parentPort } = require('worker_threads');
// CPU-heavy computation runs in separate thread
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
const result = fibonacci(workerData);
parentPort.postMessage(result);
Worker threads run JavaScript on separate V8 isolates, so CPU-heavy work like this does not block the main event loop. Shown as two files; in practice reuse workers through a pool instead of creating one per request.
Event Loop, libuv, Microtask Queue, process.nextTick, setImmediate, Thread Pool