# Node.js Event Loop - A Deep and practical Guide

# The Node.js Event Loop, Explained Properly

*From "Node is single-threaded" to a production-grade mental model including V8, libuv, microtasks, phases, the thread pool, Worker Threads, and streams.*

---

## What is different in this article?

Most explanations of the Node.js event loop fall into one of two traps. Either they stop at "Node is single-threaded and non-blocking, so it's fast," which is too shallow to be useful. Or they dump a list of phase names (`timers`, `poll`, `check`...) with no connection to what actually happens when a request hits your server.

This article builds the picture step by step. By the end you should be able to:

- **If you're a beginner -** Explain what the event loop is and why Node can serve thousands of connections.
- **If you're a working developer -** Trace exactly what happens to a real HTTP + database request, and predict the order of `console.log` output.
- **If you're preparing for senior interviews or debugging production -** Learn about libuv, the thread pool, OS-level I/O, microtasks, blocking, Worker Threads, and the exceptions to every "rule."

If you remember only one sentence from this article, make it this one:

> **The event loop does not perform asynchronous work. It coordinates *when* your JavaScript callbacks and continuations get to run after that work becomes ready.**

Let's dive deep to understand this.

---

## 1\. Is Node.js really single-threaded?

The honest answer is: **your JavaScript is, but Node.js is not.**

- Your application's JavaScript normally runs on **one main thread**.
- **V8** is the engine that executes that JavaScript.
- **libuv** is the C library that provides the event loop and the infrastructure for asynchronous I/O.
- Some operations use **operating-system async mechanisms** (for example, network sockets).
- Some operations use **libuv's worker thread pool** (for example, certain file system, DNS, and crypto calls).
- **Worker Threads** let you run additional JavaScript in parallel, each with its own isolated runtime.

So "Node is single-threaded" is a useful *approximation* for how your code executes, but a misleading statement about the runtime as a whole.

---

## 2\. The architecture: V8 + Node APIs + libuv

Node.js is not simply "V8 plus an event loop." There is a larger runtime underneath. Here is the conceptual model:

```plaintext
                Node.js Application
                       │
                       ▼
                  V8 Engine
              (executes JavaScript)
                       │
                       ▼
              Node.js Runtime APIs
          (fs, http, net, crypto, ...)
                       │
                       ▼
                    libuv
        ┌──────────────┼──────────────┐
        │              │              │
   Event Loop       OS I/O       Thread Pool
        │              │              │
        │           Network          fs
        │             I/O          crypto
        │                          DNS
        ▼
   JavaScript
   callbacks /
   continuations
```

Read it top to bottom:

1. Your code runs in **V8**.
2. When you call something like `fs.readFile` or `http.get`, you are calling a **Node runtime API**.
3. That API hands the work to **libuv**, which decides *how* the work gets done line askong the OS to notify when a socket is readable, or hand a task to a worker thread.
4. When the work completes, libuv tells the **event loop**, which schedules your callback or Promise continuation to run on the main JavaScript thread.

---

## 3\. Concurrency vs. parallelism

These two words get used interchangeably, but they mean different things, and the difference is the whole reason Node works.

- **Concurrency** means *making progress on multiple tasks over the same period of time*, by interleaving them.
- **Parallelism** means *literally executing multiple things at the same instant*, on multiple CPU cores.

Imagine three requests arriving close together:

```plaintext
Request A  →  DB query   →  waiting...
Request B  →  DB query   →  waiting...
Request C  →  API call   →  waiting...
```

What the main JavaScript thread does:

```plaintext
Main JS thread
──────────────────────────────────────────────
A starts → B starts → C starts → handles other work → ...
──────────────────────────────────────────────
```

The JavaScript for A and B is **not** executing simultaneously. Instead, Node interleaves work *around the waiting*. A request spends most of its life waiting on a database or network call, and while it waits, the main thread is free to start or finish something else.

That is why Node is excellent for **I/O-heavy workloads**: APIs, proxies, chat servers, anything where the time is spent waiting on other systems rather than computing.

It is also why **CPU-heavy JavaScript is different**. Waiting can be interleaved. Computing cannot. We'll come back to that in the second half.

