Node.js Internals #1: The Event Loop, Notes and a Cheatsheet
Notes from watching This is how the Node.js Event Loop really works (Software Developer Diaries), with every output below re-run on Node v26.8.1 instead of copied from the video.
The event loop sounds scary, but it is just a process that keeps spinning, pulling callbacks out of queues and handing them to the call stack. All the difficulty is in remembering which queue gets served first.
The parts
- Call stack: where functions actually execute. Part of the JavaScript engine (V8).
- Heap: where values live. Also part of the engine.
- libuv: the C library underneath Node. It talks to the operating system for you: network, file system, DNS, the thread pool, child processes.
- Task queue: in Node it is not one queue but four (timers, I/O,
setImmediate, close). - Microtask queue: two queues,
process.nextTickand promises. - Event loop: picks callbacks from those queues and pushes them onto the call stack when it is empty.
type NodeRuntime = {
engine: { callStack: Fn[]; heap: unknown };
libuv: "OS threads, sockets, files, DNS";
microtasks: { nextTick: Fn[]; promises: Fn[] }; // served first
tasks: { timers: Fn[]; io: Fn[]; immediate: Fn[]; close: Fn[] }; // served second
};
Rule zero: synchronous code never queues
A console.log goes straight onto the call stack and runs. The loop is not involved. The flip side is that a synchronous function that takes 10 seconds blocks everything for 10 seconds, because nothing can be pulled from any queue until the stack is empty. That is the whole reason you do not block the main thread.
Priority order
1. synchronous code (call stack)
2. microtasks → process.nextTick, then promises
3. tasks → timers, then I/O, then setImmediate, then close
After each task, the loop drains the microtasks again before moving on.
Example 1: microtasks
console.log("1 sync");
Promise.resolve().then(() => console.log("4 promise"));
process.nextTick(() => console.log("3 nextTick"));
console.log("2 sync");
1 sync
2 sync
3 nextTick
4 promise
nextTick is written after the promise but still runs before it.
Example 2: timers, I/O, and a nextTick
const fs = require("fs");
setTimeout(() => console.log("timeout 1"), 0);
setTimeout(() => console.log("timeout 2"), 0);
fs.readFile(__filename, () => console.log("readFile (I/O)"));
setTimeout(() => console.log("timeout 3"), 0);
process.nextTick(() => console.log("nextTick"));
console.log("sync");
sync
nextTick
timeout 1
timeout 2
timeout 3
readFile (I/O)
Sync first, then the microtask, then timers, then I/O. The file read needs a round trip through libuv, so even though it sits between the timers in the source, it finishes after them.
Example 3: close, timers, and setImmediate
const { Readable } = require("stream");
const r = new Readable({ read() {} });
r.on("close", () => console.log("close"));
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => {
console.log("immediate");
process.nextTick(() => console.log(" nextTick inside immediate"));
Promise.resolve().then(() => console.log(" promise inside immediate"));
});
r.destroy();
console.log("sync");
sync
close
timeout
immediate
nextTick inside immediate
promise inside immediate
Two things to notice. Microtasks queued inside a setImmediate callback run right after that callback, nextTick first. And close came before the timeout, which contradicts the "close always runs last" rule.
Why did close run first?
The "close queue" only holds close callbacks that libuv itself fires (for example a socket handle being closed). A stream's destroy() emits close from JavaScript using process.nextTick, so it lands in the microtask queue and runs before any timer. I found this by running the example, not by reading it: the mental model of "close is always last" is right for libuv handles and wrong for this stream case.
Gotcha: setTimeout 0 vs setImmediate
From the main module, the order of setTimeout(fn, 0) and setImmediate(fn) depends on how fast the process starts, so do not rely on it. From inside an I/O callback, setImmediate always wins, because the loop moves from the I/O phase straight to the check phase:
fs.readFile(__filename, () => {
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
});
// immediate, timeout (5 runs out of 5)
Cheatsheet
| What you write | Where it lands | Runs |
|---|---|---|
console.log, loops, plain calls | Call stack | Immediately |
process.nextTick | nextTick queue (microtask) | 1st after the stack empties |
.then, await continuation | Promise queue (microtask) | 2nd, after nextTick |
setTimeout, setInterval | Timers queue | Task phase 1 |
| File and network callbacks | I/O queue | Task phase 2 |
setImmediate | Immediate queue | Task phase 3 |
Handle close callbacks | Close queue | Task phase 4 |
- Microtasks are drained completely after every task, not once per loop.
- nextTick always beats promises.
- Recursive
nextTickor promise chains can starve the loop, because the microtask queue never empties. - Never block the main thread. Push CPU-heavy work to worker threads or another service.
- Timer delays are a minimum, not a promise.
Conclusion
You do not need to memorise the internals to predict most output. Ask: is it synchronous? Is it a microtask (nextTick, then promise)? Otherwise, which of the four task queues is it in? That is the entire game.
References
- This is how the Node.js Event Loop really works, Software Developer Diaries (the video these notes follow)
- JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue, Lydia Hallie (the browser-side version, recommended in the video)
- JavaScript Visualized: Event Loop, Lydia Hallie (written version)
- The Node.js Event Loop, Node.js docs
- libuv design overview
process.nextTickandsetImmediate, Node.js API docs
Node.js Internals: Part 1 · Part 2 · Part 3 · Part 4 · Part 5