Node.js Basics
Node.js Architecture and Event Loop
Node runs your JavaScript on a single thread and hands slow operations — file reads, network calls, DNS — to the operating system or a thread pool. The event loop picks up completed operations and runs their callbacks, which is how one thread serves thousands of connections.
What is Architecture and Event Loop in Node.js?
Node runs your JavaScript on a single thread and hands slow operations — file reads, network calls, DNS — to the operating system or a thread pool. The event loop picks up completed operations and runs their callbacks, which is how one thread serves thousands of connections.
Why Architecture and Event Loop matters
The event loop explains Node’s greatest strength and its sharpest edge: it handles enormous I/O concurrency, but any long synchronous computation freezes the entire server for every user.
Architecture and Event Loop example
console.log('1 — synchronous');
setTimeout(() => console.log('4 — timer'), 0);
Promise.resolve().then(() => console.log('3 — microtask'));
process.nextTick(() => console.log('2 — nextTick'));
// Output: 1, 2, 3, 4How this works
Synchronous code runs first. Then process.nextTick callbacks, then promise microtasks, and only afterwards does the event loop move on to timers — which is why a zero-millisecond timeout still runs last.
Key points to remember
- Microtasks (promises, nextTick) run between every phase, not only at the end.
- The libuv thread pool defaults to four threads and handles fs and crypto work.
- Blocking the loop blocks every connected client, not just one.
Event loop phases in order
| Phase | Handles |
|---|---|
| timers | setTimeout and setInterval callbacks |
| pending callbacks | deferred system callbacks |
| poll | incoming I/O events — where Node waits |
| check | setImmediate callbacks |
| close | close events such as socket.on("close") |
Common mistakes with Architecture and Event Loop
- A large synchronous JSON.parse or loop, which stalls all requests.
- Using fs.readFileSync inside a request handler.
- Assuming setTimeout(fn, 0) runs immediately.
Node.js Architecture and Event Loop— Interview Questions & FAQs
Is Node.js single-threaded?+
Your JavaScript runs on one thread, but Node uses a thread pool and operating-system async APIs for I/O. So it is single-threaded for application code and multi-threaded underneath.
What blocks the Node.js event loop?+
Any long synchronous work: tight loops, synchronous file reads, large JSON parsing, synchronous crypto, or complex regular expressions. Move that work to a worker thread or a separate process.
