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.readFileSyncorcrypto.pbkdf2Sync. JSON.parseorJSON.stringifyon 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_threadsor a separate service. - For medium-sized work, split it into chunks and call
setImmediatebetween 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.