In Node.js, what are the phases of one libuv event loop iteration, in order, and what kind of callback runs in each?
answer
- six boxes in a cycle
- due timers, then deferred I/O
- poll is where it waits
- check belongs to setImmediate
- abrupt closes come last
basics
~10 sEach Node.js loop iteration runs timers (due setTimeout and setInterval callbacks), pending callbacks (deferred I/O errors), idle and prepare (internal), poll (new I/O events, where the loop waits), check (setImmediate callbacks), then close callbacks.
solid answer
~40 sOne turn of Node's libuv loop visits its phases in a fixed order, and each phase has its own FIFO queue. **Timers** runs `setTimeout()` and `setInterval()` callbacks whose threshold has passed. **Pending callbacks** runs I/O callbacks libuv deferred from the previous turn, such as some TCP connection errors. **Idle** and **prepare** are internal to Node. **Poll** collects new I/O events and runs their callbacks, socket data and finished `fs` work alike, and it is the phase where libuv deliberately waits. **Check** runs `setImmediate()` callbacks, and **close callbacks** runs handlers such as the `'close'` event after `socket.destroy()`. A phase runs until its queue is empty or a limit is hit, then moves on; when nothing keeps the loop alive, the process can exit.
go deeper
Recall the six phases in order and which everyday callbacks land in timers, poll and check.
Explain that each phase drains its own FIFO queue, that poll is where libuv waits, and that finished threadpool work is delivered to JavaScript in poll.
Use the order to reason about latency: a long poll queue or one slow callback pushes back every due timer and immediate behind it.
Know where the phase model stops helping: it explains scheduling inside one loop, while throughput across cores is a question of workers, processes and replicas.
## The order of one iteration The **event loop** is libuv's loop, run by Node on the main thread. Each pass through it is an **iteration**, and each iteration visits a fixed sequence of **phases**. The Node.js guide draws six: 1. **timers**: callbacks from `setTimeout()` and `setInterval()` whose time threshold has been reached. 2. **pending callbacks**: I/O callbacks that libuv deferred to this iteration instead of running them right after polling. On some Unix systems a TCP connect that fails with `ECONNREFUSED` is reported here. 3. **idle, prepare**: used only internally by Node; your code never queues work here directly. 4. **poll**: asks the operating system for new I/O events and runs their callbacks: incoming connections, socket data, and completions of `fs`, `dns.lookup()` or crypto work that ran on the threadpool. This is where the loop blocks when there is nothing else to do. 5. **check**: callbacks scheduled with `setImmediate()`. 6. **close callbacks**: close events for handles closed abruptly, for example the `'close'` event after `socket.destroy()`. Then the cycle returns to timers. ## What each phase queue holds | Phase | Typical Node source | Notes | |---|---|---| | timers | `setTimeout()`, `setInterval()` | Runs only callbacks already due; a threshold is a minimum, not an exact time | | pending callbacks | deferred socket errors | Rarely visible in application code | | idle, prepare | Node internals | Prepare runs right before the loop blocks | | poll | `net`, `http`, `fs`, `dns.lookup()`, `zlib` callbacks | The only phase in which libuv waits for I/O | | check | `setImmediate()` | Runs right after poll finishes | | close callbacks | `'close'` after `socket.destroy()` | A graceful close emits `'close'` through `process.nextTick()` instead | Each phase has a **FIFO queue**. Entering a phase, the loop runs callbacks from that queue until it is empty or a maximum number has run, then moves to the next phase. A callback can schedule more work; new I/O events can arrive while poll callbacks are running, which is why a busy poll phase can run far longer than a timer's threshold. ## Where the timers sit The Node.js guide draws timers at the top of the cycle, and older material describes them as the first thing an iteration does. libuv's own design notes describe the current implementation slightly differently: due timers run once when the loop starts, and then at the **end** of each iteration, after close callbacks and after the loop's notion of "now" is updated. The cyclic order is the same either way (close callbacks, timers, pending callbacks, poll, check), so reasoning in that order stays correct. The detail matters only when you try to predict ordering at the very start of a program, which is the subject of the lesson comparing timers with immediates. ## When the loop stops libuv considers the loop **alive** while it has active and ref'd handles (a listening server, an open socket, a pending timer), active requests (an `fs` read in flight) or handles still closing. Between iterations Node checks this; when nothing is left, the loop ends and the process can exit cleanly. A forgotten interval or an open server therefore keeps the process running. ## What this order does and does not explain - It explains why `setImmediate()` callbacks run after the I/O callbacks of the same iteration: check follows poll. - It explains why a long poll queue, or one slow callback in any phase, delays every due timer: the timers phase cannot start until the earlier phases finish. - It explains why a threadpool result is delivered in poll: the work ran elsewhere, but the callback is an I/O event the loop collects there. - It does **not** cover `process.nextTick()` and promise reactions. Node drains those queues after each callback, between and within phases, and they are covered in the lesson on tick-queue priority. - It does **not** promise a fixed order between a `setTimeout(fn, 0)` and a `setImmediate()` scheduled from the main module; that puzzle belongs to the timers lesson. Keeping the six phases straight is the basis for every other scheduling question in Node: when a callback runs, what delays it, and why the process will or will not exit.
- Where does a completed `fs.readFile()` callback run, given that the read itself happened on a threadpool thread?On the main thread, in the poll phase. The pool thread only performs the blocking system calls. When the task finishes it notifies the loop, libuv calls the completion callback on the loop thread, and Node runs your JavaScript callback there alongside socket events.
- In Node.js, what happens to a due timer while the poll phase is busy running a long queue of I/O callbacks?It waits. A phase runs its queue until it is empty or a system-dependent maximum is reached, and only then does the loop move on. Every I/O callback that runs first adds to the timer's delay, which is why a timer's delay is a minimum threshold rather than an exact firing time.
- Promise callbacks run in their own dedicated phase of the libuv loop.
- setImmediate() callbacks run in the timers phase alongside setTimeout(fn, 0).
- The loop visits phases in whatever order events happen to arrive.
- Every socket 'close' handler runs in the close callbacks phase.
- Completed fs reads are always delivered in the pending callbacks phase.