One of the most common questions asked in backend interviews is: "If Node.js is single-threaded, how does it handle thousands of concurrent connections?" The answer lies in the Event Loop. Understanding this concept is crucial for writing performant Node.js applications and avoiding blocking code.

1 The Single-Threaded Myth

It is true that JavaScript executes on a single main thread. However, Node.js itself is not entirely single-threaded. It uses the C++ library libuv to handle asynchronous I/O operations. When Node.js needs to perform a heavy task (like reading a file or making a network request), it offloads that work to libuv's thread pool, allowing the main thread to continue executing other code.

2 The Phases of the Event Loop

The event loop is essentially an infinite loop that waits for tasks, executes them, and then sleeps until more tasks arrive. It operates in several distinct phases:

  • Timers: Executes callbacks scheduled by setTimeout() and setInterval().
  • Pending Callbacks: Executes I/O callbacks deferred to the next loop iteration.
  • Idle, Prepare: Used internally by Node.js.
  • Poll: Retrieves new I/O events; executes I/O related callbacks (almost all with the exception of close callbacks, timers, and setImmediate()).
  • Check: Executes setImmediate() callbacks.
  • Close Callbacks: Executes close events (e.g., socket.on('close', ...)).
3 The Peril of Blocking the Event Loop

Because there is only one thread executing JavaScript, if you execute a CPU-intensive operation (like a massive synchronous while loop, heavy cryptography, or image processing) directly on the main thread, the Event Loop freezes. No other incoming HTTP requests, WebSocket messages, or database responses can be processed while this operation runs.

// DANGEROUS: This freezes the entire Node.js server for all concurrent users! app.get('/heavy', (req, res) => { let count = 0; for (let i = 0; i < 1e10; i++) { count += i; } // 100% CPU lock res.send({ count }); });
Golden Backend Rule: "Don't block the event loop!" Always use non-blocking asynchronous APIs (e.g., fs.promises.readFile instead of fs.readFileSync), and offload CPU-heavy computation to Worker Threads or external microservices.
4 Microtasks vs Macrotasks (The Hidden Priority Queue)

In technical interviews, senior engineers will test your knowledge on where process.nextTick() and Promise.then() execute.

  • Microtask Queue: Holds process.nextTick() callbacks (highest priority) and resolved Promise callbacks (second priority).
  • Macrotasks: Scheduled callbacks in Timers, I/O Poll, and Check (setImmediate) phases.
Crucial Execution Rule: The Microtask queue is drained immediately after the currently running operation completes, and between every single phase transition of the Event Loop! A recursive process.nextTick() will completely starve the Event Loop of I/O.
5 The Classic Event Loop Interview Puzzle

Can you predict the exact output order of this code? This is asked in 9 out of 10 Node.js screening rounds:

console.log('1: Synchronous Script Start'); setTimeout(() => { console.log('2: setTimeout (Timer Phase)'); }, 0); setImmediate(() => { console.log('3: setImmediate (Check Phase)'); }); Promise.resolve().then(() => { console.log('4: Promise Microtask'); }); process.nextTick(() => { console.log('5: nextTick Microtask'); }); console.log('6: Synchronous Script End');

Execution Order & Explanation:

  1. 1: Synchronous Script Start — Synchronous code executes immediately on call stack.
  2. 6: Synchronous Script End — Synchronous call stack continues to completion.
  3. 5: nextTick Microtask — process.nextTick queue executes before all other microtasks.
  4. 4: Promise Microtask — Promise microtask queue executes next.
  5. 2: setTimeout & 3: setImmediate — Macrotask phases execute based on event loop cycle.
6 Configuring the Libuv Thread Pool

By default, libuv provides a thread pool of 4 worker threads for handling asynchronous tasks that cannot be performed non-blockingly at the OS kernel level (such as fs file system operations, crypto.pbkdf2, and DNS lookups).

In high-throughput enterprise servers with heavy file processing or cryptographic hashing, 4 threads can easily become a bottleneck. You can scale the thread pool up to 128 threads using the environment variable:

// Set at application bootstrap before any async task runs process.env.UV_THREADPOOL_SIZE = 16;

💡 తెలుగులో ఈవెంట్ లూప్ వివరణ (Node.js Event Loop in Telugu)

Node.js సింగిల్-థ్రెడెడ్ అయినప్పటికీ వేలకొద్దీ కనెక్షన్లను ఏకకాలంలో ఎలా హ్యాండిల్ చేస్తుందనేది చాలా మందికి అర్థం కాని ప్రశ్న.

  • సింగిల్ థ్రెడ్ మరియు libuv: మీ జావాస్క్రిప్ట్ కోడ్ కేవలం ఒకే థ్రెడ్ పై నడుస్తుంది. కానీ ఫైల్ రీడింగ్ లేదా డేటాబేస్ నెట్‌వర్క్ కాల్స్ వంటి భారీ పనులను బ్యాక్‌గ్రౌండ్‌లోని libuv థ్రెడ్ పూల్ కి అప్పగిస్తుంది.
  • ఈవెంట్ లూప్ ఫేజెస్: టైమర్స్ (Timers), పోల్ (Poll), మరియు చెక్ (Check) అనే దశల ద్వారా ఈవెంట్ లూప్ ఎడతెగకుండా తిరుగుతూ పూర్తయిన టాస్క్‌ల కాల్‌బ్యాక్‌లను కాల్ స్టాక్‌లోకి పంపుతుంది.
  • ప్రొడక్షన్ జాగ్రత్త: భారీ లూప్‌లను లేదా సింక్రోనస్ కోడ్‌ను నేరుగా రాయడం వల్ల సర్వర్ మొత్తం ఫ్రీజ్ అయిపోతుంది. ఎల్లప్పుడూ అస్రింక్రోనస్ పద్ధతులనే వాడాలి.

మరింత ప్రాక్టికల్ బ్యాకెండ్ ఆర్కిటెక్చర్ కొరకు మా Node.js & Express లైవ్ కోర్సు చూడండి.

🚀
Master Enterprise Backend Scalability (KSR Tip)
Once you truly master how the Event Loop delegates I/O to the OS kernel through epoll/kqueue, you can design Node.js microservices capable of handling millions of real-time WebSocket and HTTP connections effortlessly.