# Node.js Event Loop & Architecture

> How does the Node.js event loop work, what are its phases, and how is it different from the browser event loop?

Canonical: https://www.internhack.in/learn/interview/nodejs-interview/node-event-loop
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

How does the Node.js event loop work, what are its phases, and how is it different from the browser event loop?

## Answer

The Node.js event loop is a loop run by libuv on the main thread that repeatedly picks up completed I/O and timer events and runs their JavaScript callbacks, one at a time. Your JavaScript runs on a single thread, but the actual I/O (sockets, files, DNS, crypto) is done by the operating system or by libuv's thread pool, so one Node process can juggle thousands of concurrent connections without blocking.

### The six phases of one loop iteration

Each pass through the loop (a "tick") visits these phases in order, and each phase has its own FIFO queue of callbacks:

1. **Timers**: runs callbacks from `setTimeout` and `setInterval` whose threshold has passed.
2. **Pending callbacks**: some system-level I/O callbacks deferred from the previous iteration (for example certain TCP errors).
3. **Idle / prepare**: internal to libuv.
4. **Poll**: fetches new I/O events and runs their callbacks (a socket received data, a file read finished). If nothing else is scheduled, the loop waits here for I/O.
5. **Check**: runs `setImmediate` callbacks, right after poll.
6. **Close callbacks**: runs things like `socket.on('close')`.

Between every individual callback, Node drains the **microtask queues**: first the `process.nextTick` queue, then the Promise queue (`.then`, `await` continuations, `queueMicrotask`). That is why a resolved Promise always runs before the next timer, and why a recursive `process.nextTick` can starve the loop completely.

Since Node 20 (libuv 1.45), timers are checked only after the poll phase rather than both before and after it. This rarely changes application code, but it is why old blog posts sometimes describe slightly different ordering.

### What actually runs off the main thread

- **Network I/O** (TCP, HTTP, UDP) uses the OS's async mechanisms: epoll on Linux, kqueue on macOS, IOCP on Windows. No thread pool involved.
- **File system, `dns.lookup`, `crypto.pbkdf2`, `zlib`** and a few others run on libuv's thread pool, which has **4 threads by default** (change it with `UV_THREADPOOL_SIZE`, max 1024).
- **Your JavaScript** always runs on the main thread. A 200 ms synchronous loop in one request handler freezes every other user for 200 ms.

### Node vs browser event loop

| Aspect | Node.js | Browser |
| --- | --- | --- |
| Implemented by | libuv | The browser (per HTML spec) |
| Macrotask structure | Six named phases | Task queues chosen by the browser |
| Extra queues | `process.nextTick`, `setImmediate` | `requestAnimationFrame`, rendering steps |
| Rendering | None | Paint can happen between tasks |
| Microtasks | Drained between each callback | Drained after each task |

The big practical difference: browsers interleave rendering with tasks, so a long task causes visible jank. Node has no rendering, so a long task instead causes latency spikes and timeouts for every concurrent request.

### Common gotchas

- `setTimeout(fn, 0)` vs `setImmediate(fn)` in the main module: the order is **not guaranteed**, because it depends on how fast the loop starts. Inside an I/O callback, `setImmediate` always runs first.
- In an ES module, top-level code is itself evaluated asynchronously, so a Promise callback can print before `process.nextTick`. In CommonJS, `nextTick` wins.
- Sync APIs (`fs.readFileSync`, `crypto.pbkdf2Sync`, a huge `JSON.parse`) block the loop. Use the async version, stream, or move CPU work to `worker_threads`.
- Monitor loop health in production with `perf_hooks.monitorEventLoopDelay()`; a rising p99 delay is often the first sign of a blocking bug.

**One iteration of the Node.js event loop. Microtasks (nextTick, then Promises) are drained between every callback in every phase.**

1. **Timers**: Expired setTimeout and setInterval callbacks run.
2. **Pending callbacks**: Deferred system I/O callbacks from the last tick.
3. **Idle / prepare**: Internal libuv housekeeping.
4. **Poll**: Collect new I/O events and run their callbacks; wait here if idle.
5. **Check**: setImmediate callbacks run.
6. **Close callbacks**: Handlers such as socket.on('close') run.

## Code examples

### Predicting the event loop order

```
// order.cjs  (run with: node order.cjs)
const fs = require('node:fs');

console.log('1: sync');
setTimeout(() => console.log('timeout (main)'), 0);
setImmediate(() => console.log('immediate (main)'));
process.nextTick(() => console.log('2: nextTick'));
Promise.resolve().then(() => console.log('3: promise'));
console.log('1b: sync');

// Inside an I/O callback the order IS deterministic
fs.readFile(__filename, () => {
  setTimeout(() => console.log('5: timeout (in I/O)'), 0);
  setImmediate(() => console.log('4: immediate (in I/O)'));
});
```

Synchronous code runs first, then the nextTick queue, then Promise microtasks. Inside an I/O callback the check phase comes before the next timers phase, so setImmediate reliably beats setTimeout there.

### Blocking the Event Loop (Anti-Pattern)

```
const express = require('express');
const app = express();

// BAD: blocks the event loop for ALL users
app.get('/hash', (req, res) => {
  const crypto = require('crypto');
  // This takes ~500ms and blocks everything
  const hash = crypto.pbkdf2Sync(
    'password', 'salt', 100000, 64, 'sha512'
  );
  res.json({ hash: hash.toString('hex') });
});

// GOOD: non-blocking with async version
app.get('/hash-async', async (req, res) => {
  const crypto = require('crypto');
  const hash = await new Promise((resolve, reject) => {
    crypto.pbkdf2(
      'password', 'salt', 100000, 64, 'sha512',
      (err, key) => err ? reject(err) : resolve(key)
    );
  });
  res.json({ hash: hash.toString('hex') });
});
```

A synchronous pbkdf2 with 100,000 iterations blocks the loop, so every other request waits. The async version runs on libuv's thread pool and the main thread keeps serving traffic.

### Worker Threads for CPU-Intensive Work

```
// main.js
const { Worker } = require('worker_threads');

function runWorker(data) {
  return new Promise((resolve, reject) => {
    const worker = new Worker('./worker.js', {
      workerData: data,
    });
    worker.on('message', resolve);
    worker.on('error', reject);
  });
}

// worker.js
const { workerData, parentPort } = require('worker_threads');

// CPU-heavy computation runs in separate thread
function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

const result = fibonacci(workerData);
parentPort.postMessage(result);
```

Worker threads run JavaScript on separate V8 isolates, so CPU-heavy work like this does not block the main event loop. Shown as two files; in practice reuse workers through a pool instead of creating one per request.

## Key points

- Your JavaScript runs on one thread; I/O is handled by the OS or libuv's thread pool (4 threads by default, set by UV_THREADPOOL_SIZE).
- Phase order: timers, pending callbacks, idle/prepare, poll, check, close callbacks.
- process.nextTick queue drains before the Promise microtask queue, and both drain between callbacks.
- setTimeout(0) vs setImmediate is nondeterministic in the main module but setImmediate wins inside I/O callbacks.
- Any synchronous CPU work blocks every concurrent request; offload it to worker_threads.

## Common follow-up questions

- What is the difference between process.nextTick and setImmediate, and when would you use each?
- Which operations use the libuv thread pool, and what happens when all 4 threads are busy?
- How would you detect event loop blocking in a production service?
- When would you choose worker_threads over child_process?

## Interview tips

- Draw the phases and say where microtasks fit; it shows you understand more than "Node is single-threaded".
- Correct the common myth: Node is single-threaded for JavaScript, not for I/O.
- Mention a real symptom you have seen or would watch for, such as p99 latency rising because of a sync call in a hot path.
- If you are asked to predict output, call out the setTimeout vs setImmediate nondeterminism; interviewers often test for it.

## Concepts covered

Event Loop, libuv, Microtask Queue, process.nextTick, setImmediate, Thread Pool

Next: [Streams & Buffers](https://www.internhack.in/learn/interview/nodejs-interview/node-streams-buffers) · [All of Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)

## More Node.js Interview questions

- [REST API Design & Middleware](https://www.internhack.in/learn/interview/nodejs-interview/node-rest-api-design)
- [Node.js Basics & Runtime](https://www.internhack.in/learn/interview/nodejs-interview/node-basics-runtime)
- [Module System (CJS vs ESM)](https://www.internhack.in/learn/interview/nodejs-interview/node-module-system)
- [File System Operations](https://www.internhack.in/learn/interview/nodejs-interview/node-fs-operations)
- [Path & OS Modules](https://www.internhack.in/learn/interview/nodejs-interview/node-path-os)
- [HTTP Module & Server Creation](https://www.internhack.in/learn/interview/nodejs-interview/node-http-server)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)