---

## 4\. What actually happens when an HTTP request arrives?

Let's trace a realistic request from end to end.

```plaintext
Client
  │
  ▼
HTTP Server
  │
  ▼
JavaScript request handler
  │
  ▼
await db.query(...)
  │
  ├── the DB query runs externally (in the database server)
  │
  ▼
JavaScript function suspends at await
  │
  ▼
Main JS thread is now free
  │
  ▼
Other requests execute
  │
  ▼
DB result arrives
  │
  ▼
Promise is fulfilled
  │
  ▼
Continuation after await becomes ready
  │
  ▼
JavaScript executes it
```

The most important line in that diagram is *"the DB query runs externally."* Your Node process sends a request over a socket and then has nothing to do for this particular handler until the answer comes back. So it doesn't sit there. It moves on.

---

## 5\. `await` does not block Node.js

This is the single most common misconception, so let's be precise. Consider:

```js
async function handler() {
  console.log("A");

  const result = await db.query("SELECT * FROM users");

  console.log("B");
}
```

When execution reaches `await db.query(...)`, **the Node.js process does not stop.** What happens instead:

- **This one async function pauses.** Its state is saved.
- The **Promise** represents the still-pending result.
- The **main JS thread is released** and can run other callbacks.
- When the database responds, the Promise is fulfilled and the **continuation** (everything after the `await`) becomes eligible to run.

Think of `await` as *"pause me, not the program."*

Two corollaries worth stating explicitly:

- `async/await` does **not** create a new thread.
- `async/await` does **not** make CPU-heavy code non-blocking. It only helps when there is something to *wait* for.

---

## 6\. Two requests, one thread: Request A and Request B

Here is the classic picture:

```plaintext
Request A → DB query A → waiting
Request B → DB query B → waiting

Main JS thread
──────────────────────────────────────────
A starts
B starts
other callbacks
other requests
microtasks
...
──────────────────────────────────────────
```

Later, as the database answers:

```plaintext
DB A completes → A's continuation becomes ready
DB B completes → B's continuation becomes ready
```

Notice what the diagram does *not* promise: **the order of completion is not necessarily the order of arrival.** If B's query is cheap and A's is expensive, B finishes first. Production code must never assume requests complete in the order they started. This matters for logging, for shared mutable state, and for any code that makes assumptions about sequencing across requests.

---

## 7\. Promise mechanics

Before we go near the event loop phases, we need to understand Promises, because they are scheduled differently from timers and I/O.

```js
console.log("A");

Promise.resolve().then(() => {
  console.log("B");
});

console.log("C");
```

Output:

```plaintext
A
C
B
```

Why isn't it `A B C`? Because `.then()` callbacks never run immediately, even when the Promise is already resolved. They are placed in a queue and run **after the current synchronous code finishes**. That queue is the **microtask queue**.

---

## 8\. Microtasks: two queues, one rule

Node has two kinds of microtask-style queues you need to know:

**Promise microtasks**

```js
Promise.resolve().then(() => {
  console.log("Promise");
});
```

`process.nextTick` **callbacks**

```js
process.nextTick(() => {
  console.log("nextTick");
});
```

After the current JavaScript callback finishes, Node drains them in a specific order:

```plaintext
Current JavaScript callback finishes
        │
        ▼
process.nextTick queue   (drained first)
        │
        ▼
Promise microtask queue  (drained next)
        │
        ▼
Continue event-loop processing
```

And here is a correction to a very common oversimplification:

> **Microtasks are not event-loop phases.** They run *between* callbacks, at checkpoints, regardless of which phase you are currently in.

If you've seen diagrams that put "Promises" as a box inside the phase cycle, that diagram is misleading.

---

## 9\. `process.nextTick()` vs. Promises

Put both together and predict the output:

```js
console.log("A");

process.nextTick(() => {
  console.log("nextTick");
});

Promise.resolve().then(() => {
  console.log("Promise");
});

console.log("B");
```

Output (in a CommonJS script):

```plaintext
A
B
nextTick
Promise
```

The reasoning, step by step:

