How to Troubleshoot Event Loop Block in Node.js

Production issues in Node.js applications can be challenging to diagnose, especially when different problems exhibit similar symptoms. To make troubleshooting easier, we’re introducing a Node.js Production Troubleshooting Series, where each article focuses on one specific production issue, explores its underlying causes, and demonstrates a practical, step-by-step approach to identifying the root cause.

In this article, we are focusing on Event Loop Block. Users usually experience it as random freezes. A page that normally loads in a few hundred milliseconds suddenly takes several seconds, API calls start timing out, and then a little later everything is back to normal as if nothing happened.

What makes this issue confusing is that the server looks healthy from the outside. The process is still running, there are no crashes or restarts, and memory looks normal. Even CPU usage may look only moderately busy. That’s because Node.js runs your JavaScript on a single main thread. On a 4-core machine, one fully busy thread shows up as only about 25% CPU.

Behind the scenes, some code on the main thread is running synchronously for too long. It could be a large JSON.parse() or JSON.stringify() call, a regular expression that gets stuck on certain input, a synchronous file call like fs.readFileSync(), or a heavy loop doing calculations. While that code runs, Node.js can’t do anything else. Timers fire late, incoming HTTP requests wait in the queue, and health checks can fail even though the process never went down.

We’ll walk through how Event Loop Block shows up in a Node.js application, what typically causes it, and how to trace it back to the exact root cause. We’ll also simulate the issue in a sample application, capture diagnostic data as it happens, and analyze it step by step to pinpoint what’s going wrong.

What is ‘Event Loop Block’ in Node.js?

Node.js uses the event loop to handle tasks such as incoming requests, timers, and I/O callbacks.

If the main thread gets stuck doing a long-running synchronous task, the event loop cannot move on to other work. As a result, requests may be delayed, timers may not run on time, and the application can appear to freeze.

Event Loop Lag measures this delay. A high lag means the event loop was unable to run for a period of time.

What Causes ‘Event Loop Block’ in Node.js?

Here is the usual list of causes for the ‘Event Loop Block’ problem.

  1. Long synchronous functions: CPU-intensive work that runs on the main thread and doesn’t give the event loop a chance to run.
  2. Sync I/O: Calls such as `readFileSync()`, CPU-heavy compression, or other blocking operations can keep the main thread busy.
  3. Heavy JSON or regex: Parsing or stringifying large JSON objects, or running a complex regular expression, can take a long time and block the event loop.
  4. Busy waits and tight loops: A loop that keeps running while waiting for a condition or a specific time can prevent the event loop from processing other work.
  5. Accidental sync in async code: Even when a function uses async/await, a long-running synchronous operation before an await can still block the main thread on every request.

How to Simulate Event Loop Block in Node.js

To understand how Event Loop Block appears in the diagnostic data, let’s reproduce the issue using a sample Node.js application.

The following program repeatedly calls `runBlockEventLoopUntil`, which spins for about 1.2 seconds on the main thread, then yields briefly before the next tick.

``` JS Code (event-loop-block.js)
function runBlockEventLoopUntil(targetMs) {
const end = Date.now() + targetMs;
do {
Math.random();
} while (Date.now() < end);
}
class EventLoopBlockDemo {
constructor() {
this.isRunning = false;
this.timeoutId = null;
}
_scheduleMainTick() {
if (!this.isRunning) return;
runBlockEventLoopUntil(1200);
console.log('Event loop blocked for ~1200ms');
this.timeoutId = setTimeout(() => this._scheduleMainTick(), 400);
}
start() {
if (this.isRunning) return;
this.isRunning = true;
console.log('Starting event loop block simulation...');
this._scheduleMainTick();
}
stop() {
clearTimeout(this.timeoutId);
this.isRunning = false;
}
}
module.exports = new EventLoopBlockDemo();
```

How to Capture Diagnostic Data for Troubleshooting Event Loop Block

yCrash is a diagnostic tool that captures runtime performance data from a live Node.js process, including CPU usage, event loop lag, worker thread activity, and call stacks, and turns that data into a report that points to the root cause. To set up yCrash for your Node.js application, follow the steps below:

1. Install yCrash

yCrash is available in both Cloud and On-premises versions. Use one of the options below to get started:

  • Cloud Service: Create an account to use the cloud version.
  • On-premises: Register for a 14-day trial and install the yCrash application on your local machine or within the organization’s environment.

2. Set up the yCrash Node.js hook first

Please note that this is a one-time setup. The hook must be loaded into your Node.js application before yCrash can capture the Node.js internal data that matters for diagnosis, things like worker thread CPU, event loop lag, method profiling, and call stacks. To set this up, follow the Hook Mode steps here: Node.js Diagnostic Capture. This hook setup adds very minimalistic, almost zero overhead to your application.

3. Launch yc-360 script

Configure and start the yc-360 script to monitor your Node.js process. The full setup and configuration options specific to your deployment are available here: Micro-metrics Monitoring (M3) Mode

