CodePark/ questions / Event loop phases
START PRACTICINGPRACTICE
Backend question · Node.js › Event loop phases

What does it mean to block the event loop? Give examples and explain how to avoid it.

Blocking the event loop means one callback runs so long that nothing else can run. The event loop runs only one callback at a time. While a slow callback runs, Node handles no other request, timer or finished I/O until it returns. So every client waits longer.

Common causes:

  • Synchronous APIs in a request handler, like fs.readFileSync or crypto.pbkdf2Sync.
  • JSON.parse or JSON.stringify on very large payloads.
  • Regular expressions with catastrophic backtracking: the regex tries a huge number of paths on some inputs. Attackers can use this, which is called ReDoS (Regular expression Denial of Service).
  • Heavy loops, such as sorting huge arrays or processing images.

How to avoid it:

  • Use the async versions of APIs.
  • Limit input sizes.
  • Use safe regexes.
  • Move CPU-heavy work to worker_threads or a separate service.
  • For medium-sized work, split it into chunks and call setImmediate between them, so other callbacks get a turn.

Measure the delay with perf_hooks.monitorEventLoopDelay.

  • The loop runs one callback at a time, so a slow one delays everyone.
  • Common causes are sync fs or crypto calls, huge JSON, ReDoS and heavy loops.
  • Use async APIs and limit input sizes.
  • Move CPU-heavy work to worker threads or another service.
  • Split work into chunks with setImmediate, and monitor event loop delay.