← Back to JavaScript, page 9

javascript-0175 · Hard senior

What is microtask starvation, how can it happen with promises or process.nextTick, and how do you yield to the event loop?

The event loop drains the whole microtask queue before it moves on, so a microtask that keeps scheduling another one means timers, I/O, input, and painting never get a turn. process.nextTick in Node.js is even earlier than promise callbacks. The fix is to process work in chunks and yield through a task, such as setTimeout, setImmediate, or scheduler.yield, so other work can run between chunks.

Full answer

After each task, the engine runs microtasks until the queue is empty, including microtasks that were added while draining. If every microtask adds another one, the queue never empties. The event loop is stuck in the microtask phase: timers do not fire, network callbacks wait, and in a browser there is no paint or input handling. The page freezes, although the code is "asynchronous".

How it happens in practice:

  • A recursive promise chain or an async function that loops with await on an already resolved value, for example polling a cache that returns immediately. await on a settled promise only continues in a microtask.
  • A recursive queueMicrotask.
  • In Node.js, process.nextTick callbacks run before promise microtasks, and a recursive nextTick also starves everything else. Node.js limits nothing by default.
  • A retry or drain loop with no real asynchronous boundary.

Timing detail: a promise callback is a microtask, setTimeout and setImmediate callbacks are tasks (macrotasks) in the timers and check phases in Node.js, and I/O callbacks have their own phase. Microtasks run after each callback, in every phase.

Fixes:

  1. Process work in bounded chunks and yield to a real task between them: await new Promise((r) => setTimeout(r)), setImmediate in Node.js, and scheduler.yield() or scheduler.postTask() in browsers that support them, with MessageChannel as a common fallback.
  2. Put heavy CPU work in a worker thread or Web Worker.
  3. For polling, use a real wait or an event instead of a loop of resolved promises.
  4. Use a time budget per chunk (for example 5 ms) rather than an item count, so the chunk size adapts to the machine.

A related design point: yielding has a cost, so do not yield on every item. Yield about every few milliseconds of work. Also make the work cancellable between chunks with an AbortSignal.

Interview angle: explain that "async" does not mean "does not block"; only tasks give other work a chance, and microtasks only give other microtasks a chance.

javascript
const events = [];
const TOTAL = 50000;

function starving() {
  return new Promise((resolve) => {
    let count = 0;
    const step = () => {
      if (++count < TOTAL) queueMicrotask(step);
      else {
        events.push(`starving work done, ${count} microtasks`);
        resolve();
      }
    };
    queueMicrotask(step);
  });
}

function chunked() {
  return new Promise((resolve) => {
    let count = 0;
    const CHUNK = 10000;
    const step = () => {
      const stop = Math.min(count + CHUNK, TOTAL);
      while (count < stop) count++;
      events.push(`chunk finished at ${count}`);
      if (count < TOTAL) setImmediate(step);
      else resolve();
    };
    step();
  });
}

(async () => {
  setImmediate(() => events.push('immediate A ran'));
  await starving();
  await new Promise((resolve) => setImmediate(resolve));
  events.push('--- now the chunked version ---');

  setImmediate(() => events.push('immediate B ran'));
  await chunked();
  await new Promise((resolve) => setImmediate(resolve));
  console.log(events.join('\n'));

  const order = [];
  setImmediate(() => order.push('setImmediate'));
  Promise.resolve().then(() => order.push('promise'));
  process.nextTick(() => order.push('nextTick'));
  queueMicrotask(() => order.push('queueMicrotask'));
  order.push('sync');
  await new Promise((resolve) => setTimeout(resolve, 5));
  console.log(order.join(' > '));
})();

Run with Node.js v24.22.1 as js-175.js; two runs gave identical output. Output: starving work done, 50000 microtasks immediate A ran --- now the chunked version --- chunk finished at 10000 immediate B ran chunk finished at 20000 chunk finished at 30000 chunk finished at 40000 chunk finished at 50000 sync > promise > queueMicrotask > nextTick > setImmediate

Key points

  • The microtask queue is drained completely, including newly added microtasks, before the next task.
  • Recursive promises, awaits on settled values, queueMicrotask, and process.nextTick can starve timers, I/O, and painting.
  • process.nextTick runs before promise callbacks in Node.js.
  • Yield through a task (setTimeout, setImmediate, scheduler.yield) between chunks.
  • Use a time budget for each chunk, a worker for heavy work, and cancellation between chunks.

Common mistakes

  • Believing that async code can never block the page.
  • Looping on await of an already resolved promise.
  • Yielding with another promise, which does not give timers or paint a turn.
  • Yielding on every item, which makes the work much slower.

Follow-ups

  • How would you cancel a chunked job halfway?
  • What is the difference between process.nextTick and queueMicrotask?
  • How does scheduler.yield differ from setTimeout 0?

Tips

  • State that only a task lets other work run.
  • Mention the nextTick before promise order in Node.js.
  • Suggest a time budget per chunk instead of a fixed item count.