Back to results for “Advanced Node.js”
Node.js › Advanced Node.js

How do you detect and prevent event loop blocking in a long-running Node.js service?

Advanced

Answer

Event loop blocking happens when synchronous code (a large JSON.parse, a tight computational loop, a synchronous crypto operation) runs long enough to delay all other pending callbacks, timers, and I/O -- detectable via tools like the loopbench or blocked-at packages, which measure the delay between when a timer should fire and when it actually does. Prevention means offloading CPU-heavy work to worker threads, breaking large synchronous loops into chunks processed across multiple event loop ticks, and using streaming (rather than loading entire payloads into memory) for large data.
const blocked = require('blocked-at');
blocked((time, stack) => {
  console.log(`Blocked for ${time}ms`, stack);
}, { threshold: 100 });

// Chunking a large synchronous loop across ticks
function processInChunks(items, i = 0) {
  const end = Math.min(i + 1000, items.length);
  for (; i < end; i++) { /* process items[i] */ }
  if (i < items.length) setImmediate(() => processInChunks(items, i));
}
Real-world example An API that occasionally froze for several seconds under load is traced, using blocked-at, to a synchronous bcrypt.hashSync() call on the main thread; switching to the async bcrypt.hash() variant (which offloads to the libuv thread pool) eliminates the freezes entirely.

Common follow-ups: What's the practical difference between offloading work to a worker thread versus just chunking it across setImmediate() calls?;How would you set up automated alerting for event loop lag in production?