EVENT LOOP STARVATION

One long task and every other request waits

L112 MINRACE CONDITIONS
PREDICT

A Node service starts a synchronous JSON.parse that takes 400 ms. A GET /health request arrives 100 ms into it. When does the health handler run?

A single-threaded event loop runs one task at a time, to completion. Timers, incoming requests and I/O callbacks go into a queue and run when the current task returns. A synchronous 400 ms JSON.parse is one task, so a health check due at 100 ms waits until 400 ms. The fix is to make the long task give the loop back: process a slice, await new Promise(r => setImmediate(r)), process the next slice. A bare await on an already-resolved promise is not enough: it only runs microtasks, and the probe still waits. The queue drains between slices, and the probe waits at most one slice. If one slice is still too long, the work does not belong on this thread: post it to a worker.

▶ SIMULATION
IMPORT REQUEST
mode: — (not arrived)
rows: 0 / 10,000
slices run: 0
EVENT LOOP (one thread)
t = 0 ms
last ran: —
queue: empty
timers: none
HEALTH PROBE
due: —
answered: —
latency: —
timeout: 200 ms
longest queue wait0 ms (budget 200 ms)
✓ no queued task waits longer than 200 ms
SCHEDULE
01[A]POST /import arrives: JSON.parse 10,000 rows, synchronous
02[B]kubelet schedules GET /health for t=100 ms
03[LOOP]event loop: next turn
04[LOOP]event loop: next turn
05[LOOP]event loop: keep turning until the queue is empty
Start of blocking task scenario. 5 steps.
app.post('/import', (req, res) => {
  const rows = JSON.parse(req.body);   // 400 ms of CPU. Nothing else runs.
  for (const r of rows) insert(r);
  res.send('ok');
});
app.get('/health', (req, res) => res.send('ok'));   // queued behind the loop

Watch the invariant strip after the loop’s first turn in BLOCKING TASK: the probe has been in the queue longer than its timeout, so it has already failed before the handler ever runs. A few failures like that in a row and the kubelet restarts the pod. In FIX: CHUNKED, drag ROWS PER SLICE and watch the longest wait track the slice length.

TUNE IT NOT YET

The probe SLO is 25 ms, not 200. The import still has at least 400 ms of CPU to do. A probe can arrive at any moment in a slice, so find a slice size that keeps every slice, and so the worst queue wait, under 25 ms.

GOAL: every slice <= 25 ms and longest queue wait <= 25 ms, with IMPORT CPU >= 400 ms

FIX IT NOT YET

Each item costs 1 ms of CPU. A probe arrives every 100 ms, starting at any moment, and must be served within 50 ms. Rewrite processAll so it yields to the loop often enough, and still processes every item exactly once.

Mental model:

on an event loop, latency is the longest task, not the average. Anything you run synchronously is a lock on the whole process for that long. Keep every task shorter than your latency budget by yielding between slices, and move anything that cannot be sliced to a worker.

IN PRODUCTION

Node and browser code that parses, serializes, compresses, hashes or sorts a large payload inline; a regex with catastrophic backtracking; a tight loop over a big array in a request handler. The symptom is failed health checks, a frozen UI, or p99 spikes that look like network problems.

IN INTERVIEWS

“Why did the health check fail if the process was fine?” and “How would you make this handler not block?” Say that the loop runs one task to completion, name event-loop lag as the metric, and give both fixes: chunk with setImmediate for work you can slice, a worker thread for work you cannot.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.

USED IN

Chapters that build on this lesson.

NEXT: LIVELOCK & PRIORITY INVERSION →