If you've worked with JavaScript for a while, you probably already understand the event loop.
You know that this:
console.log('A');
Promise.resolve().then(() => {
console.log('B');
});
setTimeout(() => {
console.log('C');
}, 0);
console.log('D');
prints:
A
D
B
C
You probably have a mental model something like this:
Synchronous code
↓
Microtasks
↓
Tasks
↓
Microtasks
↓
Tasks
↓
...
That's a useful model for browser JavaScript.
Then you start writing a Node.js server.
And suddenly someone shows you this:
┌─────────────┐
│ timers │
└──────┬──────┘
↓
┌─────────────┐
│ pending │
│ callbacks │
└──────┬──────┘
↓
┌─────────────┐
│ poll │
└──────┬──────┘
↓
┌─────────────┐
│ check │
└──────┬──────┘
↓
┌─────────────┐
│ close │
└──────┬──────┘
│
└──────► timers
And you're told:
"This is the Node.js event loop."
Technically, yes.
But if you're coming from frontend JavaScript, this diagram raises more questions than it answers.
Where did the microtask queue go?
Where does Promise.then() run?
What is process.nextTick()?
Why does Node have poll and check?
And what exactly is the relationship between setTimeout() and setImmediate()?
The missing piece is that Node.js has a more detailed execution model than the browser model you're probably used to.
Once you connect the two models, the Node.js event loop becomes much easier to reason about.
Start With the Mental Model You Already Know
Let's start with the browser.
A simplified model is:
┌──────────────────────┐
│ JavaScript runs │
│ synchronously │
└──────────┬───────────┘
↓
┌──────────────────────┐
│ Microtask queue │
│ │
│ Promise.then() │
│ queueMicrotask() │
└──────────┬───────────┘
↓
┌──────────────────────┐
│ Next task / event │
└──────────────────────┘
The important idea isn't the exact terminology.
It's this:
JavaScript runs one piece of synchronous work at a time, then asynchronous work gets a chance to run.
Promises are especially important because their callbacks run as microtasks.
For example:
console.log('1');
Promise.resolve().then(() => {
console.log('3');
});
console.log('2');
The output is:
1
2
3
The Promise callback doesn't interrupt the synchronous code.
It waits until the current synchronous execution finishes.
That mental model still applies in Node.js.
But Node adds another layer.
Node.js Has Event Loop Phases
Node.js implements its event loop using libuv.
Instead of one generic "task queue", Node organizes much of its asynchronous work into several phases.
A simplified version is:
┌─────────────┐
│ timers │
└──────┬──────┘
↓
┌─────────────┐
│ pending │
│ callbacks │
└──────┬──────┘
↓
┌─────────────┐
│ idle/prepare│
└──────┬──────┘
↓
┌─────────────┐
│ poll │
└──────┬──────┘
↓
┌─────────────┐
│ check │
└──────┬──────┘
↓
┌─────────────┐
│ close │
└──────┬──────┘
│
└──────────► timers
These are the phases Node documents as part of its event loop. Each phase has its own responsibilities and callback queue.
You don't need to memorize every phase.
For most application code, three are particularly useful:
timers
poll
check
because they correspond to APIs you're likely to use:
setTimeout / setInterval
↓
timers
I/O callbacks
↓
poll
setImmediate
↓
check
So Where Did Promises Go?
This is the part that often makes the official diagram confusing to frontend developers.
Promise.then() isn't another event loop phase.
Neither is process.nextTick().
Think of them as a layer that sits around JavaScript callback execution, rather than as phases alongside timers, poll, and check.
A useful mental model is:
Node.js event loop
│
▼
┌─────────────────┐
│ Execute a │
│ JavaScript │
│ callback │
└────────┬────────┘
│
▼
┌─────────────────┐
│ nextTick queue │
└────────┬────────┘
│
▼
┌─────────────────┐
│ microtask queue │
└────────┬────────┘
│
▼
continue event loop
This is the bridge between the browser mental model and the Node.js model.
Node's own documentation explicitly notes that process.nextTick() is not technically part of the event loop. Its queue is processed after the current operation completes, regardless of which event-loop phase you're in.
That's why I prefer to draw nextTick and microtasks as a layer between JavaScript callbacks rather than as additional event-loop phases.
The Full Mental Model
Put the two pieces together:
Node.js Event Loop
│
▼
┌───────────────────────────┐
│ timers │
└─────────────┬─────────────┘
│
▼
nextTick queue
│
▼
microtask queue
│
▼
┌───────────────────────────┐
│ pending callbacks │
└─────────────┬─────────────┘
│
▼
nextTick queue
│
▼
microtask queue
│
▼
┌───────────────────────────┐
│ poll │
└─────────────┬─────────────┘
│
▼
nextTick queue
│
▼
microtask queue
│
▼
┌───────────────────────────┐
│ check │
└─────────────┬─────────────┘
│
▼
nextTick queue
│
▼
microtask queue
│
▼
┌───────────────────────────┐
│ close callbacks │
└───────────────────────────┘
Important: this is a teaching model, not a literal list of additional Node.js phases.
The important relationship is:
event-loop callback
↓
nextTick
↓
microtasks
↓
continue
Node's actual implementation has more nuanced scheduling boundaries, but this model gives you the right intuition for application-level JavaScript.
process.nextTick() Is Not setImmediate()
This is where Node gets particularly confusing.
Consider:
process.nextTick(() => {
console.log('nextTick');
});
setImmediate(() => {
console.log('immediate');
});
These APIs have very different positions in Node's execution model.
process.nextTick() runs before Node continues to the next event-loop phase.
setImmediate() schedules a callback for the check phase.
So conceptually:
Current callback
│
├── process.nextTick()
│
▼
nextTick queue
│
▼
microtasks
│
▼
continue event loop
│
...
▼
check phase
│
└── setImmediate()
This is why the name nextTick is confusing.
process.nextTick() doesn't mean:
"run on the next event-loop iteration."
It means something much closer to:
"run after the current operation, before the event loop continues."
Node's documentation makes the same distinction: process.nextTick() runs on the current phase's continuation, while setImmediate() runs on a subsequent event-loop iteration in the check phase.
Let's See It in Code
Here's a simple example:
console.log('1: sync');
setTimeout(() => {
console.log('5: setTimeout');
}, 0);
Promise.resolve().then(() => {
console.log('4: Promise');
});
process.nextTick(() => {
console.log('3: nextTick');
});
console.log('2: sync end');
In a CommonJS context, the output is:
1: sync
2: sync end
3: nextTick
4: Promise
5: setTimeout
Why?
Start with the synchronous code:
console.log('1')
console.log('2')
Then the current operation completes.
Node processes:
nextTick
Then:
microtasks
Then it can continue into the event loop and reach:
timers
where the setTimeout() callback executes.
So:
sync
↓
nextTick
↓
Promise microtask
↓
timer
This is one of the most useful ordering rules to know when debugging Node.js code.
One Important Modern Node.js Detail: ESM
There is a subtlety here that is worth knowing if you're writing modern TypeScript.
The simple:
nextTick → Promise
ordering should not be presented as a universal law across every Node.js module context.
Node's ESM execution model can produce different observable ordering because ESM module evaluation itself is integrated with the microtask machinery.
So if you're experimenting with:
.mjs
or:
{
"type": "module"
}
don't assume every process.nextTick() / Promise example will behave exactly like a CommonJS script.
This is one reason I prefer teaching the underlying model rather than giving developers a list of "always happens before" rules.
What Is the Poll Phase?
If you're coming from frontend development, poll is probably the most important new concept.
The poll phase is where Node handles a large amount of I/O-related work.
Think:
HTTP requests
TCP sockets
file system callbacks
network activity
The exact implementation varies by operation, but conceptually:
Kernel / libuv
│
│ I/O completes
▼
poll queue
│
▼
JavaScript callback
This is one reason Node can handle thousands of concurrent network connections with a relatively small number of JavaScript threads.
The JavaScript thread isn't sitting there waiting for the network.
Instead:
JavaScript
│
│ "Tell me when this is ready."
▼
OS / libuv
│
│ work happens
▼
JavaScript callback
Node's event loop is essentially the mechanism that keeps bringing completed asynchronous work back into JavaScript execution.
Why setTimeout(fn, 0) Doesn't Mean "Run Now"
Frontend developers already know that:
setTimeout(fn, 0);
doesn't mean:
execute immediately.
It means roughly:
execute after the timer's threshold has elapsed and the event loop gets an opportunity to process it.
Node makes this especially important.
Suppose:
setTimeout(() => {
console.log('timeout');
}, 100);
The 100 milliseconds is a threshold, not a guarantee that the callback runs exactly at 100ms.
If the event loop is busy:
100ms threshold reached
│
▼
callback
│
│ but another callback is running
▼
wait longer
For example:
timer threshold = 100ms
poll callback starts at 95ms
│
│ runs for 20ms
▼
poll callback ends at 115ms
timer callback can now run
So the timer fires at approximately:
115ms
not 100ms.
Node's documentation explicitly describes timer delays as thresholds rather than exact execution times, and shows an example where a nominal 100ms timer executes after 105ms because an I/O callback took additional time.
setImmediate() Finally Makes Sense
Now consider:
setImmediate(() => {
console.log('immediate');
});
Where does it go?
The answer is:
poll
↓
check
↓
setImmediate
That's literally what the check phase is for.
This becomes particularly useful when you're inside an I/O callback:
import { readFile } from 'node:fs';
readFile('file.txt', () => {
setTimeout(() => {
console.log('timeout');
}, 0);
setImmediate(() => {
console.log('immediate');
});
});
Here the code is already executing as part of an I/O cycle.
The event loop is going through:
poll
↓
check
So setImmediate() runs before the timer.
Output:
immediate
timeout
Node's documentation specifically notes that setImmediate() is designed to execute after the current poll phase, and when both are scheduled inside an I/O cycle, setImmediate() executes before the timer.
But setTimeout(0) vs setImmediate() Is Not Always Deterministic
This is another common interview question:
Which runs first?
setTimeout(() => {
console.log('timeout');
}, 0);
setImmediate(() => {
console.log('immediate');
});
If you run this from the main module, the answer is:
It depends.
The exact order can depend on process timing.
But inside an I/O callback:
fs.readFile(..., () => {
setTimeout(...);
setImmediate(...);
});
setImmediate() wins.
So don't memorize:
setImmediate > setTimeout
as a universal rule.
The better rule is:
setImmediate()is tied to thecheckphase;setTimeout()is tied to the timers phase. Their relative order depends on where and when they are scheduled.
That's a much more useful mental model.
Node.js 20 Changed One Important Detail
There's another reason older event-loop diagrams can be misleading.
Starting with libuv 1.45.0, used by Node.js 20, timers are run after the poll phase in each event-loop iteration rather than both before and after polling as in older versions. This can affect the interaction between timers and setImmediate().
You may therefore find older diagrams that look like:
timers
↓
poll
↓
check
↓
timers
while newer explanations simplify the flow differently.
The exact libuv implementation matters when you're reasoning about edge cases.
But for application developers, the important abstraction remains:
timers → timer callbacks
poll → I/O callbacks
check → setImmediate callbacks
Don't let the implementation details obscure the programming model.
Why process.nextTick() Can Be Dangerous
There's one more reason to understand the distinction between nextTick and the event loop.
Consider:
function loop() {
process.nextTick(loop);
}
loop();
What happens?
You keep scheduling more nextTick callbacks.
Because Node processes the nextTick queue before continuing through the event loop, you can prevent the event loop from reaching I/O phases.
Conceptually:
nextTick
↓
nextTick
↓
nextTick
↓
nextTick
↓
nextTick
↓
...
Meanwhile:
poll
never gets a chance to run.
This is called event loop starvation.
Node's own documentation explicitly warns that recursive process.nextTick() calls can starve I/O by preventing the event loop from reaching the poll phase.
This is one reason you shouldn't think of process.nextTick() as simply another way to schedule asynchronous work.
It has much higher priority.
Why Does process.nextTick() Exist?
At this point you might ask:
If
process.nextTick()can starve the event loop, why does Node have it?
Because sometimes you need to guarantee that something happens:
after the current JavaScript stack
↓
but before the event loop continues
Imagine an API that sometimes has an error synchronously and sometimes asynchronously.
Without nextTick, you could accidentally create inconsistent behavior:
function apiCall(callback: () => void) {
callback(); // synchronous
}
Now:
let value = null;
apiCall(() => {
console.log(value);
});
value = 1;
The callback runs before:
value = 1;
With process.nextTick():
function apiCall(callback: () => void) {
process.nextTick(callback);
}
the current script gets to finish:
apiCall()
│
▼
schedule callback
│
▼
value = 1
│
▼
current operation ends
│
▼
nextTick callback
Node uses this pattern in APIs where it needs to preserve asynchronous behavior while allowing the current operation to finish.
The One Diagram I Wish Every Frontend Developer Saw
If I had to reduce all of this to one mental model, it would be this:
┌─────────────────────────┐
│ JavaScript callback │
│ runs synchronously │
└────────────┬────────────┘
│
▼
┌─────────────────────────┐
│ nextTick queue │
│ process.nextTick() │
└────────────┬────────────┘
│
▼
┌─────────────────────────┐
│ microtask queue │
│ Promise / queueMicrotask│
└────────────┬────────────┘
│
▼
┌──────────────────────────────────────┐
│ Event Loop │
│ │
│ timers → pending → poll → check │
│ ↓ │
│ close callbacks │
└──────────────────┬───────────────────┘
│
└──────► next callback
The important distinction is:
EVENT LOOP
│
┌─────────────┴─────────────┐
│ │
Phases Queues
│ │
│ nextTick queue
│ │
│ microtask queue
│
├── timers
├── pending callbacks
├── poll
├── check
└── close callbacks
Phases and queues are different concepts.
Once you see that distinction, Node's event loop diagram becomes much less mysterious.
So What Does "Single-Threaded" Actually Mean?
Now we can answer another question that often causes confusion:
"If Node.js is single-threaded, how can it handle thousands of requests?"
"Single-threaded" primarily means that one JavaScript thread executes your JavaScript callbacks.
It does not mean the entire machine has only one thread doing work.
Node delegates asynchronous work to the operating system and libuv.
For network I/O, the OS can notify Node when a socket becomes ready.
For operations such as file-system work, libuv can use its thread pool.
The architecture is roughly:
Node.js
│
JavaScript thread
│
┌────────────┼────────────┐
│ │ │
▼ ▼ ▼
HTTP File DNS
I/O I/O ...
│ │
▼ ▼
OS/kernel libuv pool
│ │
└──────┬─────┘
▼
callback ready
│
▼
event loop
│
▼
JavaScript callback
This is why an operation like:
await fetch(url);
doesn't block the JavaScript thread while the network is waiting.
The JavaScript thread is free to process other work.
And This Matters Even More for AI Applications
If you're building AI applications with Node.js, the event loop isn't an academic detail.
Consider an LLM request:
Browser
│
▼
Node.js
│
│ fetch()
▼
LLM API
│
│ 10 seconds...
│
│ streaming tokens...
▼
Node.js
│
▼
Browser
The LLM call is primarily network I/O.
You don't want your server doing:
while (waitingForLLM) {
// ...
}
That would block the JavaScript thread.
Instead, the server registers asynchronous work and lets the event loop continue processing other requests.
This is one reason Node.js is a natural fit for AI applications that spend much of their time waiting for:
- LLM APIs
- databases
- vector stores
- HTTP APIs
- file I/O
- streaming responses
But there is an important exception.
If you perform CPU-heavy work directly on the JavaScript thread:
app.get('/bad', (c) => {
const result = expensiveComputation();
return c.json({ result });
});
you can block the event loop.
While that computation runs:
Request A
│
▼
CPU-heavy work
│
│ JavaScript thread blocked
│
├── Request B waits
├── Request C waits
├── Request D waits
└── ...
This is why CPU-intensive work may need Worker Threads or another architecture rather than running directly in the request handler.
The distinction is simple:
LLM API call
↓
network I/O
↓
doesn't block JS
CPU-intensive computation
↓
JavaScript execution
↓
blocks JS
The Mental Model to Take Away
You don't need to memorize every libuv detail.
Instead, remember these layers.
Layer 1: Your JavaScript
synchronous code
One JavaScript thread executes it.
Layer 2: Node's priority queues
nextTick
↓
microtasks
These can run before Node continues through the event loop.
Layer 3: Event-loop phases
timers
pending callbacks
poll
check
close callbacks
Different kinds of asynchronous work enter different phases.
Layer 4: The OS and libuv
network
filesystem
DNS
other asynchronous operations
The actual waiting and background work happens outside your JavaScript execution.
Put together:
Your JavaScript
│
▼
nextTick queue
│
▼
microtask queue
│
▼
Node event loop
│
┌─────────────┼─────────────┐
▼ ▼ ▼
timers poll check
│ │ │
└─────────────┼─────────────┘
│
▼
OS / libuv
│
▼
I/O completes
│
▼
callback ready
│
└──────────────►
Once you see this, the Node.js event loop is no longer a completely different concept from the browser event loop.
It's the same fundamental idea with a much more explicit server-side execution model.
The Short Version
If you remember only five things, remember these:
1. Node.js runs JavaScript on a main thread.
That's what "single-threaded JavaScript" means.
2. Node.js has multiple event-loop phases.
The important ones for everyday development are:
timers
poll
check
3. process.nextTick() is not an event-loop phase.
It has its own queue and runs before Node continues through the event loop.
4. Promise callbacks are microtasks.
They run after the current synchronous operation and before the event loop continues.
5. Don't block the JavaScript thread.
Network I/O is cheap from the event-loop perspective.
CPU-heavy JavaScript is not.
Final Thought
Frontend developers already understand the JavaScript event loop.
You don't need to throw that mental model away when you move to Node.js.
You just need to add another layer:
Browser mental model
sync
↓
microtasks
↓
tasks
becomes:
Node.js mental model
JavaScript callback
↓
nextTick
↓
microtasks
↓
event-loop phases
↓
I/O
↓
next callback
That's the connection that makes Node.js asynchronous code much easier to reason about.
And once you understand it, concepts like:
Streams
SSE
LLM streaming
AbortSignal
database I/O
HTTP concurrency
Worker Threads
stop looking like unrelated Node.js features.
They're all consequences of the same underlying execution model.
Further Reading
The Node.js Event Loop documentation is the canonical reference for the phases, process.nextTick(), setImmediate(), and timer behavior.
For AI application developers, understanding this model is especially useful because so much of an AI server's work is asynchronous I/O: LLM calls, streaming responses, databases, file processing, and external APIs.
The event loop, streams and cancellation on the server are covered in Chapter 3 of 《AI Engineering with TypeScript — A Comprehensive Guide to Building AI Agents》 at Leanpub. The book's companion code is at github.com/aiengineering-book/code.
Top comments (0)