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.
CPU Spike is one of those production issues that can appear suddenly. The Node.js process looks fine, then CPU jumps, the app slows down or stops responding, and request times shoot up. By the time it shows up in APM or a user reports it, the spike may already be over. Finding the code that caused it is much harder once that moment has passed.
In this blog, we’ll walk through how CPU spikes show up in a Node.js application, what typically causes them, 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 ‘CPU Spike’ in Node.js?
Node.js runs your application on a single main thread. That thread also runs the event loop, so timers, I/O callbacks, and HTTP responses all depend on it.
A CPU spike means that thread is busy computing rather than waiting for I/O. The OS may already accept the Incoming requests, but they cannot be completed until that work finishes. Latency goes up even when memory and disk look fine.
On a multi-core machine, this usually shows up as one CPU core running close to 100% and the others almost idle. That busy core is the event-loop thread. worker_threads can use additional cores, but that is a separate source of CPU usage. If the spike is on the main thread, the process cannot handle new events until the blocking operation finishes.
What Causes ‘CPU Spike’ in Node.js?
Here is the usual list of causes for the ‘CPU Spike’ problem.
- Blocking the event loop withCPU-heavy processing: As your application code has a single event loop, blocking this thread with extremely intensive operations (like image processing, Data compression, JSON parsing, etc.) will invariably lead to CPU spikes.
- Unoptimized loops or recursion: An unbounded loop (e.g., no ‘break’ statement or faulty condition check on a for/while loop), or a poorly coded recursive function, will keep running the process indefinitely. This will drain the CPU.
- SetInterval/setTimeout misused: An setInterval or setTimeout that is set infinitely or one whose execution triggers the next execution before the event loop gets back to it again, will lead to a buildup in tasks and in CPU utilization over time.
- Inefficient database operations: An expensive or slow(repeatedly) database query that the application spends excessive time on will drain resources significantly. Furthermore, even when not directly interacting with the DB, the result of the DB operation can spend excess time processing the data or handling errors.
- Memory leaks and garbage collector overhead: In the event that a memory leak occurs, Node.js will try to clean itself up; as the volume of memory that needs to be processed for garbage collection grows, it will begin consuming large amounts of CPU resources.
- Uncapped API requests: This can be a server-wide issue; if you have no mechanism to limit the rate at which the server accepts incoming requests, you may find one that starts experiencing high CPU usage quickly as it cannot keep up with the request volume.
- Bad async patterns: Not handling a Promise.all() or having excessively nested callbacks can cause long-running async operations to pile up. Even with these operations on the order of milliseconds, the sheer volume of such operations can put sufficient load on the CPU to spike it.
How to Simulate CPU Spike in Node.js
To understand how a CPU Spike appears in the diagnostic data, let’s reproduce the issue using a sample Node.js application.
The following program saturates CPU on both the main event-loop thread and a pool of worker_threads. Each worker runs a continuous `crypto.pbkdf2Sync` loop so every core stays busy. On the main thread, a `loop()` callback runs `pbkdf2Sync` for about `900 ms`, then pauses for about `20 ms` before starting again. That short pause is intentional because without it, the process can become too stuck for the yc-360 script. Together, this keeps the process CPU high long enough for the yCrash Micro-metrics Monitoring (M3) to treat it as a long-lasting, sustained spike, rather than a short burst.
``` JS Code (cpu-spike.js)const os = require('os');const crypto = require('crypto');const { Worker, availableParallelism } = require('worker_threads');class CPUSpikeDemo { constructor() { this.workers = []; this.isRunning = false; this._timeoutId = null; } start() { if (this.isRunning) { console.log('CPU spike is already running'); return; } this.isRunning = true; console.log('Starting CPU spike simulation...'); const numCPUs = os.cpus().length; const parallelism = typeof availableParallelism === 'function' ? availableParallelism() : numCPUs; // Peg every core with a continuous worker so process CPU stays high // long enough for M3 to detect a sustained spike (not a short burst). const workerCount = Math.max(1, numCPUs); const pbkdf2Iterations = 2000; const mainBusyMs = 900; const mainIdleMs = 20; const m3TargetPct = workerCount * 80; for (let i = 0; i < workerCount; i++) { const worker = new Worker(` const crypto = require('crypto'); const iter = ${pbkdf2Iterations}; while (true) { crypto.pbkdf2Sync('cpu-spike', 'salt', iter, 32, 'sha512'); } `, { eval: true, name: `cpu-spike-worker-${i + 1}` }); worker.on('error', (err) => console.error(`Worker error: ${err.message}`)); this.workers.push(worker); } // Main thread: near-continuous pbkdf2Sync burn with a short yield so // the process can still talk to yc-360 / the hook. const loop = () => { if (!this.isRunning) { return; } const end = Date.now() + mainBusyMs; while (Date.now() < end) { crypto.pbkdf2Sync( 'cpu-spike-main', 'salt', Math.min(1200, pbkdf2Iterations), 32, 'sha512' ); } this._timeoutId = setTimeout(loop, mainIdleMs); }; loop(); console.log( `CPU spike started: ${workerCount} continuous workers (parallelism ${parallelism}), ` + `pbkdf2 ${pbkdf2Iterations}, main ${mainBusyMs}ms busy / ${mainIdleMs}ms yield. ` + `M3 App CPU needs TOP process %CPU >= ${m3TargetPct} on this host — capture while running` ); } stop() { this.isRunning = false; this.workers.forEach((w) => { try { w.terminate(); } catch (_) {} }); this.workers = []; if (this._timeoutId) { clearTimeout(this._timeoutId); this._timeoutId = null; } console.log('CPU spike simulation stopped'); } getStatus() { return { running: this.isRunning, workerCount: this.workers.length, mainThreadSpike: !!this._timeoutId }; }}module.exports = new CPUSpikeDemo();```
How to Capture Diagnostic Data for Troubleshooting CPU Spike
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 CPU Spike Using the Diagnostic Data
In this section, we’ll see how to analyze a CPU spike 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 Node.js Internals and the CPU profile reports to find the code that is actually using the CPU.
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 to 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 an overloaded worker thread pool. All 8 worker threads were consuming high CPU, leaving no capacity for new jobs. It also flags a blocked event loop (about 1.8 seconds) as a related symptom of that CPU pressure.
Issues in application and device