1. `A` and `B` are synchronous, so they print first, in order.
2. The `nextTick` callback and the Promise callback were both *queued* during that synchronous run.
3. When the synchronous code ends, Node drains the `nextTick` **queue first**, then the **Promise microtask queue**.

---

## 10\. `process.nextTick()` starvation

This deserves its own production warning.

```js
function loop() {
  process.nextTick(loop);
}

loop();
```

Every time the `nextTick` queue is drained, a new callback is added to it. Node keeps processing them and **never gets to continue to the normal event-loop phases**. Timers don't fire. I/O callbacks don't run. The process looks alive but is effectively frozen.

This demonstrates something subtle:

> **Asynchronous does not automatically mean non-blocking.** A callback chain can still monopolize the runtime.

Recursive Promise chains (`.then(() => loop())` forever) can starve the loop in the same way. If you need to yield to I/O between chunks of work, `setImmediate()` is the right tool, and that brings us to the event loop itself.

---

## 11\. The event loop phases

Now we can finally open the loop itself. Each iteration (often called a *tick*) moves through a fixed sequence of phases:

```plaintext
┌─────────────────────┐
│       timers        │  setTimeout / setInterval callbacks
├─────────────────────┤
│  pending callbacks  │  some deferred system-level callbacks
├─────────────────────┤
│   idle / prepare    │  internal use
├─────────────────────┤
│        poll         │  retrieve I/O events, run I/O callbacks
├─────────────────────┤
│        check        │  setImmediate callbacks
├─────────────────────┤
│  close callbacks    │  socket.on('close'), etc.
└─────────────────────┘
          │
          └── repeat
```

You do **not** need to memorize every internal detail. For practical Node.js development, four phases matter:

- **timers:** runs expired `setTimeout` / `setInterval` callbacks.
- **poll:** gets new I/O events and runs I/O callbacks. This is where most server work happens.
- **check:** runs `setImmediate` callbacks.
- **close callbacks:** cleanup, such as `socket.on("close", ...)`.

And remember from section 8: between every one of these callbacks, Node drains the `nextTick` queue and then the Promise queue.

---

## 12\. `setTimeout()`

```js
setTimeout(() => {
  console.log("timeout");
}, 0);
```

A common mistake is reading `setTimeout(fn, 0)` as *"run immediately."* It actually means:

> Make this callback **eligible** once the timer threshold has elapsed, and run it when the event loop next reaches the timers phase.

So `0` is a minimum delay, not an execution guarantee. If the main thread is busy, or the loop is in a different phase, the callback waits. (Node also treats a `0` delay as `1` ms in practice.)

---

## 13\. `setImmediate()`

```js
setImmediate(() => {
  console.log("immediate");
});
```

`setImmediate` schedules its callback for the **check phase**, which comes right after the poll phase in the same loop iteration. The name is confusing: it doesn't mean "before everything else," it means "right after the current poll phase finishes."

---

## 14\. `setTimeout(0)` vs. `setImmediate()`: the ordering trap

This comparison is where many articles go wrong, so let's be careful. Both of these statements are **false**:

- ❌ "`setTimeout(0)` always runs first."
- ❌ "`setImmediate` always runs first."

The real answer depends on **where you call them from**.

**From the main module**, the order is non-deterministic. It depends on how long process startup took and whether 1 ms has elapsed by the time the loop first reaches the timers phase:

```js
// main script: order can vary between runs
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
```

**From inside an I/O callback**, the order is deterministic: `setImmediate` runs first.

```js
const fs = require("fs");

fs.readFile(__filename, () => {
  setTimeout(() => console.log("timeout"), 0);
  setImmediate(() => console.log("immediate"));
});

// Always prints:
// immediate
// timeout
```

Why? An I/O callback runs during the **poll phase**. The next phase after poll is **check**, so `setImmediate` fires right away. The timer has to wait for the *next* loop iteration to reach the timers phase again.

The takeaway: never write code that depends on the relative order of these two unless you control the context, and when you do, you now know which way it falls.

---

## 15\. The poll phase, the check phase, and close callbacks

### Poll

The poll phase is the heart of a server. It:

