Event Loop & Architecture
How Node.js handles concurrency with a single thread
Node.js Event Loop
Node.js is single-threaded but non-blocking. It uses an event-driven architecture with libuv handling I/O operations in a thread pool, while the main thread processes callbacks via the event loop.
Event Loop Phases
typescript
// Event Loop Phases Demo
console.log('1: sync start');
setTimeout(() => console.log('2: setTimeout'), 0);
setImmediate(() => console.log('3: setImmediate'));
process.nextTick(() => console.log('4: nextTick'));
Promise.resolve().then(() => console.log('5: Promise'));
console.log('6: sync end');
// Output: 1, 6, 4, 5, 2, 3
// nextTick > microtasks > macrotasks💬 Why is Node.js single-threaded but still fast?
Node delegates I/O operations (file reads, network requests, DNS) to libuv's thread pool (default 4 threads). The main thread never blocks — it registers callbacks and processes them when I/O completes. This is efficient for I/O-heavy workloads but NOT for CPU-heavy tasks.