When the yc-360 script detects a problem, it captures  360° diagnostic artifacts (GC log, Event loop lags, Worker threads, CPU Profile, Unhandled rejections, Call stack, Active handles, Process, Storage, Kernel, Network, etc.). It uploads them to the yCrash server automatically. yCrash server analyzes the artifacts using advanced pattern recognition and ML algorithms to identify the root cause of the problem.

How to Analyze Event Loop Block Using the Diagnostic Data

In this section, we’ll see how to analyze an Event Loop Block using the diagnostic data captured by yCrash. We’ll start with the incident on the calendar dashboard, check the RCA Summary to understand what’s going on, and then drill into Event Loop Lag and the CPU profile reports to find the code that is blocking the main thread.

Step 1: Open the incident from the yCrash dashboard

When the yc-360 script detects any performance degradation in the Node.js application, it automatically captures 360° diagnostic data and transmits it to the yCrash server. The yCrash server analyses this data and creates an incident in the yCrash dashboard as shown in the screenshot below. Open that incident from the yCrash calendar dashboard to view the reports.

Fig: yCrash dashboard, incident list view

Step 2: Start with the RCA Summary Page


Before diving into details, let’s start with the RCA Summary. yCrash analyzes the Node.js diagnostic data and brings the key findings together in simple language with their severity levels.

In the RCA Summary, we will focus on two sections:

  • AI Overview
  • Issues in application and device

AI Overview

At the top of the RCA summary report page, you’ll see an AI Overview section. It gives you an AI-generated summary of the incident, which would help even a non-technical person understand the root cause of the problem. Within the AI Overview section, below the AI summary, you can also click on the ‘Dive Deeper in AI Mode’ button to open a chat window to ask any question to the AI about this incident.

Fig: RCA Summary highlighting the AI Overview

As shown in the AI Overview above, the root cause is a blocked event loop that stalled for over a second (1211 ms in this capture). The overview also mentions an event listener leak warning, which is secondary here.

Issues in application and device

Fig: RCA Summary highlighting the issues in application and device

As shown in the above screenshot, several application-level issues are reported. The 2 that matter most for an Event Loop Block are:

  • Event loop blocked
  • Hot method

The event listener leak and duplicate package warnings do not explain the freeze. You can set them aside for this investigation.

Step 3: Confirm the stall in Event Loop Lag

Open the Node.js Internals report from the left navigation as shown in the screenshot below. In the top section of this report called “Observations”, you will find all the problems detected in this report. Now let’s click the “detail here” hyperlink present at the end of the Event Loop blocked problem statement. This will take you to the Event Loop Lag section.

Fig: Event Loop Lag in Node.js Internals report

As you can see in the above graph, the lag stays near about 1210 ms for most of the window, with Fatal Spike rows such as 1210 ms, 1208 ms, and 1209 ms. That matches the ~1.2 second `runBlockEventLoopUntil` spin.

Event Loop Lag does not name the function. To find out which code blocked the loop, we will review the CPU Profiling report next.

Step 4: Use CPU Profiling to close the investigation

In the CPU Profiler Report page, yCrash aggregates the V8 sampling profile into a Function Explorer table (hot methods ranked by self CPU %). It provides an option to inspect the hot methods to do a deep diagnosis.

Open the CPU Profiler Report page from the left navigation and scroll to the Function Explorer section.

Fig: Function Explorer in CPU Profiler report

The Function Explorer confirms what we saw on the RCA Summary page: runBlockEventLoopUntil used 71.01% of CPU across about 19,777 calls on one thread.

For deep diagnosis, let’s click on the “Inspect” button from the same row.

Fig: Inspector view of runBlockEventLoopUntil

As you can see in the Inspect view above, `runBlockEventLoopUntil` sits at the top of the parent chain. Under it, you can see `_scheduleMainTick` in `event-loop-block.js`, then Node’s timer path.

This is useful because the CPU Profiler doesn’t just tell you that the event loop was blocked. It also shows which function was keeping the main thread busy during the stall.

How to Fix Event Loop Block in Node.js

The following are the potential solutions for this issue:

  1. Replace blocking synchronous operations with asynchronous APIs where possible.
  2. Split CPU-intensive work into smaller pieces and use `setImmediate()` to give timers, I/O, and other events a chance to run.
  3. Use worker threads or a bounded worker pool for CPU-intensive tasks.
  4. Tracking Event Loop Lag helps you detect new or recurring blocking issues early.

Conclusion

Diagnosing and identifying the root cause of Event Loop Block can be challenging, especially when average CPU looks only moderately busy. In this example, the diagnostic data was captured using the yc-360 script and analyzed using the yCrash server, which helped correlate Event Loop Lag with the runBlockEventLoopUntil hot method.

The analysis traced the issue to a synchronous spin inside runBlockEventLoopUntil in event-loop-block.js. By examining the RCA Summary, the Event Loop Lag chart, and the CPU Profiler Inspect view, we could connect the Fatal 1211 ms stall to that code path.

Keeping synchronous work short, or moving it off the main thread, addresses the underlying problem and helps prevent the issue from recurring.

Mahesh Devda
Mahesh Devda
Articles: 20

Share your Thoughts!