Node.js Event Loop Phases
Give a real production-style example of using Node.js Event Loop Phases. Walk through the scenario end-to-end.
Answers use simple, clear English.
Quick interview answer
Scenario: API server: heavy sync JSON.parse in request handler blocks the poll phase and delays all concurrent connections. Implementation notes: Offload CPU work to worker_threads; never block the event loop in hot paths.
Detailed answer
Scenario: API server: heavy sync JSON.parse in request handler blocks the poll phase and delays all concurrent connections. Implementation notes: Offload CPU work to worker_threads; never block the event loop in hot paths. Core: Node runs libuv phases: timers → pending → idle/prepare → poll → check (setImmediate) → close. process.nextTick and Promise microtasks run between phases and can starve I/O if abused. Real-time example: API server: heavy sync JSON.parse in request handler blocks the poll phase and delays all concurrent connections. Pros: Single-threaded model simplifies reasoning; non-blocking I/O scales connection count. Cons: CPU-bound work blocks the loop; microtask flooding delays timers. Common mistakes: Assuming setTimeout(0) runs before setImmediate always (order varies at startup). Best practices: Offload CPU work to worker_threads; never block the event loop in hot paths. Audience level: Junior.
Full explanation
Node runs libuv phases: timers → pending → idle/prepare → poll → check (setImmediate) → close. process.nextTick and Promise microtasks run between phases and can starve I/O if abused.
Real example & use case
API server: heavy sync JSON.parse in request handler blocks the poll phase and delays all concurrent connections.
Pros & cons
Pros: Single-threaded model simplifies reasoning; non-blocking I/O scales connection count. Cons: CPU-bound work blocks the loop; microtask flooding delays timers.
Common mistakes
Assuming setTimeout(0) runs before setImmediate always (order varies at startup).
Best practices
Offload CPU work to worker_threads; never block the event loop in hot paths.
Follow-up questions
- How would you test Node.js Event Loop Phases?
- What metrics prove Node.js Event Loop Phases is healthy in prod?
- How does Node.js Event Loop Phases change at 10× traffic?