How to Troubleshoot Busy Wait 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.

Busy Wait is one of those production issues that makes the app look hung even though the process is still alive. The main thread sits in a tight loop checking the clock or burning CPU on nothing useful, and every timer and incoming request has to wait until that loop finishes.

In this blog, we’ll walk through how Busy Wait 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 ‘Busy Waiting’ in Node.js?

Busy waiting means a program keeps checking a condition in a tight loop instead of sleeping, waiting on an event, or handing control back to the runtime. The CPU stays busy the whole time, but the application is not making useful progress. It is stuck asking “are we done yet?” over and over.

In many programming languages, a thread can wait without continuously using the CPU. Node.js works differently. JavaScript on the main thread shares one event loop with timers, network callbacks, and HTTP responses. If that thread is inside a loop such as while (Date.now() < end) { … } or while (!ready) { }, nothing else on that loop can run until the function finally returns.

The process may still appear healthy from the outside. Health checks might pass, and average CPU may not look high if the busy loop runs only in short bursts. But while the loop is running, requests queue up, timers fire late, and the app can feel hung for seconds at a time.

What causes ‘Busy Waiting’ in Node.js?

Here is the usual list of causes for the ‘Busy Waiting’ problem.

  1. Spin loops on the main thread: Patterns like while (Date.now() < end) { … } or while (!ready) { } with no await or setImmediate keep the event loop stuck.
  2. Polling instead of events: Busy-checking a flag or file instead of using callbacks, promises, or watchers.
  3. Accidental infinite work: A loop whose exit condition is wrong, so it keeps running until something else stops it.
  4. Sync retry hammering: Retrying a failed operation in a tight loop with no backoff.

How to Simulate Busy Waiting in Node.js

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

The following program calls `busyLoop` over and over. Each run spins for about 2 seconds on the main thread using `Math.random()`, then pauses briefly before the next spin.

``` JS Code (busy-wait.js)
function busyLoop(targetMs) {
const end = Date.now() + targetMs;
do {
Math.random();
} while (Date.now() < end);
}
class BusyWaitDemo {
constructor() {
this.isRunning = false;
this.timeoutId = null;
}
_scheduleMainTick() {
if (!this.isRunning) return;
busyLoop(2000);
console.log('Event loop blocked by busy wait for ~2s');
this.timeoutId = setTimeout(() => this._scheduleMainTick(), 500);
}
start() {
if (this.isRunning) return;
this.isRunning = true;
console.log('Starting busy wait simulation...');
this._scheduleMainTick();
}
stop() {
clearTimeout(this.timeoutId);
this.isRunning = false;
}
}
module.exports = new BusyWaitDemo();
```

How to Capture Diagnostic Data for Troubleshooting Busy Waiting

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 Busy Waiting Using the Diagnostic Data

In this section, we’ll see how to analyze a Busy Waiting 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 spinning on 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 the 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 make 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 2 seconds. The overview also mentions an event listener leak warning, which is secondary in this case.

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 a Busy Waiting are:

  • Event loop blocked
  • Hot method

The event listener leak and duplicate package warnings are not what caused the freeze. You can ignore them for this walkthrough.

Step 3: Confirm multi-second 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 2000 ms for most of the window, with Fatal Spike rows such as 2009 ms, 2010 ms, and 2008 ms. That matches the 2-second busyLoop spin almost one-for-one.

Event Loop Lag does not name the function. To find out which code was spinning, 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: busyLoop used 76.1% of CPU across about 20,941 calls on one thread.

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

Fig: Inspector view of busyLoop

As you can see in the Inspect view above, busyLoop sits at the top of the parent chain. Under it, you can see Node’s timer path (listOnTimeout / processTimers), which matches a timer-driven spin on the main thread.

Together with the Fatal event-loop lag, that is enough to close the Busy Waiting case: the app froze because the main thread was inside busyLoop, not because it was waiting on I/O.

How to fix Busy Waiting in Node.js

The following are the potential solutions for this issue:

  1. Delete spin loops on the main thread; wait with promises, events, or timers instead of polling in a while loop.
  2. If you must poll, yield between checks with setImmediate()/setTimeout and use backoff.
  3. Move unavoidable CPU work to a bounded worker pool so the event loop stays free.
  4. Alert on Event Loop Lag so busy-wait regressions show up early.

Conclusion

Diagnosing and identifying the root cause of Busy Waiting can be challenging when the process is still alive, and average CPU does not look dramatic. In this example, the diagnostic data was captured using the yc-360 script and analyzed using the yCrash server, which helped correlate multi-second Event Loop Lag with the busyLoop hot method.

The analysis traced the issue to a tight Math.random() spin inside busyLoop. By examining the RCA Summary, the Event Loop Lag chart, and the CPU Profiler Inspect view, we could connect the Fatal 2010 ms stall to that function.

Removing the spin, or moving real work off the main thread, addresses the underlying problem and helps prevent the issue from recurring.

Mahesh Devda
Mahesh Devda
Articles: 16

Share your Thoughts!