- retrieves new I/O events (a socket became readable, a connection arrived),
- runs the callbacks associated with those events,
- and, when nothing else is scheduled, may **wait** for new I/O instead of spinning the CPU.

This is where the abstract event loop meets real network behavior: an incoming HTTP request becomes a poll-phase event, which ends up invoking your request handler.

### Check

After poll, the loop enters **check**, where `setImmediate` callbacks run. That's why `setImmediate` is the natural way to say "do this right after the current I/O work, before timers."

### Close callbacks

When a handle such as a socket or server is closed abruptly, its close event is emitted here:

```js
socket.on("close", () => {
  console.log("closed");
});
```

It's the last phase before the loop wraps around to timers again.

---

## 16\. Putting it all together: one realistic request

Here is a handler that mixes everything we've covered:

```js
app.get("/users", async (req, res) => {
  console.log("Request started");

  setTimeout(() => {
    console.log("timeout");
  }, 0);

  setImmediate(() => {
    console.log("immediate");
  });

  Promise.resolve().then(() => {
    console.log("promise");
  });

  const users = await db.query("SELECT * FROM users");

  console.log("DB completed");

  res.json(users);
});
```

Typical output:

```plaintext
Request started
promise
immediate
timeout
DB completed
```

Let's walk through it:

1. **The request arrives (poll phase).** The socket becomes readable, libuv reports it, and Node invokes the handler. We are now inside an I/O callback.
2. **Synchronous code runs.** `"Request started"` prints. The timer and the immediate are *scheduled*. The Promise callback is *queued as a microtask*. Then `db.query(...)` is called and sends the query to the database.
3. `await` **suspends the function.** The handler returns a pending Promise to its caller. The main thread is free again.
4. **Microtasks drain.** Before the loop moves on, the queued Promise callback runs: `"promise"` prints.
5. **The loop moves from poll to check.** `setImmediate` fires: `"immediate"` prints.
6. **Next iteration, timers phase.** The 1 ms timer has expired: `"timeout"` prints.
7. **Meanwhile, the database works externally.** When its response arrives, it shows up as a poll-phase I/O event. The Promise is fulfilled, the continuation becomes ready, and `"DB completed"` prints. `res.json(users)` then writes the response.

Two honest caveats: the exact position of `"DB completed"` depends on how fast your database answers (a sub-millisecond reply could, in theory, land earlier), and while all this happens for request A, the loop is also happily servicing request B, C, and D between the steps.

---

## 17\. Why database queries don't run "on the event loop"

A tempting but wrong mental model:

```plaintext
Event Loop
   ↓
runs DB query
```

A better one:

```plaintext
Node.js
   ↓
DB driver
   ↓
Database server
   ↓
query execution
   ↓
result
   ↓
Node.js receives the result
   ↓
Promise fulfilled
   ↓
JS continuation runs
```

**The database performs the database computation.** Node sends bytes over a socket and later receives bytes back. The event loop only notices "data arrived on this socket" and schedules the JavaScript that cares about it.

That's also why a Node API in front of a slow query is rarely *CPU-bound*: your process is mostly waiting, which it does very cheaply.

---

## 18\. libuv, and where async work actually happens

libuv is the C library at the center of Node's asynchronous behavior. It provides:

- the **event loop** itself,
- **asynchronous I/O** integration with the operating system,
- **timers**,
- a **thread pool** for work that can't be done asynchronously by the OS,
- abstractions over OS-specific mechanisms (epoll on Linux, kqueue on macOS/BSD, IOCP on Windows).

So asynchronous work reaches completion by one of **two routes**, and confusing them is where many Node explanations become inaccurate.

### Route 1: OS-level asynchronous I/O

Network operations (TCP sockets, HTTP connections, most database connections) generally use the operating system's own readiness-notification facilities. libuv asks the OS, "tell me when this socket has data," and **no worker thread is consumed per connection**.

```plaintext
Network I/O
    ↓
OS async mechanism (epoll / kqueue / IOCP)
    ↓
libuv
    ↓
callback / Promise continuation
```

This is why one Node process can hold tens of thousands of idle connections open cheaply.

### Route 2: The libuv thread pool

