Sub topic 15
Blocking the Loop and Starving It with Microtasks
This chapter assumes you already know how the call stack, the task queue, and the microtask queue work together, and that you can trace the output order of code that mixes timers, promises, and async/await. It also assumes you know where rendering sits in the browser loop and how Node.js splits its loop into phases. Here we use that model to explain the two most common ways an application stops responding. The first is blocking, where one piece of work runs too long. The second is microtask starvation, where the microtask queue never empties.
Why one long task freezes everything
JavaScript runs each task to completion. While a function is on the call stack, the event loop cannot take the next task, drain microtasks, or render a frame. Anything waiting stays queued: a click handler, a timer callback, a network response, an incoming HTTP request in Node.js.
A blocked loop doesn't throw an error or log a warning. Everything simply waits. In the browser, buttons ignore clicks, animations freeze, and text input lags. In Node.js, a single slow request handler delays every other client connected to the process.
The size of the pause matters. At 60 Hz, a browser has about 16.7 ms per frame. The browser counts any task longer than 50 ms as a "long task". Interaction to Next Paint (INP), the responsiveness metric, rates a page as good only when its slowest interactions finish in 200 ms or less.
A blocked Node.js server
This server handles two routes. The /slow route does CPU work synchronously, so it holds the thread for the whole computation.
const http = require('http');
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
http.createServer((req, res) => {
if (req.url === '/slow') {
const result = fib(42); // several seconds of synchronous work
res.end(`fib: ${result}\n`);
} else {
res.end('fast\n');
}
}).listen(3000, () => console.log('listening on 3000'));Run curl localhost:3000/slow in one terminal, then curl localhost:3000/fast right away in another. The fast request doesn't answer until the slow one finishes. The new connection reaches the operating system, but its callback can't run until the poll phase comes around again, and that can't happen while fib is on the stack.
Common sources of blocking
| Source | Example | Why it blocks |
|---|---|---|
| Heavy loops and recursion | Image processing, `fib(42)`, nested loops over large arrays | Pure CPU work on the main thread |
| Big serialization | `JSON.parse` or `JSON.stringify` on tens of MB | Runs as one synchronous call |
| Synchronous Node.js APIs | `fs.readFileSync`, `crypto.pbkdf2Sync`, `zlib.gzipSync` | Waits for I/O or crypto on the main thread |
| Catastrophic regex backtracking | `/^(a+)+$/.test('a'.repeat(30) + 'b')` | One `test` call can run for seconds |
| Large DOM updates | Inserting thousands of nodes, then reading layout | Forces style and layout work in one task |
| Sorting or searching huge arrays | `array.sort()` on millions of items | One synchronous call |
Microtask starvation
Starvation is less obvious. Every single callback can be fast, and the loop still stops.
The event loop drains the microtask queue completely before it moves on. If a microtask queues another microtask, that new one also runs in the same drain. If this happens over and over, the loop never reaches the next task or the rendering step. Timers don't fire, input isn't handled, and the page doesn't repaint.
The next script shows starvation in a bounded form. It schedules a zero-delay timer and then a chain of one million microtasks.
let count = 0;
const start = Date.now();
setTimeout(() => {
console.log(`timer fired after ${count} microtasks and ${Date.now() - start} ms`);
}, 0);
function spin() {
count++;
if (count < 1_000_000) {
queueMicrotask(spin);
}
}
queueMicrotask(spin);
// Output: timer fired after 1000000 microtasks and <some> msThe timer waits for the whole chain to finish, because each spin call refills the queue before the loop can look at the timer. Remove the if and the timer never fires: the tab hangs or the Node.js process keeps one CPU core at 100%.
Hidden starvation with await
Starvation often comes from awaiting values that are already resolved. Each await resumes in a microtask, so a loop of awaits on resolved values never gives the event loop a chance to run tasks.
async function sumAll(items) {
let total = 0;
for (const item of items) {
total += await item; // already-resolved values: each resume is a microtask
}
return total;
}
setTimeout(() => console.log('timer'), 0);
const items = Array.from({ length: 500_000 }, (_, i) => Promise.resolve(i));
sumAll(items).then((total) => console.log('total', total));
// Output: total 124999750000, then timerThe code looks asynchronous, so people assume it yields. It doesn't. Only work that waits on a task-based source (a timer, I/O, a message) gives the loop a chance to run other tasks.
Starvation in Node.js
Node.js has an extra queue that runs ahead of the others. The process.nextTick queue is drained before the promise microtask queue. A recursive process.nextTick therefore starves promise callbacks as well as timers and I/O. Node.js doesn't cap this recursion, so the process stops serving requests while it keeps running. setImmediate doesn't have this problem: callbacks scheduled while the check phase runs wait for the next iteration, so I/O gets its turn in between.
Blocking versus starvation
| Aspect | Blocking | Microtask starvation |
|---|---|---|
| Cause | One task or callback runs too long | The microtask queue keeps refilling |
| Call stack | Busy with one long call | Empties briefly between microtasks |
| What a profile shows | One long function | Thousands of short calls inside one long task |
| Typical code | Heavy loops, sync APIs, regex | Recursive `then`, `queueMicrotask`, `nextTick`, awaits on resolved values |
| Fix direction | Split the work or move it off the thread | Yield to the task queue between steps |
From the user's point of view, both look the same: the page or server doesn't respond. The difference shows up in a profiler. That is why measuring comes before fixing.
Detecting a stalled loop
In the browser
Chromium-based browsers support the Long Tasks API, which reports any task over 50 ms. Other browsers may not support it, so check for support before you rely on it.
if (PerformanceObserver.supportedEntryTypes.includes('longtask')) {
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('long task:', Math.round(entry.duration), 'ms');
}
}).observe({ type: 'longtask', buffered: true });
}The Performance panel in DevTools marks long tasks with a red corner. Expand one to see whether it contains one heavy function (blocking) or a long row of tiny microtask calls (starvation).
In Node.js
perf_hooks.monitorEventLoopDelay samples how late the loop runs compared with when it should have run. The histogram values are in nanoseconds.
const { monitorEventLoopDelay } = require('perf_hooks');
const histogram = monitorEventLoopDelay({ resolution: 20 });
histogram.enable();
// Simulate a 300 ms block after 100 ms
setTimeout(() => {
const start = Date.now();
while (Date.now() - start < 300) {}
}, 100);
setTimeout(() => {
histogram.disable();
console.log('max delay ms:', (histogram.max / 1e6).toFixed(1));
console.log('p99 delay ms:', (histogram.percentile(99) / 1e6).toFixed(1));
}, 1000);
// max delay is roughly 300 msIn production, export these numbers as metrics. A p99 delay that keeps rising usually means some request handler is doing synchronous work that grows with the input.
Fixing it
The fixes for both problems follow from the model:
- For starvation, break the chain so it goes through the task queue at intervals, for example with
setTimeout,setImmediate, orMessageChannel. This lets timers, I/O, and rendering run between steps. - For blocking, either split the work into smaller tasks or move it to another thread.
- Replace synchronous Node.js APIs with their asynchronous versions in any code that serves requests.
- Rewrite regular expressions with nested quantifiers, and limit the input length before you test it.
The next chapter covers chunking and Web Workers in detail.
Exercise
A page runs function poll() { fetchCache().then(poll); } where fetchCache returns Promise.resolve(cachedValue). Clicks stop working after this starts. Is this blocking or starvation, and why do clicks never get handled?
Show answer
It is microtask starvation. Each then(poll) callback calls fetchCache, which returns an already-resolved promise, so a new microtask is queued right away. The event loop drains microtasks until the queue is empty, and here it never empties, so the loop never reaches rendering or the next task, such as a click event.
Exercise
In Node.js, what does this print, and in what order? setTimeout(() => console.log('timeout'), 0); let n = 0; function tick() { if (++n < 3) process.nextTick(tick); else console.log('ticks done'); } process.nextTick(tick); Promise.resolve().then(() => console.log('promise'));
Show answer
It prints "ticks done", then "promise", then "timeout". The nextTick queue, including ticks added while it is being drained, empties before promise microtasks run. Timers run only after all of that, in the timers phase.
Exercise
An Express handler does const data = JSON.parse(fs.readFileSync(bigFile, 'utf8')) on every request, and the p99 event loop delay grows with traffic. Name the two blocking operations and give one change for each.
Show answer
fs.readFileSync blocks while it waits for disk I/O. Replace it with await fs.promises.readFile, or read the file once at startup and cache it. JSON.parse on a large string blocks while it parses. Parse once and cache the result, or move the parsing to a worker thread if the data changes per request.