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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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
- What does 'blocking the event loop' mean? Give three real examples.
- One endpoint does heavy work and the whole API slows down. Why, and how do you prove it?
- How do you fix it without changing the API contract?
- 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 voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.