Some operations don't have a good asynchronous OS interface, or are simply blocking work. For those, libuv runs the operation on a **worker thread** and reports back when it finishes.

```plaintext
Main JS thread
       │
       ▼
     libuv
       │
       ▼
Thread Pool
 ┌─────┼─────┐
 T1    T2    T3 ...
```

Examples that commonly use the pool:

- many **file system** operations,
- DNS lookups via `dns.lookup`,
- CPU-intensive **crypto** functions such as `pbkdf2`, `scrypt`, and `randomBytes`,
- **zlib** compression.

By default the pool has **4 threads** (adjustable with the `UV_THREADPOOL_SIZE` environment variable). That has a practical consequence: if you fire off many slow file or crypto operations at once, they queue up behind those four threads, even though your main thread is idle.

The critical accuracy point:

> **Not all asynchronous operations use the thread pool.** Network I/O mostly doesn't. Which operations use which route can vary by operation and platform, so avoid sweeping statements in either direction.

---

## 19\. Worker Threads

Worker Threads are a different thing from the libuv pool, and the two are frequently confused.

```js
const { Worker } = require("worker_threads");

const worker = new Worker("./heavy-task.js");
```

- The **libuv thread pool** runs *native* operations on behalf of Node's built-in APIs. You don't write code for it.
- **Worker Threads** run *your JavaScript* on another thread, each with its own V8 instance and event loop.

```plaintext
Main JS Thread
       │
       ├── normal application JS
       │
       └── Worker
             │
             └── another JS execution thread
```

Workers communicate with the main thread by passing messages (and can share memory via `SharedArrayBuffer`). Their main use case is **CPU-intensive work** that would otherwise block the main thread.

---

## 20\. When the main thread gets blocked: CPU-heavy JavaScript

Here's the scenario that breaks Node servers in production:

```js
app.get("/calculate", (req, res) => {
  const result = veryHeavyCalculation();

  res.json(result);
});
```

If `veryHeavyCalculation()` takes 10 seconds, this is what the main thread looks like:

```plaintext
Main JS thread
──────────────────────────────────────────
  Heavy calculation
  ██████████████████████████████
            BLOCKED
──────────────────────────────────────────
```

For those ten seconds, **no other JavaScript callback can run**. Not other requests, not timers, not health checks. Every user of that process experiences an outage. That's why CPU-heavy workloads can destroy Node's responsiveness even though the *I/O model* is excellent.

Wrapping the function in `async` does not help:

```js
app.get("/calculate", async (req, res) => {
  const result = veryHeavyCalculation(); // still blocks the thread
  res.json(result);
});
```

`async` only changes the return type. The computation is still synchronous JavaScript on the main thread.

### **The fix: move the heavy work to a Worker Thread**

A Worker Thread runs your JavaScript on a separate thread with its own V8 instance and event loop. The main thread hands the job over, keeps serving other requests, and picks up the result when the worker sends it back.

