2. The Event Loop & Async Architecture
Understanding the Event Loop
The Event Loop is the most important concept in Node.js. It is the #1 topic in senior engineering interviews. The Event Loop is what allows a single-threaded language to handle thousands of concurrent connections efficiently.
The Call Stack
The Call Stack is a simple list that tracks which function is currently running. It works like a stack of books: you put one on top, then another, then another. You always remove from the top first. JavaScript can only do one thing at a time, and the Call Stack keeps track of what that one thing is.
function first() { console.log('First'); } function second() { first(); console.log('Second'); } second(); console.log('Global');
Second
Global
Try it: Trace the order. second() goes on stack, it calls first(), first() goes on top, finishes, pops off, then second() finishes, then global code runs.
Blocking the Event Loop
Blocking happens when code takes too long to finish, and the Call Stack cannot move to the next task. If the Call Stack is stuck, the server cannot respond to new requests. The entire application freezes. This is why you never run heavy synchronous operations in Node.js.
// This blocks the event loop for 5 seconds const start = Date.now(); while (Date.now() - start < 5000) { // Doing nothing, just waiting } console.log('Finally done!');
setTimeout and setImmediate
setTimeout schedules a function to run after a minimum delay. Even with 0ms, the callback waits until the Call Stack is empty. setImmediate runs after the current phase of the event loop completes but before timers. Understanding the order of these is essential for debugging async code.
setTimeout(() => { console.log('Timeout (0ms)'); }, 0); setImmediate(() => { console.log('Immediate'); }); console.log('Synchronous code');
Immediate
Timeout (0ms)
process.nextTick
process.nextTick has the HIGHEST priority of all async operations. It runs immediately after the current operation completes, before the event loop continues. This is useful when you need to defer execution but still want it to happen before any I/O or timers.
console.log('1. Start'); process.nextTick(() => { console.log('2. nextTick - HIGHEST priority'); }); setTimeout(() => { console.log('4. Timeout runs last'); }, 0); Promise.resolve().then(() => { console.log('3. Promise - High priority'); }); console.log('5. End');
5. End
2. nextTick - HIGHEST priority
3. Promise - High priority
4. Timeout runs last
Microtasks vs Macrotasks
Not all async tasks are equal. Microtasks (Promises, process.nextTick) have priority over Macrotasks (setTimeout, setInterval, I/O). The Event Loop clears the entire Microtask queue before taking a single Macrotask. This is why Promises always run before timers, even if the timer delay is zero.
Knowledge Check
Ready to test your understanding of 2. The Event Loop & Async Architecture?