Lab 01: Event Loop Deep Dive

Time: 30 minutes | Level: Advanced | Docker: docker run -it --rm node:20-alpine sh

Overview

Master Node.js's event loop internals: phases (timers/poll/check), microtask queue, macrotask queue, process.nextTick vs queueMicrotask, libuv thread pool, and blocking detection.


Step 1: Event Loop Phases

The Node.js event loop has 6 phases that execute in order:

   ┌───────────────────────────┐
┌─>│           timers          │  setTimeout, setInterval callbacks
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │     pending callbacks     │  I/O errors from previous iteration
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │       idle, prepare       │  Internal use only
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │           poll            │  Retrieve I/O events, execute callbacks
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │           check           │  setImmediate callbacks
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
└──┤      close callbacks      │  'close' events
   └───────────────────────────┘

Between each phase: microtask queue (nextTick + Promises) runs to completion.


Step 2: Execution Order Demo

💡 process.nextTick fires before other microtasks. Overuse can starve I/O!


Step 3: Microtask Queue In Detail


Step 4: setTimeout vs setImmediate


Step 5: libuv Thread Pool


Step 6: Blocking the Event Loop


Step 7: setImmediate vs nextTick Performance


Step 8: Capstone — Event Loop Timing

Run verification:

📸 Verified Output:


Summary

Queue/Phase
API
Priority
When Runs

nextTick queue

process.nextTick()

Highest

After current op, before microtasks

Microtask queue

Promise.then(), queueMicrotask()

High

After nextTick, before phases

Timers phase

setTimeout(), setInterval()

Normal

When timer expires

Poll phase

I/O callbacks

Normal

Waiting for I/O

Check phase

setImmediate()

Normal

After poll

Thread pool

crypto, fs, dns.lookup

OS threads

Up to UV_THREADPOOL_SIZE parallel

Last updated