```javascript
// The server (main thread):
// server.js
const { Worker } = require("worker_threads");
const { once } = require("events");

async function runHeavyCalculation(input) {
  const worker = new Worker("./heavy-worker.js", { workerData: input });

  const [result] = await once(worker, "message");
  return result;
}

app.get("/calculate", async (req, res) => {
  try {
    const result = await runHeavyCalculation(req.query);
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// The worker (separate thread):

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

function veryHeavyCalculation(input) {
  // CPU-intensive work happens here, on the worker's own thread
}

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

### **How this prevents the blocking problem**

The handler still uses await, but now there is something real to wait for: a message from another thread. So await does what it was always meant to do, suspend the handler while the main thread is released.

**Compare the two situations:**

- **Without a worker:** the 10-second computation occupies the only JavaScript thread. /health, /users, and timers all wait.
- **With a worker:** the computation occupies a *different* thread. The main thread spends only a few milliseconds on each side of it (starting the job, sending the response), so other requests keep flowing.

This works because Worker Threads give you real **parallelism**, not just concurrency: the calculation and your other request handling execute at the same instant on different CPU cores.

### **Practical notes**

- **Starting a worker has a cost.** Creating a new worker per request, as the example does for clarity, adds startup time and memory. In production, use a **worker pool** (a fixed set of reusable workers, for example with the piscina library) and queue jobs onto it.
- **Data is copied between threads.** Messages are cloned with the structured clone algorithm. For large binary data, use **transferable objects** (such as ArrayBuffer) or SharedArrayBuffer to avoid copying.
- **Workers don't share your variables.** Each worker has its own isolated memory, so there are no data races on ordinary objects, but you also can't just reference main-thread state.
- **Workers are for CPU work, not I/O.** For database or network calls, plain async/await on the main thread is already the right tool.
- **Heavy and long-running at scale?** Consider a separate process or service, so a runaway computation can't take memory or CPU from your API process.

### Async I/O vs. CPU-heavy work

- **Async I/O** (database, HTTP, network, file system) is a great fit for Node, because Node can *wait* without blocking the main thread.
- **CPU-heavy work** (image processing, large JSON transformations, heavy hashing, complex computation) needs a different strategy: **Worker Threads**, a **separate process**, or a **separate service**.

This distinction is one of the most reliable senior-level interview questions in the Node ecosystem.

---

## 21\. Streams

Streams are Node's answer to a different problem: data that is too big, or arrives too slowly, to handle all at once. There are four kinds:

- **Readable streams:** a source of data (file read, incoming HTTP request).
- **Writable streams:** a destination (file write, HTTP response).
- **Duplex streams:** both readable and writable (a TCP socket).
- **Transform streams:** duplex streams that modify data as it passes through (compression, encryption).

Without streams, serving a large file looks like this:

```plaintext
Large file
   ↓
Load entire file into RAM
   ↓
Process
```

With streams:

```plaintext
Large file
   ↓
Read chunk
   ↓
Process chunk
   ↓
Write chunk
   ↓
Read next chunk
```

Memory use stays flat no matter how big the file is, and the first bytes reach the client sooner. In code:

```js
const fs = require("fs");
const zlib = require("zlib");
const { pipeline } = require("stream/promises");

await pipeline(
  fs.createReadStream("huge.log"),
  zlib.createGzip(),
  fs.createWriteStream("huge.log.gz")
);
```

Streams also fit Node's event-driven design naturally: each chunk arrival is an event, handled by a small callback, with the loop free to do other work between chunks.

---

## 22\. Backpressure

Streams introduce a new problem: what if the producer is faster than the consumer?

```plaintext
Producer (fast)
   ↓
████████████████████
   ↓
Consumer (slow)
```

**Without backpressure**, the producer keeps producing, the unconsumed data piles up in memory, and the process eventually slows down or crashes.

**With backpressure**, the system pushes back:

```plaintext
Producer
   ↓
pauses when the consumer's buffer is full
   ↓
Consumer catches up
   ↓
Producer resumes
```

In Node, `writable.write()` returns `false` when its internal buffer is full, and a `'drain'` event signals that it's safe to continue. If you use `pipe()` or, better, `stream.pipeline()`, this handshake is handled for you. If you write the loop by hand and ignore the return value of `write()`, you've quietly opted out of backpressure.

---

## 23\. Common misconceptions

Here are the myths this article set out to retire.

- ❌ **"Node.js is single-threaded."** Better: JavaScript normally executes on one main thread, but the runtime uses libuv, OS facilities, a worker pool, and optionally Worker Threads.
- ❌ **"**`async/await` **creates a new thread."** No. It is syntax over Promises.
- ❌ **"**`await` **blocks Node.js."** No. It suspends that one async function.
- ❌ **"The event loop executes the database query."** No. The database does, and Node coordinates.
- ❌ **"All async operations use the thread pool."** No. Network I/O mostly uses OS mechanisms.
- ❌ **"**`setTimeout(0)` **means execute immediately."** No. It means eligible after the threshold, when the loop reaches the timers phase.
- ❌ **"**`setImmediate()` **always runs before** `setTimeout(0)`**."** No. From the main module it varies. Inside an I/O callback it does run first.
- ❌ **"Promise callbacks are event-loop phases."** No. They are microtasks, run between callbacks.
- ❌ **"Async means parallel."** Not necessarily. Async is about not waiting idly; parallelism needs multiple threads or processes.
- ❌ **"CPU-heavy code becomes non-blocking inside an async function."** No. It still blocks the main thread.

---

## 24\. The complete request lifecycle

Here is the whole picture in one diagram. This should be your central mental model of Node.

```plaintext
                    CLIENT
                       │
                       ▼
                HTTP SERVER
                       │
                       ▼
              JS REQUEST HANDLER
                       │
             ┌─────────┴─────────┐
             │                   │
          Sync JS           Async operation
             │                   │
             │          ┌────────┴────────┐
             │          │                 │
             │       OS I/O         libuv thread pool
             │          │                 │
             │          └────────┬────────┘
             │                   │
             └──────────┬─────────┘
                        │
                  operation done
                        │
                        ▼
                Promise fulfilled
                        │
                        ▼
          Microtask / ready continuation
                        │
                        ▼
                  Main JS thread
                        │
                        ▼
                  HTTP response
                        │
                        ▼
                     CLIENT
