Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readNode.js
#Node.js#Event Loop#Async#Performance
3D illustration of a circular conveyor with six phase stations and a priority chip jumping the queue

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

js
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 }
text
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 queue

Key Comparison Table

MechanismQueueRuns beforeBlocks I/OGood for
process.nextTicknextTickPromise microtasksYes, if recursiveDeferring to after the current operation, error-first APIs
queueMicrotask / Promise.thenMicrotaskTimers, I/OYes, if recursiveSequencing async work
setImmediateCheck phaseTimers of the next iterationNoYielding in a loop, "after this poll"
setTimeout(fn, 0)Timers phaseCheck phase of the current iterationNoDeferring at least one iteration
setTimeout(fn, 4)Timers—NoAny deliberate delay; clamped to ≥1 ms
await on a resolved valueMicrotaskNext macrotaskNoNormal async control flow
ObservationWhat it means
eventLoopUtilization() > 0.9 sustainedCPU-bound work on the main thread
p99 loop delay in tens of msBlocking call in a request path
Recursive nextTick starves setImmediatenextTick queue drains before every phase
setTimeout(0) drifts to 1–2 msDocumented clamping, not a bug

Practical Edge Cases and Deep Dives

1. Why the ordering in an I/O callback is deterministic

js
import { readFile } from 'node:fs'; readFile(import.meta.filename, () => { setTimeout(() => console.log('timeout'), 0); setImmediate(() => console.log('immediate')); }); // immediate // timeout

The 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

js
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

js
async function f() { console.log('a'); await undefined; console.log('c'); } f(); console.log('b'); // a b c

await 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

js
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

js
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 handles

A 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

SymptomCauseFix
setTimeout/setImmediate test flakyOrder at module top level is undefinedAssert inside an I/O callback, or test the behaviour
Process unresponsive, CPU at 100%Synchronous loop, or recursive nextTickChunk with setImmediate, move to a worker
Requests time out under load, CPU lowThreadpool saturated (fs, crypto, dns)Async APIs, raise UV_THREADPOOL_SIZE, cache
Script never exitsActive timer, socket, or serverunref(), clearInterval, server.unref()
Last log lines missing on exitprocess.exit() before flushSet process.exitCode, let the loop drain
await in a tight map is slowOne microtask hop per itemBatch, or use a synchronous transform
p99 latency spikes with no CPU spikeBlocking call in a rare pathmonitorEventLoopDelay, then --cpu-prof
Top-level await delays startupModule graph waits for the promiseKeep TLA out of shared modules

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.