Node.js Event Loop: Phases, Microtasks, and nextTick Order
Six phases, two queues that are not phases, and one rule: nextTick then microtasks drain between every callback. Why setTimeout and setImmediate swap order at top level.

Quick Summary
Node.js runs your JavaScript on one thread and hands blocking work to libuv. That thread runs an event loop with six named phases per iteration: timers, pending callbacks, idle/prepare, poll, check, close callbacks.
Between callbacks — and between phases — Node drains two queues that are not phases at all: the process.nextTick queue first, then the Promise microtask queue. That ordering is the whole reason a Promise.then runs before a setTimeout(fn, 0) and after a process.nextTick.
Two timers look interchangeable and are not. setTimeout(fn, 0) is clamped to about 1 ms and fires in the timers phase at the start of the next iteration; setImmediate fires in the check phase at the end of the current one. In the main module their order is genuinely unpredictable; inside an I/O callback, setImmediate always wins.
Basic Syntax and Core Signatures
import { setImmediate as immediate, setTimeout as delay } from 'node:timers/promises';
import { monitorEventLoopDelay, performance } from 'node:perf_hooks';
// Ordering primitives
process.nextTick(() => console.log('1 nextTick'));
queueMicrotask(() => console.log('2 microtask'));
Promise.resolve().then(() => console.log('3 promise'));
setImmediate(() => console.log('4 check phase'));
setTimeout(() => console.log('5 timers phase'), 0);
// Yield to the loop from sync-looking async code
await new Promise((resolve) => setImmediate(resolve));
await delay(0); // timers/promises, fires next timers phase
// Timers you do not want to keep the process alive for
const t = setTimeout(() => {}, 60_000);
t.unref(); // or: t[Symbol.toPrimitive]() for the id
clearTimeout(t);
// Measure the loop rather than guess
const h = monitorEventLoopDelay({ resolution: 10 });
h.enable();
setInterval(() => {
console.log('p99 ms', (h.percentile(99) / 1e6).toFixed(1));
h.reset();
}, 5_000).unref();
const elu = performance.eventLoopUtilization(); // { idle, active, utilization }One iteration of the loop:
timers setTimeout / setInterval callbacks that are due
pending I/O callbacks deferred from the previous iteration
idle/prepare internal
poll wait for I/O; run I/O callbacks (fs, net, dns results)
check setImmediate callbacks
close 'close' handlers (sockets, file handles)
after every callback and before the next phase:
drain process.nextTick queue
drain Promise / queueMicrotask queueKey Comparison Table
| Mechanism | Queue | Runs before | Blocks I/O | Good for |
|---|---|---|---|---|
process.nextTick | nextTick | Promise microtasks | Yes, if recursive | Deferring to after the current operation, error-first APIs |
queueMicrotask / Promise.then | Microtask | Timers, I/O | Yes, if recursive | Sequencing async work |
setImmediate | Check phase | Timers of the next iteration | No | Yielding in a loop, "after this poll" |
setTimeout(fn, 0) | Timers phase | Check phase of the current iteration | No | Deferring at least one iteration |
setTimeout(fn, 4) | Timers | — | No | Any deliberate delay; clamped to ≥1 ms |
await on a resolved value | Microtask | Next macrotask | No | Normal async control flow |
| Observation | What it means |
|---|---|
eventLoopUtilization() > 0.9 sustained | CPU-bound work on the main thread |
| p99 loop delay in tens of ms | Blocking call in a request path |
Recursive nextTick starves setImmediate | nextTick queue drains before every phase |
setTimeout(0) drifts to 1–2 ms | Documented clamping, not a bug |
Practical Edge Cases and Deep Dives
1. Why the ordering in an I/O callback is deterministic
import { readFile } from 'node:fs';
readFile(import.meta.filename, () => {
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
});
// immediate
// timeoutThe callback runs inside the poll phase. The check phase comes next in the same iteration, so setImmediate fires there; the timer is only due at the start of the next iteration, after check and close. At the top level of a module the poll phase comes before the timers phase of the next iteration and the outcome depends on how long the process took to reach the loop, so setTimeout(fn, 0) and setImmediate can print in either order. Any test that asserts one of them at module top level is a flaky test.
2. Microtasks versus the next tick, and starvation
function loop(iter) {
if (iter === 0) return;
process.nextTick(loop, iter - 1); // starvation: nothing else runs
}
loop(1e6);
setImmediate(() => console.log('never reached until the queue empties'));process.nextTick callbacks are drained completely before Promises, before timers, before I/O. A self-scheduling nextTick is an infinite loop with extra steps, and the symptom is not a crash but an unresponsive process that never accepts a connection. queueMicrotask and .then have the same property (the microtask queue is drained to empty), which is why a while loop inside a .then is just as fatal. The fix is a macrotask boundary: setImmediate in a chunked loop yields to I/O between chunks.
3. await costs a tick even when nothing is pending
async function f() {
console.log('a');
await undefined;
console.log('c');
}
f();
console.log('b');
// a b cawait always suspends, even for a non-promise, so the continuation lands in the microtask queue after the synchronous code finishes. In a loop over 100k items with await inside, that is 100k microtask hops — measurable, and the reason a synchronous hot path should not be written as async. Node's own fs/promises and HTTP server callbacks are fine; what hurts is await in a per-item map over a large array.
4. Finding a blocked loop instead of guessing
import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
setInterval(() => {
const p99 = h.percentile(99) / 1e6;
if (p99 > 50) console.warn(`loop delay p99 ${p99.toFixed(0)}ms`);
h.reset();
}, 10_000).unref();Loop delay measures how late a 20 ms interval actually fired, which is the honest signal for "something blocked the thread". Pair it with performance.eventLoopUtilization() for saturation and with a CPU profile (--cpu-prof) to find the function. crypto.pbkdf2Sync, zlib.gzipSync, JSON.parse on multi-megabyte payloads, and fs.readFileSync in a request handler are the usual culprits; their async variants run the work on the libuv threadpool instead.
5. Timers, unref, and processes that will not exit
const keepAlive = setInterval(ping, 30_000);
keepAlive.unref(); // do not keep the loop alive for this timer
const socket = net.connect(port);
socket.unref(); // same for handlesA timer or open handle counts as active work, so a script that sets an interval never exits on its own. unref() removes that reference without cancelling the timer: it still fires while something else keeps the loop alive. The opposite mistake — process.exit() from inside a callback — terminates before pending writes flush, which is how log lines and HTTP responses disappear under load. Set process.exitCode and let the loop drain instead.
6. Where worker threads and the threadpool fit
The event loop is one thread; the libuv threadpool (four threads by default, UV_THREADPOOL_SIZE) handles fs, dns.lookup, crypto callbacks and zlib. CPU-bound JavaScript has no threadpool — it blocks the loop itself, and moving it to a worker_threads Worker is the only real fix. Raising UV_THREADPOOL_SIZE helps when many small file operations queue behind each other, but it does nothing for a synchronous loop; and the loop can only run the completion callbacks, so a saturated threadpool shows up as latency rather than as high CPU.
Common Node.js Runtime Mistakes
| Symptom | Cause | Fix |
|---|---|---|
setTimeout/setImmediate test flaky | Order at module top level is undefined | Assert inside an I/O callback, or test the behaviour |
| Process unresponsive, CPU at 100% | Synchronous loop, or recursive nextTick | Chunk with setImmediate, move to a worker |
| Requests time out under load, CPU low | Threadpool saturated (fs, crypto, dns) | Async APIs, raise UV_THREADPOOL_SIZE, cache |
| Script never exits | Active timer, socket, or server | unref(), clearInterval, server.unref() |
| Last log lines missing on exit | process.exit() before flush | Set process.exitCode, let the loop drain |
await in a tight map is slow | One microtask hop per item | Batch, or use a synchronous transform |
| p99 latency spikes with no CPU spike | Blocking call in a rare path | monitorEventLoopDelay, then --cpu-prof |
Top-level await delays startup | Module graph waits for the promise | Keep TLA out of shared modules |
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js EventEmitter: once, error Events, and Listener Memory Leaks
emit is synchronous, so a throwing listener aborts the rest. An error event with no listener crashes the process, and a listener per request is the classic leak.
Node.js fs/promises: Read, Write, Watch, and Atomic File Operations
writeFile truncates before writing, so a crash leaves half a file. The atomic pattern is temp file, fsync, rename; readFile loads everything, so large files need streams.
Node.js Streams: Readable, Writable, Transform, and pipeline
pipe() forwards data but not errors; pipeline() destroys the chain and rejects. Backpressure is the false return from write(), and _flush that never calls back hangs forever.
Node.js crypto: Hashing, HMAC, AES-GCM, and Random Bytes
Hashing, HMAC, AES-256-GCM and randomness solve different problems. Never reuse a GCM nonce, never hash a password with sha256, and compare secrets with timingSafeEqual.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.