
If you have worked with Node.js, you have probably heard that it is single-threaded, non-blocking, and asynchronous. But have you ever wondered how Node.js handles multiple requests at the same time if JavaScript runs on a single main thread?
For example, imagine you are building a backend API that fetches user information from MongoDB, sends an email, and returns a response to the client. While Node.js is waiting for the database query to finish, does it stop executing everything else? If it did, handling multiple users would become a serious problem.
This is where the event loop in Node.js comes into the picture.
The event loop allows Node.js to handle asynchronous operations without blocking the main JavaScript thread while those operations are waiting to complete. It is one of the main reasons Node.js works well for APIs, real-time applications, chat applications, and other I/O-heavy workloads.
In this blog, we will understand what the event loop is, how it works, what its different phases do, and how you can use that knowledge when writing Node.js applications.
What Is the Event Loop in Node.js?
The event loop is a mechanism that allows Node.js to execute JavaScript callbacks associated with asynchronous operations when the main thread is available to run them.
Node.js uses the V8 JavaScript engine to execute JavaScript. It also relies on libuv, a library that helps manage the event loop, asynchronous I/O, and a thread pool for certain operations.
When your application starts, Node.js executes your JavaScript code. If it encounters an asynchronous operation, such as a timer or an I/O request, that operation can be handled without making JavaScript wait synchronously for its completion.
Once the operation is ready and its callback can run, Node.js schedules that callback for execution through the relevant event loop mechanisms.
Let's look at a simple example.
console.log("Start");
setTimeout(() => {
console.log("Timer completed");
}, 1000);
console.log("End");Output:
Start
End
Timer completedWhy does this happen?
Node.js executes
console.log("Start").It encounters
setTimeout()and registers the timer.JavaScript continues executing instead of waiting for the timer.
Node.js executes
console.log("End").When the timer becomes eligible to run, its callback executes when the event loop reaches the appropriate point.
The important thing to understand is that setTimeout() does not pause the entire application for one second.
Instead, it schedules a callback to become eligible for execution after the specified delay. The callback may run later than that delay if JavaScript is busy.
This is the basic idea behind the event loop.
Why Does Node.js Need an Event Loop?
JavaScript normally executes one piece of JavaScript at a time on the main thread. If a function takes a long time to execute, other JavaScript callbacks cannot run until that function finishes.
Without asynchronous I/O and event-loop coordination, an application could spend a lot of time waiting for database queries, network requests, and file operations.
Consider a typical backend API:
app.get("/users", async (req, res) => {
const users = await User.find();
res.json(users);
});When User.find() performs an asynchronous database operation, JavaScript does not need to sit idle until the database returns its result. The await pauses the execution of this particular async function, allowing other JavaScript work to proceed.
When the database query completes, the promise settles and the function can resume.
Meanwhile, Node.js can handle other incoming requests, process available callbacks, and continue other work as resources become available.
There is one important distinction here: the event loop does not make every operation run in parallel. It coordinates when JavaScript callbacks execute. Some operations rely on the operating system, while certain APIs use libuv's thread pool.
This is why Node.js can handle many concurrent I/O operations without creating a separate JavaScript thread for every request.
How Does the Node.js Event Loop Work?
To understand the event loop, it helps to look at what happens when your application runs.
Imagine your Node.js server receives requests from several users. Some requests need database access, some read files, and others perform calculations.
A simplified execution flow looks like this:
Node.js executes JavaScript on the main thread.
When it encounters asynchronous work, the relevant API arranges for that work to be handled.
JavaScript continues executing whenever it has other synchronous work to perform.
Once an asynchronous operation completes, its associated callback or promise reaction becomes eligible to run.
The event loop processes callbacks according to its scheduling rules.
JavaScript executes the ready callback, and the process continues.
Let's use a file-reading example.
const fs = require("node:fs");
console.log("Reading file...");
fs.readFile("data.txt", "utf8", (err, data) => {
if (err) {
console.error("Failed to read file:", err.message);
return;
}
console.log("File content:", data);
});
console.log("Continuing application...");Possible output:
Reading file...
Continuing application...
File content: Hello from Node.js!The exact file content depends on your data.txt file, but the ordering demonstrates the important point.
The file-reading operation is asynchronous. Node.js can continue executing JavaScript while the file is being read.
Once the operation completes, the callback becomes eligible to execute.
A note about asynchronous operations: Not all of them work in exactly the same way internally. Network I/O, file-system operations, timers, and CPU-intensive work have different implementation details. The event loop coordinates callbacks, but the underlying operation determines how the work gets done.
The Different Phases of the Node.js Event Loop
The Node.js event loop has several phases. Each phase handles a particular category of callbacks.
The main phases commonly discussed are:
Timers
Pending callbacks
Idle and prepare
Poll
Check
Close callbacks
You do not need to memorize every internal detail immediately. For everyday development, it is more useful to understand what each phase does and how it affects callback execution.
1. Timers Phase
The timers phase handles callbacks scheduled by functions such as:
setTimeout()setInterval()
For example:
setTimeout(() => {
console.log("Timeout callback");
}, 1000);This schedules a callback to become eligible after approximately one second.
However, the delay is not an exact execution time.
If the JavaScript thread is busy, the callback cannot run until the current JavaScript execution finishes and the event loop gets an opportunity to process it.
Consider this example:
setTimeout(() => {
console.log("Timer executed");
}, 0);
console.log("Synchronous code");Output:
Synchronous code
Timer executedEven with a delay of zero, the timer callback does not execute immediately. The synchronous code runs first.
Also, setTimeout(fn, 0) does not guarantee that the callback will run at the next exact millisecond. It means the callback can become eligible after the minimum delay, subject to event-loop scheduling and other work.
2. Pending Callbacks Phase
The pending callbacks phase handles certain I/O-related callbacks deferred from previous event-loop iterations.
For example, some system-level errors associated with networking can be handled in this phase.
You generally do not need to manage this phase directly when writing normal Node.js applications.
Still, it helps explain why not every asynchronous callback runs in the same phase.
3. Idle and Prepare Phase
The idle and prepare phase is used internally by Node.js and libuv.
It helps the event loop prepare for the next iteration.
As an application developer, you rarely interact with this phase directly. It is more important to know that it exists than to memorize its internal implementation.
4. Poll Phase
The poll phase is particularly important because it deals with I/O-related callbacks.
For example, when an asynchronous file-system or networking operation completes, its callback may be processed through the relevant I/O mechanisms associated with the poll phase.
The poll phase also determines whether the event loop should wait for additional I/O events or move forward to another phase.
Let's look at a simplified example:
const fs = require("node:fs");
fs.readFile("data.txt", () => {
console.log("File reading completed");
});
setTimeout(() => {
console.log("Timer callback");
}, 0);The output order can depend on the timing of the file operation and the event-loop state. You should not assume that the file callback always runs before the timer callback, or vice versa.
This is an important lesson: when multiple asynchronous operations are involved, their completion and scheduling rules matter.
If your application depends on a particular order, make that order explicit instead of relying on incidental timing.
5. Check Phase
The check phase handles callbacks scheduled with setImmediate().
For example:
setImmediate(() => {
console.log("Immediate callback");
});
console.log("Synchronous code");Output:
Synchronous code
Immediate callbackThe synchronous statement executes first because JavaScript runs the current call stack before processing the scheduled callback.
setImmediate() is especially useful to understand when working with I/O callbacks in Node.js.
Consider this example:
const fs = require("node:fs");
fs.readFile("data.txt", () => {
setImmediate(() => {
console.log("setImmediate callback");
});
console.log("File callback");
});The output is:
File callback
setImmediate callbackThe file-reading callback is already executing. It schedules the immediate callback, then logs File callback. After the current callback finishes, the immediate callback can run in the check phase.
6. Close Callbacks Phase
The close callbacks phase handles certain close events.
For example, a socket may emit a close event when the connection closes.
const net = require("node:net");
const server = net.createServer((socket) => {
socket.on("close", () => {
console.log("Socket connection closed");
});
socket.end("Hello!");
});
server.listen(3000, () => {
const client = net.createConnection(
{ port: 3000 },
() => {
console.log("Connected to server");
}
);
client.on("data", (data) => {
console.log(data.toString());
});
client.on("end", () => {
server.close();
});
});This example demonstrates a basic TCP server and client. When the socket closes, the registered close handler can run.
The exact lifecycle depends on the connection and shutdown behavior, but the key point is that some close-related callbacks are processed in a dedicated event-loop phase.
What Are Microtasks in Node.js?
Understanding event-loop phases is only part of the picture. You also need to understand microtasks.
Microtasks include promise reaction callbacks, such as those registered with .then(), .catch(), and .finally(). The queueMicrotask() API also schedules a microtask.
Node.js additionally has a special queue for callbacks registered with process.nextTick().
These mechanisms affect when JavaScript runs callbacks relative to other scheduled work.
Let's look at an example:
console.log("Start");
setTimeout(() => {
console.log("Timer");
}, 0);
Promise.resolve().then(() => {
console.log("Promise callback");
});
console.log("End");Output:
Start
End
Promise callback
TimerHere's why:
Startis logged immediately.The timer callback is scheduled.
A promise reaction is scheduled.
Endis logged.Once the current synchronous JavaScript execution finishes, the promise reaction runs before the timer callback in this example.
The promise callback is not executed at the moment .then() is called. Instead, it runs as a microtask after the current synchronous execution completes.
What About process.nextTick()?
Node.js provides process.nextTick() to schedule a callback that runs after the current operation completes, before the event loop continues to its next phase.
console.log("Start");
process.nextTick(() => {
console.log("nextTick callback");
});
Promise.resolve().then(() => {
console.log("Promise callback");
});
console.log("End");In a typical CommonJS Node.js script, the output is:
Start
End
nextTick callback
Promise callbackThe process.nextTick() callback runs before the promise reaction in this example.
However, you should not assume that all scheduling behavior is identical in every context. ES modules and CommonJS can exhibit different ordering in some examples because of how module evaluation interacts with microtask processing.
For most applications, remember these practical points:
Synchronous JavaScript runs first.
process.nextTick()callbacks are processed before Node.js proceeds to the next event-loop phase.Promise reactions and
queueMicrotask()callbacks run as microtasks.Timers and
setImmediate()callbacks are processed according to event-loop scheduling rules.
Be careful with recursive process.nextTick() calls. If callbacks keep scheduling more callbacks in the next-tick queue, they can delay the event loop from handling I/O.
For example:
function keepBusy() {
process.nextTick(keepBusy);
}
keepBusy();This is a bad pattern. It keeps scheduling more next-tick callbacks and can prevent normal event-loop progress.
Avoid creating an endless chain of callbacks that never allows other work to proceed.
What Is the Difference Between setTimeout() and setImmediate()?
This is a common Node.js interview question because both functions schedule callbacks, but they are associated with different event-loop phases.
Feature |
|
|
|---|---|---|
Purpose | Schedule a callback after a minimum delay | Schedule a callback for the check phase |
Event-loop phase | Timers | Check |
Timing | Callback becomes eligible after the delay | Callback runs when the event loop reaches the check phase |
Exact execution time | Not guaranteed | Not guaranteed |
Common use | Delayed tasks and recurring timers | Scheduling work after I/O callbacks |
Consider this example:
setTimeout(() => {
console.log("Timeout");
}, 0);
setImmediate(() => {
console.log("Immediate");
});When these functions are scheduled from the top level of a script, you should not rely on a fixed ordering between the two callbacks. The result can depend on timing and the environment.
However, when both are scheduled inside an I/O callback, setImmediate() generally runs before a zero-delay timer scheduled in that same callback.
For example:
const fs = require("node:fs");
fs.readFile("data.txt", () => {
setTimeout(() => {
console.log("Timeout callback");
}, 0);
setImmediate(() => {
console.log("Immediate callback");
});
});The usual output is:
Immediate callback
Timeout callbackThe immediate callback is processed in the check phase, while the timer callback is handled in the timers phase.
This distinction is useful when you need to understand callback ordering, but you should avoid using timing tricks to control important application logic.
Is Node.js Really Single-Threaded?
This is one of the biggest misconceptions about Node.js.
JavaScript application code usually runs on a single main thread by default, but Node.js itself is not limited to one thread for all its internal work.
Several components work together:
V8: Executes JavaScript.
Event loop: Coordinates when eligible callbacks are processed.
Operating system: Supports asynchronous I/O mechanisms for operations such as network communication.
libuv thread pool: Handles certain operations that cannot be performed through the same non-blocking mechanisms, including many file-system operations and some DNS and cryptographic tasks.
For example:
const fs = require("node:fs");
console.log("Start");
fs.readFile("data.txt", "utf8", (err, data) => {
if (err) {
console.error(err.message);
return;
}
console.log("File content:", data);
});
console.log("End");JavaScript does not need to block while waiting for the file-reading operation to finish.
However, the callback itself runs on the JavaScript thread when Node.js invokes it. If that callback performs an expensive calculation, it can still block other JavaScript work.
This is why asynchronous I/O and CPU-intensive JavaScript should be treated differently.
Can CPU-Intensive Code Block the Event Loop?
Yes, and this is an important issue in production applications.
Consider this example:
console.log("Start");
for (let i = 0; i < 1_000_000_000; i++) {
// Expensive synchronous work
}
console.log("End");The loop runs synchronously on the main JavaScript thread.
While it is running, Node.js cannot execute other JavaScript callbacks on that thread. Incoming requests may wait, timers can be delayed, and responses may become slower.
This can create a serious performance problem for an API server.
Imagine an endpoint that performs a large calculation:
app.get("/calculate", (req, res) => {
let result = 0;
for (let i = 0; i < 1_000_000_000; i++) {
result += i;
}
res.json({ result });
});The calculation blocks the event loop until it finishes.
Even requests to unrelated endpoints may be delayed because they depend on the same JavaScript thread.
How Can You Avoid Blocking the Event Loop?
The right solution depends on the type of work.
1. Use asynchronous APIs when available
Avoid synchronous operations in request handlers when they would block the main thread unnecessarily.
For example, prefer fs.readFile() over fs.readFileSync() when handling file access in a typical API request.
2. Move CPU-heavy work to worker threads
Node.js provides the worker_threads module for running JavaScript in separate threads.
This can be useful for expensive calculations, image processing, and other CPU-intensive tasks.
For example, the main thread can delegate a large calculation to a worker rather than performing it directly inside an HTTP request handler.
3. Use a queue for background jobs
Tasks such as generating reports, processing large files, or sending batches of emails may be better handled by background workers.
A job queue allows your API to accept a request and delegate the longer-running work to a separate process or worker.
4. Keep callbacks efficient
Even when using asynchronous APIs, avoid performing long synchronous operations inside callbacks.
An asynchronous operation does not make the code inside its callback asynchronous automatically.
If the callback contains a large synchronous loop, that loop can still block the main thread.
How to Check Whether the Event Loop Is Being Blocked
In real applications, you should not rely only on code inspection. Monitoring can help identify event-loop delays.
Node.js provides the perf_hooks module, which includes monitorEventLoopDelay().
Here is a basic example:
const {
monitorEventLoopDelay,
} = require("node:perf_hooks");
const histogram = monitorEventLoopDelay({
resolution: 20,
});
histogram.enable();
setInterval(() => {
console.log({
meanDelayMs: Number(histogram.mean) / 1e6,
maxDelayMs: Number(histogram.max) / 1e6,
});
histogram.reset();
}, 5000);This code samples event-loop delay and reports the mean and maximum observed delay in milliseconds.
A few things to remember:
The values depend on the workload and environment.
Initial readings may not be meaningful if the histogram has not collected enough samples.
High event-loop delay is a signal to investigate, not proof of a specific bug.
In production, combine event-loop monitoring with CPU usage, request latency, error rates, and other application metrics.
This is especially useful when an API becomes slow even though database response times appear normal.
Event Loop Best Practices for Node.js Developers
When building Node.js applications, keep these practices in mind.
1. Avoid Synchronous Work in Request Handlers
Synchronous file access, large loops, and expensive data transformations can block the main JavaScript thread.
Use asynchronous APIs where appropriate and move CPU-heavy work to a suitable worker.
2. Do Not Assume Timers Run at Exact Times
A timer schedules a callback after a minimum delay. It does not guarantee execution at an exact moment.
Avoid using setTimeout() as a precise scheduling mechanism.
3. Be Careful With Recursive Microtasks
Excessive use of process.nextTick() or endless chains of microtasks can delay other event-loop work.
Use these mechanisms when you understand why they are needed, rather than as a general replacement for asynchronous control flow.
4. Understand Your Database and Network Operations
An asynchronous database query does not block JavaScript in the same way as a synchronous calculation.
However, too many simultaneous queries can still overload your database or exhaust your connection pool.
Non-blocking execution does not mean unlimited capacity.
5. Monitor Event-Loop Delay
If your application handles many requests, event-loop delay can help reveal whether the JavaScript thread is spending too much time on synchronous work.
Measure performance rather than guessing.
6. Use Worker Threads for CPU-Intensive Tasks
Worker threads can help separate expensive calculations from the main JavaScript thread.
They are not automatically the best choice for every operation, though. For ordinary network and database I/O, asynchronous APIs are usually more appropriate.
Frequently Asked Questions
1. What is the event loop in Node.js in simple terms?
The event loop is the mechanism Node.js uses to process eligible callbacks for asynchronous operations. It allows JavaScript to continue working instead of blocking while operations such as I/O are waiting to complete.
2. Is the Node.js event loop part of JavaScript?
The event loop is not defined by the JavaScript language itself. It is part of the Node.js runtime environment, which uses V8 and libuv to execute JavaScript and coordinate asynchronous operations.
3. Does the event loop make Node.js multithreaded?
No. The event loop does not automatically run JavaScript callbacks on multiple threads. JavaScript generally runs on the main thread by default, while Node.js and the operating system can use other mechanisms and threads to handle certain operations.
4. What happens if the event loop is blocked?
Other JavaScript callbacks on the same thread must wait. This can delay incoming request handling, timers, I/O callbacks, and other application work.
5. What is the difference between the event loop and the call stack?
The call stack tracks the JavaScript functions currently executing. The event loop coordinates when eligible callbacks can execute as the runtime processes asynchronous work.
The event loop does not interrupt a function halfway through its synchronous execution just because another callback is ready.
6. What is the difference between process.nextTick() and setImmediate()?
process.nextTick() schedules a callback to run after the current operation completes, before the event loop proceeds to its next phase. setImmediate() schedules a callback for the check phase.
Using process.nextTick() repeatedly can delay event-loop progress, so it should be used carefully.
7. Why is the event loop important for backend developers?
Understanding the event loop helps developers write responsive APIs, diagnose slow requests, avoid blocking operations, and choose the right approach for I/O-heavy versus CPU-heavy tasks.
Final Thoughts
The event loop is one of the most important concepts to understand when working with Node.js.
It explains how Node.js can handle asynchronous operations without blocking the main JavaScript thread while those operations are waiting to complete. It also helps explain why a single expensive synchronous function can slow down an entire API server.
You do not need to memorize every internal detail of libuv to become a good Node.js developer. Start by understanding synchronous execution, asynchronous callbacks, promises, timers, and I/O. Then learn how the event-loop phases and microtask scheduling affect callback ordering.
Most importantly, remember this: asynchronous I/O helps Node.js handle waiting efficiently, but CPU-intensive JavaScript can still block the event loop.
Once you understand that difference, it becomes much easier to build responsive Node.js APIs, debug performance issues, and make better architectural decisions.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


