Skip to the page

How Node runs your code · mid

Blocking the event loop: find it and fix it

Any long synchronous work on the main thread, like a big loop, a huge JSON.parse, a slow regex or a *Sync API in a request handler, blocks the event loop so every other request waits; you find it by measuring event loop delay and CPU profiles, and fix it by limiting input, splitting the work or moving it off the main thread.

The notes

What you must know

  • Typical blockers: CPU-heavy loops; JSON.parse/stringify of big payloads (the Node guide measured about 1.3 s to parse 50 MB); catastrophic regexes (ReDoS, e.g. nested quantifiers like (a+)*); sync APIs (fs.readFileSync, crypto.pbkdf2Sync, zlib.*Sync, execSync) inside request handlers.
  • Measure: perf_hooks.monitorEventLoopDelay() gives a histogram of loop delay (watch p99); CPU profiles with node --cpu-prof or --inspect and Chrome DevTools; APM tools show event loop lag.
  • Fix 1: limit input size (body limits, max JSON size, pagination instead of 'return everything').
  • Fix 2: split the work into chunks and yield between chunks with setImmediate, so other callbacks can run.
  • Fix 3: move CPU work to worker_threads (a pool such as Piscina) or to a background job or another service.
  • Sync APIs are fine at startup (reading config once), not in hot request paths.
  • A blocked loop also delays timers, health checks and keep-alive replies, so the load balancer may mark the instance unhealthy and restart it.

The red pen

Common traps: mistake → fix

  • Mistake: Making a function async makes it non-blocking

    Fix: an async function still runs its synchronous code on the main thread; only awaited I/O lets other work run.

  • Mistake: Promise.all runs CPU work in parallel

    Fix: it only waits for things concurrently; JavaScript CPU work still runs one piece at a time on one thread.

  • Mistake: Sync fs calls are always wrong

    Fix: they are fine at startup; the problem is using them in request handlers.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does 'blocking the event loop' mean? Give three real examples.
  2. One endpoint does heavy work and the whole API slows down. Why, and how do you prove it?
  3. How do you fix it without changing the API contract?
  4. What is ReDoS and how do you protect an API from it?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview