Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Concepts and Pitfalls

Blocking the Node.js event loop

How long synchronous code blocks the Node.js event loop, how to measure event-loop delay, and fixes: chunking, worker threads, streaming and safer regexes.

All JavaScript in a Node.js process runs on one thread. While a function is running, nothing else on that thread can happen: no timer fires, no request is read, no response is written. If a handler spends 300 ms in a tight loop, every other client waits at least 300 ms, even if their own work is trivial. This is called blocking the event loop, and it is the most common cause of "Node is slow" reports.

The loop is blocked by anything long and synchronous: heavy computation, JSON.parse() of a huge string, a *Sync file call, a catastrophic regular expression, or a giant for loop over a big array. The symptoms are rising latency for all requests, timeouts under modest load, and a CPU core pinned at 100% while throughput stays low.

NODE
const start = Date.now();
setTimeout(() => console.log('late'), 10);
while (Date.now() < start + 100) {} // the timer cannot run for 100 ms

Try it

Node.js Measuring a blocked loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Fix 1: yield with setImmediate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Fix 2: a worker thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

How to notice it

  • Event-loop delay. perf_hooks.monitorEventLoopDelay() samples how late a timer fires. Report the p99 and max; a p99 of tens of milliseconds on an otherwise idle server means something is blocking.
  • Event-loop utilization. performance.eventLoopUtilization() returns the fraction of time the loop was busy. Values near 1 mean the thread is saturated.
  • CPU profile. node --cpu-prof app.js or the inspector shows which function holds the thread.
  • Symptoms. Latency spikes affecting unrelated routes at the same moment, health checks failing, WebSocket heartbeats missed.
NODE
import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay({ resolution: 10 });
h.enable();
// later: h.percentile(99) / 1e6  -> milliseconds

Common causes and fixes

Cause Fix
CPU-heavy loops (image resizing, hashing, parsing) Worker threads, a worker pool library, or a separate service
fs.readFileSync, execSync in request handlers Use the promise or callback versions
JSON.parse or JSON.stringify of very large data Stream and parse in pieces, paginate, or move to a worker
Regular expressions with nested quantifiers on user input Rewrite the pattern, limit input length, or use a safe matcher
Sorting or mapping huge arrays Chunk with setImmediate, or compute ahead of time
Synchronous crypto (pbkdf2Sync, scryptSync) Use the asynchronous versions (they run in the thread pool)
Huge await chains over many awaitables with heavy callbacks Limit concurrency and yield between batches

Usage notes

  • async does not mean non-blocking. An async function runs synchronously until its first await; CPU work inside it still blocks.
  • await between slices is not enough if the awaited promise is already resolved: promise callbacks are microtasks and run before I/O. Yield with setImmediate (or scheduler.yield() where available) to let I/O in.
  • Worker threads cost memory and startup time (tens of milliseconds, several MB). Reuse a pool for repeated jobs.
  • Startup code may block. Reading a config file synchronously before the server listens is fine; nobody is waiting yet.
  • Catastrophic regexes are a denial-of-service risk: a short crafted string can take seconds. Treat patterns applied to user input as security-relevant.
  • Process-level fixes (cluster, more instances) add capacity but do not shorten a single blocked tick.