How the Node.js Event Loop Actually Works
Understand the call stack, asynchronous I/O, event-loop phases, promises, timers, and why CPU-heavy JavaScript can still block a Node.js server.
TechSilo
AI-assisted and human-curated
A Node.js server can manage many open network connections without creating a JavaScript thread for every request. That does not mean JavaScript callbacks run in parallel. Most JavaScript in a Node.js process executes on one event-loop thread, and the event loop decides when ready callbacks get a turn.
Understanding that distinction makes async bugs, slow endpoints, and timer behavior much easier to diagnose.
Start with the call stack
JavaScript runs the current synchronous work until the call stack is empty. Consider:
console.log('first');
setTimeout(() => {
console.log('timer callback');
}, 0);
Promise.resolve().then(() => {
console.log('promise callback');
});
console.log('last');The synchronous messages print first: first, then last. The promise callback runs as a microtask after the current JavaScript stack finishes. The timer callback runs later when the timer is eligible and the event loop reaches the appropriate point.
A zero-millisecond timeout is a minimum delay, not a promise that the callback runs immediately.
What happens while JavaScript is busy?
When code starts asynchronous work, Node.js can delegate it instead of waiting synchronously. Network I/O is generally handled through operating-system facilities. Some operations, such as many file-system and cryptographic tasks, use libuv's worker pool.
When the operation completes, Node schedules the relevant callback. The callback still runs on the JavaScript thread. If that callback takes 400 ms of CPU time, other JavaScript callbacks on that event loop cannot run during those 400 ms.
This is why an endpoint can have low database latency and still respond slowly: a synchronous loop, expensive JSON transformation, or CPU-heavy regular expression can block the event loop.
The important Node.js phases
Node's event loop has several phases. The most useful ones to recognize are:
- Timers: callbacks whose setTimeout() or setInterval() thresholds have elapsed.
- Pending callbacks: certain system-level I/O callbacks deferred to a later iteration.
- Poll: retrieve and process I/O events; the loop may wait here when there is no work to run.
- Check: callbacks scheduled with setImmediate().
- Close callbacks: some close-related events, such as a socket's close event.
There are internal phases too, but you rarely need to memorize the entire diagram to debug an application.
Timer timing also depends on the surrounding work. Node.js 20 changed libuv's timer processing relative to the poll phase, so examples that promise one universal ordering between setTimeout(fn, 0) and setImmediate(fn) are misleading. Their order can depend on where they are scheduled.
EventEmitter is not an asynchronous queue
A common misconception is that emitting an event automatically puts its listeners into the event-loop queue. Node's EventEmitter.emit() calls registered listeners synchronously, in registration order.
const { EventEmitter } = require('node:events');
const bus = new EventEmitter();
bus.on('ready', () => {
console.log('listener ran');
});
console.log('before emit');
bus.emit('ready');
console.log('after emit');Output:
before emit
listener ran
after emitIf a listener performs expensive synchronous work, the call to emit() takes that time. Use an explicit asynchronous scheduling mechanism when that is what your design requires.
Promises, nextTick, and timers are different queues
Promise handlers and queueMicrotask() use the microtask queue. Node also has process.nextTick(), which is processed before the event loop continues in common callback contexts. Recursive nextTick() scheduling can starve I/O, so it should not be used as a general-purpose task queue.
Use setImmediate() when you intentionally want to yield and schedule work for the check phase. Use timers when you need a delay threshold. Do not depend on incidental ordering unless the Node documentation guarantees it for the context you are using.
How to keep a server responsive
1. Measure the slow route before changing the architecture.
2. Look for synchronous file operations, large loops, expensive serialization, and catastrophic regular expressions.
3. Move genuinely CPU-bound work to worker threads or a separate job process when it justifies the added complexity.
4. Keep I/O asynchronous, but also apply timeouts and limits so slow dependencies do not accumulate unlimited work.
5. Monitor event-loop delay and request latency together; one metric alone can hide the cause.
The official [Node.js event-loop guide](https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick) explains the phases and scheduling details. Use it when exact timer behavior matters. The practical rule is simpler: async I/O frees the thread while work is waiting; it does not make long-running JavaScript free.
Want to put this into practice?
Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.
Related blog posts
Console.log Alternatives for Efficient JavaScript Debugging
Use browser breakpoints, console.table, console.trace, timing APIs, and structured logs to debug without flooding production consoles.
Read postJavaScript Destructuring Defaults: Avoid Undefined and Subtle Bugs
Use default values in object and array destructuring correctly, including nested options, null behavior, and function parameters.
Read postEnvironment Variable Management: Secure Secrets and Deployment Practices
Keep environment configuration safe across local development, CI, and production without leaking API keys into browser bundles or logs.
Read postnpm Scripts Cheat Sheet: Commands, Arguments, and Automation
A developer reference for package.json scripts, npm run, pre/post hooks, environment variables, and safe task automation.
Read postPractical CORS Configuration Security Guide for APIs
Secure cross-origin browser requests with explicit origin allowlists, correct preflight handling, and credential rules.
Read post