One of the most useful ways to identify event loop blocking is to measure how long the event loop takes to respond when it should be available.
Node.js provides the monitorEventLoopDelay() function through the built-in perf_hooks module.
It records event loop delay using a histogram. This helps developers understand whether callbacks are being delayed beyond their expected scheduling time.
Create a file named event-loop-monitor.js:
const {
monitorEventLoopDelay
} = require("node:perf_hooks");
const histogram = monitorEventLoopDelay({
resolution: 20
});
histogram.enable();
function getMilliseconds(nanoseconds) {
return Number((nanoseconds / 1e6).toFixed(2));
}
setInterval(() => {
const metrics = {
min: getMilliseconds(histogram.min),
max: getMilliseconds(histogram.max),
mean: getMilliseconds(histogram.mean),
p50: getMilliseconds(histogram.percentile(50)),
p95: getMilliseconds(histogram.percentile(95)),
p99: getMilliseconds(histogram.percentile(99))
};
console.log("Event loop delay:", metrics);
histogram.reset();
}, 10000);
The monitor collects event loop delay measurements and reports them every ten seconds.
The important values include:
Metric | Meaning |
|---|
Min | Minimum observed delay |
Max | Maximum observed delay |
Mean | Average observed delay |
P50 | Median observed delay |
P95 | Delay below which 95% of observations fall |
P99 | Delay below which 99% of observations fall |
For example, a high P99 value can indicate that the event loop occasionally experiences significant delays even when the average looks reasonable.
Do not treat one measurement as proof of a blocking-code problem. Event loop delay can also be affected by operating system scheduling, CPU contention, garbage collection, and resource pressure.
Compare measurements over time and correlate them with request latency, CPU utilization, and application activity.
Monitoring Event Loop Utilization
Event loop delay tells us how late the event loop is responding. Event loop utilization provides another useful perspective: how much time the event loop spends active compared with its idle time.
Node.js provides eventLoopUtilization() through the perf_hooks module.
For example:
const {
performance
} = require("node:perf_hooks");
let previous = performance.eventLoopUtilization();
setInterval(() => {
const current = performance.eventLoopUtilization(
previous
);
previous = performance.eventLoopUtilization();
console.log({
utilization: Number(
current.utilization.toFixed(3)
),
active: Number(
current.active.toFixed(2)
),
idle: Number(
current.idle.toFixed(2)
)
});
}, 5000);
The utilization value is between zero and one.
A value closer to one indicates that the event loop spent more of the measurement interval active rather than idle. It does not necessarily mean that the application is unhealthy. A busy API may legitimately have high utilization while serving requests efficiently.
The useful approach is to examine utilization alongside event loop delay.
Event loop delay | Event loop utilization | Possible interpretation |
|---|
Low | Low | The application has relatively little event loop activity |
Low | High | The event loop is busy but may still be processing callbacks efficiently |
High | High | CPU-heavy JavaScript or scheduling pressure may be delaying callbacks |
High | Low | Investigate intermittent blocking, system scheduling, or measurement conditions |
These values are diagnostic signals, not fixed performance thresholds. Establish baselines for the actual application and investigate meaningful changes.
Finding Blocking Code With a Practical API Example
Let's build a small Express API that demonstrates how a synchronous calculation affects unrelated endpoints.
Install Express:
npm install express
Create server.js:
const express = require("express");
const app = express();
app.get("/health", (req, res) => {
res.json({
status: "healthy"
});
});
app.get("/orders", async (req, res) => {
await new Promise(resolve => {
setTimeout(resolve, 50);
});
res.json({
orders: 10
});
});
app.get("/report", (req, res) => {
let result = 0;
for (let i = 0; i < 500000000; i++) {
result += Math.sqrt(i);
}
res.json({
result
});
});
app.listen(3000, () => {
console.log("API running on port 3000");
});
The health endpoint performs almost no work. The orders endpoint simulates an asynchronous operation. The report endpoint performs a large synchronous calculation.
Start the application:
node server.js
Open one terminal and call the report endpoint:
curl http://localhost:3000/report
While the calculation is running, call the health endpoint from another terminal:
curl http://localhost:3000/health
The health endpoint may take much longer than expected because the main thread is busy executing the report calculation.
This demonstrates an important point: an endpoint does not need to contain slow code to become slow. It only needs to share a blocked event loop with another operation.
Using the Node.js Inspector to Find the Blocking Function
Event loop metrics tell us that the application is experiencing delays, but they do not identify the exact function responsible.
For that, developers can use the Node.js Inspector and CPU profiling.
Start the application with the inspector enabled:
node --inspect server.js
Node.js starts an inspector endpoint that can be connected to using Chrome DevTools or another compatible debugging client.
Open Chrome and navigate to:
chrome://inspect
Select the Node.js process and open its inspection window.
Go to the Performance panel and start a recording. While the recording is active, send requests to the API, especially the endpoint suspected of blocking the event loop.
After stopping the recording, inspect the CPU profile.
Look for functions that consume a large amount of execution time. A function that repeatedly appears at the top of the call stack may be responsible for the CPU-intensive work.
For example, a profile might reveal a call chain similar to:
GET /report
generateReport()
calculateStatistics()
normalizeRecords()
expensiveRegularExpression()
This helps narrow the investigation from a slow endpoint to a specific operation.
The inspector is useful during development and controlled troubleshooting. Avoid exposing the inspector port publicly in production because it provides powerful access to the running Node.js process.
For production investigations, use controlled profiling, restricted access, and an appropriate diagnostic window.
Using the Built-In CPU Profiler
Node.js also supports CPU profiling through its command-line options.
For example:
node --cpu-prof server.js
The CPU profiler records CPU activity and writes a profile file when the process exits.
You can inspect the generated profile using compatible profiling tools.
For an application that is already running, Node.js provides diagnostic mechanisms that can capture CPU profiles without requiring every production process to run continuously with an interactive debugger.
CPU profiling is particularly useful when an issue occurs only under realistic traffic or when a specific endpoint is difficult to reproduce locally.
However, profiling itself has overhead. Collect profiles during a controlled period and understand the impact before enabling detailed diagnostics across every production instance.
Fixing Event Loop Blocking With Worker Threads
When profiling confirms that a JavaScript calculation is consuming too much time on the main thread, worker threads are one possible solution.
They allow CPU-intensive JavaScript operations to execute on separate threads.
For example, move the report calculation into a worker.
Create report-worker.js:
const {
parentPort,
workerData
} = require("node:worker_threads");
function calculateReport(count) {
let result = 0;
for (let i = 0; i < count; i++) {
result += Math.sqrt(i);
}
return result;
}
const result = calculateReport(workerData.count);
parentPort.postMessage(result);
Update the API endpoint:
const express = require("express");
const { Worker } = require("node:worker_threads");
const path = require("node:path");
const app = express();
function generateReport(count) {
return new Promise((resolve, reject) => {
const worker = new Worker(
path.resolve(__dirname, "report-worker.js"),
{
workerData: {
count
}
}
);
let completed = false;
worker.once("message", (result) => {
completed = true;
resolve(result);
});
worker.once("error", (error) => {
reject(error);
});
worker.once("exit", (code) => {
if (code !== 0 && !completed) {
reject(
new Error(
`Worker exited with code ${code}`
)
);
}
});
});
}
app.get("/health", (req, res) => {
res.json({
status: "healthy"
});
});
app.get("/report", async (req, res) => {
try {
const result = await generateReport(500000000);
res.json({ result });
} catch (error) {
console.error(
"Report generation failed:",
error.message
);
res.status(500).json({
message: "Unable to generate report"
});
}
});
app.listen(3000, () => {
console.log("API running on port 3000");
});
Now the calculation runs inside a worker instead of occupying the main JavaScript thread.
The main thread can continue processing health checks and other requests while the worker performs the calculation.
This example creates one worker per report request to keep the implementation simple. A production API should normally use a bounded worker pool, limit queued tasks, and handle cancellation and shutdown. Creating an unlimited number of workers can simply move the resource problem from the event loop to CPU and memory consumption.
Handling Large JSON and File Processing
Not every event loop blocking problem requires worker threads.
Sometimes the better solution is to avoid loading and processing an entire dataset at once.
Consider an API that reads a large JSON file and transforms every record. Even if the file is read asynchronously, parsing and transforming the complete dataset can still occupy the event loop.
Possible improvements include:
Use streaming parsers for large structured files.
Process records in bounded batches.
Avoid unnecessary object copying.
Return paginated results instead of constructing huge responses.
Move expensive transformations to a background worker.
Store generated reports and allow clients to retrieve them separately.
For example, a report that takes several seconds to generate may be better implemented as a background job.
The API can accept the request, create a job identifier, and return an HTTP 202 Accepted response. A worker processes the report independently, and the client checks the job status later.
This design avoids keeping an HTTP request open while a large operation runs.
Distinguishing Event Loop Blocking From Slow I/O
A slow API response does not always indicate event loop blocking.
For example, an endpoint may wait several seconds for a database query. During that time, the main event loop may remain available to process other requests.
This is different from a synchronous calculation that prevents the event loop from running.
Consider the following situations:
Situation | Likely cause | Investigation |
|---|
CPU usage is high and event loop delay increases | CPU-heavy JavaScript or scheduling pressure | CPU profile and event loop metrics |
CPU usage is low but requests are slow | Database, network, or external service delay | Dependency tracing and query timing |
Only large payloads cause delays | Parsing, serialization, or memory pressure | Payload size and CPU profiling |
Health checks slow down during report generation | Shared event loop blocking | Correlate health latency with report activity |
Delays appear during garbage collection | Allocation pressure or large object graphs | Heap and garbage collection profiling |
Do not solve a slow database query by adding worker threads. Workers do not automatically make external I/O faster.
Similarly, changing synchronous JavaScript into an async function does not make the underlying computation asynchronous. The following code still blocks the event loop:
app.get("/report", async (req, res) => {
const result = calculateLargeReport();
res.json({ result });
});
The async keyword changes how the function handles Promises. It does not move calculateLargeReport() to another thread.
Best Practices for Preventing Event Loop Blocking
Preventing event loop blocking is easier when performance considerations are included in API design and code reviews.
Keep Request Handlers Small
Request handlers should validate input, coordinate the required operations, and return a response. Large calculations and expensive transformations should be moved into suitable services or background processing components.
This makes the code easier to test and helps developers identify CPU-intensive operations.
Avoid Synchronous APIs in Request Paths
Synchronous file system operations, child process operations, and other blocking APIs should generally be avoided inside frequently used request handlers.
Use asynchronous alternatives when available.
Limit Input Size
Large request bodies can increase parsing time, memory consumption, and serialization overhead.
Configure request-size limits and validate the amount of work a client can request.
Use Bounded Concurrency
Do not create an unlimited number of workers or background tasks. Use bounded worker pools and queues with explicit capacity limits.
When the system reaches its capacity, reject excess work or apply backpressure instead of allowing memory usage to grow without control.
Monitor the Event Loop Continuously
Track event loop delay, utilization, CPU usage, memory consumption, and API response latency.
A useful monitoring dashboard should show these metrics together so that developers can correlate application slowdowns with resource behavior.
Test Under Realistic Load
A blocking operation may not be noticeable when only one developer is testing the API.
Run load tests that combine normal requests with expensive operations. Verify that health checks, authentication endpoints, and common API requests remain responsive when background workloads increase.
Common Mistakes During Troubleshooting
One common mistake is assuming that every slow endpoint has a database problem. Database timing should be measured, but event loop delay and CPU profiles should also be inspected.
Another mistake is adding async and await to a function without changing the blocking operation. This improves Promise handling but does not move CPU-heavy JavaScript off the main thread.
Developers also sometimes create one worker for every incoming request. This can overload the machine when traffic increases. A bounded worker pool is generally a more controlled solution.
Finally, do not rely only on average response time. A small number of requests can experience severe delays even when the average looks acceptable. Monitor percentile latency and event loop delay to understand these problems.
Summary
Event loop blocking is an important performance problem in Node.js APIs because JavaScript callbacks execute on the main thread. When synchronous operations or CPU-intensive calculations occupy that thread, unrelated requests can also become slow.
The first step is to measure event loop delay and utilization. These metrics help identify when the event loop is not responding promptly. CPU profiling through the Node.js Inspector or built-in profiling options can then help locate the functions responsible.
The solution depends on the workload. Use asynchronous APIs for I/O operations, streaming and batching for large datasets, and worker threads for CPU-intensive JavaScript calculations. For longer operations, a background job architecture may be more appropriate.
A responsive Node.js API is not achieved simply by making every function asynchronous. Developers must understand which operations block the event loop, measure their impact under realistic traffic, and choose an approach that keeps CPU-intensive work from delaying ordinary requests.
Join the conversation! Your thoughts help the community grow.