```

Read it as: *synchronous work runs immediately; asynchronous work leaves the main thread by one of two routes; when it finishes, a continuation is scheduled back onto the one JavaScript thread; and the response goes out.*

---

## 25\. A production debugging mental model

When a Node service is slow, ask these questions in order:

1. **Is the main thread blocked?** Symptoms: *all* requests slow at once, timers firing late, health checks timing out. Suspects: heavy loops, large `JSON.parse`/`JSON.stringify`, synchronous `fs` or `crypto` calls, catastrophic regex backtracking. Measure *event loop delay* (for example with `perf_hooks.monitorEventLoopDelay()`).
2. **Is the thread pool saturated?** Symptoms: file system, DNS, or crypto calls get slow while network calls are fine. Consider `UV_THREADPOOL_SIZE`, or move the work elsewhere.
3. **Is it waiting on something external?** Symptoms: the loop is healthy, but individual requests are slow. Look at database latency, connection pool exhaustion, and downstream API timeouts.
4. **Is memory growing?** Suspects: missing backpressure, unbounded queues, buffering whole files instead of streaming.
5. **Is something starving the loop?** Suspects: recursive `nextTick` or Promise chains that never yield. Use `setImmediate` to give I/O a turn.

---

## 26\. The senior-level explanation

If you're asked to explain this in an interview, here is a concise version:

> Node.js executes application JavaScript on a main thread and uses the event loop to coordinate asynchronous work. Network I/O is integrated with operating-system facilities through libuv, while certain operations such as file system, DNS, and cryptographic work can use libuv's worker pool. When asynchronous work completes, its callback or Promise continuation becomes eligible for JavaScript execution. Microtasks such as `process.nextTick()` and Promise callbacks are processed at microtask checkpoints between callbacks. CPU-intensive JavaScript can block the main thread and should be moved to Worker Threads or separate services when appropriate.

And the single most important idea:

> **The event loop does not perform the asynchronous operation itself. It coordinates when JavaScript callbacks and continuations should execute after asynchronous work becomes ready.**

---

## Final cheat sheet

- **V8** runs your JavaScript. **libuv** provides the event loop, OS I/O integration, timers, and the thread pool.
- **Concurrency** is interleaving around waiting. **Parallelism** is simultaneous execution. Node gives you the first by default and the second via Worker Threads, processes, or the libuv pool.
- `await` suspends one function, never the process.
- **Microtask order:** current callback → `nextTick` queue → Promise queue → continue the loop. Microtasks are *not* phases.
- **Phases that matter:** timers → poll → check → close callbacks.
- `setTimeout(0)` **vs** `setImmediate()`**:** unpredictable from the main module; `setImmediate` first inside I/O callbacks.
- **Network I/O** usually uses OS mechanisms. **fs / DNS lookup / crypto / zlib** often use the 4-thread libuv pool.
- **CPU-heavy JS blocks everything.** Put it in Worker Threads or another process or service.
- **Streams** keep memory flat. **Backpressure** keeps fast producers from overwhelming slow consumers.
- **The event loop coordinates. It doesn't do the work.**