Fig: RCA Summary highlighting the issues in application and device
As shown in the above screenshot, 5 application-level and 3 device-level issues are reported by the yCrash tool. The 3 that matter most for a CPU spike are:
- Worker pool overloaded
- Event loop blocked
- Hot method
Step 3: Worker thread CPU in Node.js Internals Report
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 Worker pool-overloaded problem statement. This will take you to the Worker Threads section.

Fig: Worker threads in Node.js Internals report
In the worker threads section, you can see that all 8 worker threads are consuming about 367% to 370% CPU on a 4-core machine.
Now let’s click on the “View Details” button displayed in the same row of the thread `top-sustain-cpu-4 (ID: 4)` to inspect its call stack and any captured method profile.

Fig: Worker thread call stack and method profile
For the ` top-sustain-cpu-4 (ID: 4)` thread, the call stack sits inside `crypto.pbkdf2Sync` within the worker’s infinite loop. This tells us that this worker thread burns CPU while doing synchronous cryptographic work.
The worker method profiling is empty for this worker thread because, during the capture, the worker thread was continuously busy in `while (true)` with `pbkdf2Sync`, so it didn’t give the profiler a chance to capture method profiling data.
Step 4: Check whether the main thread is blocked too
On the same Node.js internals report, scroll to the Event Loop Lag section.
One important thing to understand is that worker thread CPU and main-thread CPU are not the same problem in Node.js.
For example, in this blog, the worker threads are using 370% CPU; it means the machine is under heavy CPU load. But that doesn’t necessarily mean your HTTP requests, timers, or health checks are stuck. These are handled by the main event-loop thread.
So, even when worker threads are using multiple CPU cores, the application can still respond to incoming requests as long as the main thread is getting enough CPU time to run.
The situation is different when the main thread itself is consuming high CPU. This can happen because of a tight loop, parsing a very large JSON payload, synchronous crypto operations, a problematic regular expression, or other CPU-intensive work. When the main thread is busy with this kind of work, it cannot process other tasks, and incoming requests have to wait until the main thread becomes available again.
This is where Event Loop Lag becomes useful. It tells how much the event loop is delayed by comparing when a timer was supposed to run with when it actually ran. High event-loop lag is a sign that the main thread is busy and isn’t getting a chance to process other events.

Fig: Event Loop Lag in Node.js Internals report
As you can see in the above graph, from `05:06:56` to `05:07:23` the process couldn’t run timers or callbacks for `~1.8 seconds`.
So this incident is not work-thread-only. The main thread was also blocked, which is why the app would feel hung even after you have seen the pegged worker threads in the worker threads section.
Event Loop Lag does not name the function. To find out the function name, we will review the CPU Profiling report as our next step.
Step 5: 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: ‘run’ used 98.27% of CPU across 18,981 calls.
For deep diagnosis, let’s click on the “Inspect” button in the same row.

Fig: Inspector view of run function
As you can see in the Inspect view of the `run` function above, the Self CPU and Total CPU are both 98.27% across about 19,000 samples on one thread.
The timeline chart shows that from about 05:06:53 to 05:07:25, the count stays high for the whole window.
In the Calling (Parent) Functions tree, `run` is the native frame behind Node’s crypto work. Expand it, and you will see that almost all of that time (98.3%) is spent in `pbkdf2Sync`.
Expand `pbkdf2Sync` one more level, and you can trace the CPU usage back to our application code where we have the while loop in cpu-spike.js that keeps calling synchronous `pbkdf2Sync` over and over.
In this capture, you may also see a similar loop from the TOP-sustain path, which uses the same pattern to keep CPU elevated for M3. So the CPU Profiler does not stop at “CPU is high.”
How to Fix CPU Spike in Node.js
The following are the potential solutions for this issue:
- Cap the number of worker threads to the number of available cores and queue up the work instead of making too many threads.
- Replace synchronous crypto or CPU-heavy work with async APIs or offload to a bounded pool that yields.
- Remove main-thread busy-waits; break long tasks into smaller chunks that yield with `setImmediate()` or similar.
Conclusion
Diagnosing and identifying the root cause of a CPU Spike can be challenging, especially in complex production environments where multiple symptoms often overlap. In this example, the diagnostic data was captured using the yc-360 script and analyzed using yCrash server, which helped correlate the relevant runtime and system-level data to identify the underlying problem.
The analysis traced the issue to CPU-intensive synchronous pbkdf2Sync() calls running continuously inside worker-thread loops, along with a near-continuous pbkdf2Sync burn on the main thread’s loop(). By examining the RCA Summary, the Node.js Internals report (Worker Threads and Event Loop Lag), and the CPU Profiler, we were able to confirm the root cause and determine the appropriate fix.
Applying bounding to the worker pool, replacing synchronous CPU-heavy operations with asynchronous or bounded alternatives, and removing main-thread busy-waits address the underlying problem and help prevent the issue from recurring in the application.
