debugjavascriptnodejsCriticalpending
Debug: Node.js event loop blocking detection
Viewed 0 times
event loopblockinglagperf_hooksworker_threads
Error Messages
Problem
Node.js application becomes unresponsive or slow. Requests queue up and timeouts increase.
Solution
Detect and fix event loop blocking:
- Detect with built-in diagnostics:
const { monitorEventLoopDelay } = require('perf_hooks');
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
setInterval(() => {
console.log(`Event loop delay: p50=${h.percentile(50)/1e6}ms p99=${h.percentile(99)/1e6}ms`);
h.reset();
}, 5000);- Simple lag detection:
let lastCheck = Date.now();
setInterval(() => {
const now = Date.now();
const lag = now - lastCheck - 1000;
if (lag > 100) console.warn(`Event loop lag: ${lag}ms`);
lastCheck = now;
}, 1000);- Common causes and fixes:
- JSON.parse/stringify on large objects -> use streaming parser
- Synchronous file I/O -> use async versions
- CPU-intensive computation -> use worker_threads
- Large array operations -> chunk with setImmediate
- Regular expressions on large strings -> use RE2 or limit input
Why
Node.js runs JavaScript on a single thread. Any synchronous operation that takes more than a few milliseconds blocks all other requests.
Context
Node.js applications experiencing latency or unresponsiveness
Revisions (0)
No revisions yet.