Detecting and diagnosing event loop lag
production diagnosis of a blocked single thread.
measure delay between scheduled and actual timer fire, expose it as a metric, find synchronous CPU-bound code.
WHAT THIS TESTS This evaluates whether the candidate understands that Node runs JavaScript on one thread, and can observe and fix the symptom when that thread is monopolized. It is a core production-readiness signal.
A GOOD ANSWER COVERS Event loop lag is the gap between the time a callback was scheduled to run and the time it actually ran. Because all JavaScript shares one thread, any long synchronous operation delays every pending timer, I/O callback, and incoming request, inflating latency across the board. To detect it, use perf_hooks.monitorEventLoopDelay, which gives a histogram with min, max, mean, and percentiles, or a library that schedules a timer and measures the drift. Sample it periodically, export it to Prometheus or a similar system, and alert when p99 lag crosses a threshold. To diagnose the cause, capture a CPU profile with the inspector or clinic.js flame graphs to see which synchronous function dominates.
COMMON WRONG ANSWERS Reaching straight for more pods or a bigger instance without identifying the blocking code, which only hides the problem. Confusing high CPU from many concurrent requests with a single blocking call. Assuming async/await alone prevents blocking; await does not help if the awaited function itself runs synchronous CPU work.
LIKELY FOLLOW-UPS How would you offload CPU work? When do worker threads versus child processes make sense? How do you set a sane lag threshold? What is the difference between lag from CPU work versus from a saturated thread pool?
ONE CONCRETE EXAMPLE A reporting endpoint synchronously parsed and transformed a large JSON payload. Under load, monitorEventLoopDelay showed p99 lag spiking to hundreds of milliseconds, and unrelated health checks began timing out. A flame graph pinpointed the synchronous transform. Moving the heavy computation to a worker thread restored lag to near zero and unblocked every other request.
Read the original → nodejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.