A Node.js API can handle many concurrent requests without creating a separate JavaScript thread for every request. Its event-driven architecture allows the application to process incoming requests while waiting for database queries, network calls, and other asynchronous operations to complete.
However, this architecture depends on the event loop remaining available. When a request executes CPU-intensive JavaScript code or performs a synchronous operation, it can prevent the event loop from handling other work. Even a single slow operation can affect unrelated requests that share the same Node.js process.
This problem is often difficult to identify because the API may work correctly during development and show no obvious errors. Under production traffic, response times increase, health checks become slow, and requests that normally complete quickly may start timing out.
Finding event loop blocking code requires more than checking whether an endpoint is slow. Developers need to measure event loop delay, inspect CPU usage, identify long-running JavaScript operations, and distinguish event loop blocking from slow external dependencies.
This article explains how the Node.js event loop works, how blocking code affects API performance, and how to identify and troubleshoot these problems using built-in Node.js tools and practical examples.
Understanding the Node.js Event Loop
Node.js executes JavaScript callbacks on its main thread. The event loop coordinates when those callbacks run and allows the application to handle asynchronous operations without waiting synchronously for every operation to finish.
Consider a typical API endpoint that reads information from a database:
app.get("/orders", async (req, res) => {
try {
const orders = await database.getOrders();
res.json(orders);
} catch (error) {
res.status(500).json({
message: "Unable to retrieve orders"
});
}
});
When database.getOrders() starts an asynchronous database operation, the JavaScript function can pause at await. Node.js can continue processing other callbacks while the database operation is in progress.
When the database operation completes, its Promise settles and the remaining JavaScript code becomes eligible to run.
This does not mean that every operation in Node.js runs in parallel. JavaScript callbacks still execute on the main thread unless work is moved to another thread or handled by an external system.
For example, the following calculation blocks the main thread:
function calculateTotal() {
let total = 0;
for (let i = 0; i < 500000000; i++) {
total += Math.sqrt(i);
}
return total;
}
app.get("/calculate", (req, res) => {
const result = calculateTotal();
res.json({ result });
});
While calculateTotal() is running, the event loop cannot execute other JavaScript callbacks on that thread. Requests that arrive during this period must wait for the calculation to finish before their JavaScript handlers can run.
The problem is not limited to the endpoint performing the calculation. Other endpoints in the same process can also become slow.
Why Event Loop Blocking Affects the Entire API
Imagine an API with three endpoints:
GET /health checks whether the application is responding.
GET /orders retrieves order information from a database.
POST /reports generates a large report.
The report endpoint performs an expensive synchronous calculation. While that calculation runs, the event loop cannot promptly process requests to the health or orders endpoints.
The application may show the following symptoms:
Health checks become slow even though the database is available.
Requests that normally complete in a few milliseconds take much longer.
Incoming requests accumulate while the main thread is busy.
Reverse proxies and load balancers report request timeouts.
CPU usage increases on the Node.js process.
The application appears unresponsive during large file or data-processing operations.
This behavior can be confusing because the slow endpoint may not be the endpoint users complain about. A request that does very little work can still be delayed by another request that blocks the shared event loop.
The key diagnostic question is whether the Node.js process is spending too much time executing JavaScript or whether it is waiting for an external operation.
Identifying Common Sources of Event Loop Blocking
Several coding patterns can prevent the event loop from processing other callbacks promptly.
Synchronous File System Operations
Node.js provides synchronous and asynchronous file system APIs.
A synchronous operation blocks the JavaScript thread until the operation completes.
For example:
const fs = require("node:fs");
app.get("/configuration", (req, res) => {
const content = fs.readFileSync(
"./configuration.json",
"utf8"
);
res.type("application/json").send(content);
});
Every request to this endpoint reads the file synchronously. If the file is large or the storage system is slow, the event loop remains occupied during the operation.
For request-handling code, use asynchronous file operations when possible:
const fs = require("node:fs/promises");
app.get("/configuration", async (req, res) => {
try {
const content = await fs.readFile(
"./configuration.json",
"utf8"
);
res.type("application/json").send(content);
} catch (error) {
console.error("Configuration read failed:", error.message);
res.status(500).json({
message: "Unable to read configuration"
});
}
});
The asynchronous API allows the event loop to process other callbacks while the file operation is pending.
However, asynchronous does not mean that the operation has no resource cost. Large files still consume memory, and the underlying operation may use the libuv thread pool or operating system facilities.
Large JSON Parsing and Serialization
JSON parsing and serialization are synchronous JavaScript operations.
For small request and response bodies, this is normally acceptable. However, parsing or serializing very large objects can occupy the event loop long enough to affect API responsiveness.
Consider an endpoint that reads a large JSON file:
const fs = require("node:fs");
app.get("/large-data", (req, res) => {
const content = fs.readFileSync(
"./large-data.json",
"utf8"
);
const data = JSON.parse(content);
res.json(data);
});
There are two separate concerns here. The file read is synchronous, and JSON.parse() performs synchronous processing.
Changing the file read to an asynchronous API removes the synchronous I/O operation, but JSON.parse() still runs on the main JavaScript thread.
For very large datasets, consider streaming formats and parsers, processing smaller chunks, or moving CPU-intensive parsing into a worker thread.
Expensive Regular Expressions
Regular expressions can also block the event loop.
Some patterns have pathological backtracking behavior. When applied to carefully chosen input, they can take a very long time to complete.
For example:
const dangerousPattern = /^(a+)+$/;
app.post("/validate", (req, res) => {
const input = req.body.value;
const valid = dangerousPattern.test(input);
res.json({ valid });
});
An input containing many repeated characters followed by a character that prevents a match can cause this expression to perform excessive backtracking.
This type of issue can become a regular expression denial-of-service vulnerability, commonly called ReDoS.
Use simpler patterns, limit input length, and avoid nested ambiguous quantifiers. For complex user-controlled matching, consider a regular expression engine designed to provide predictable execution behavior.
Large Loops and Data Transformations
Loops that process large collections can occupy the event loop for a considerable period.
For example:
app.post("/process-records", (req, res) => {
const records = req.body.records;
const result = records.map((record) => {
return {
id: record.id,
score: calculateScore(record)
};
});
res.json(result);
});
If records contains hundreds of thousands of items and calculateScore() performs expensive calculations, the endpoint can block other requests.
Using Promise.all() does not solve this problem if the work inside each callback is synchronous JavaScript.
For CPU-intensive transformations, consider worker threads or a background job system. If the work can be divided into manageable chunks, process those chunks with a controlled scheduling strategy.
Join the conversation! Your thoughts help the community grow.