Asynchronous and Event-Driven Programming Questions
The programming model of a single asynchronous runtime: callbacks, promises and futures, async/await, event loops and task/microtask scheduling (including microtask starvation and where rendering fits), reactive streams and back-pressure, and how ordering, cancellation, timeouts, retries and error propagation behave across JavaScript, Node.js, mobile coroutine or async runtimes, and a comparison with Python asyncio and Java futures. Includes the async mechanics of a data fetch such as parallel versus sequential requests, partial failure, stale or out-of-order responses, abort, debounced live search, single-flight token refresh, and bounded concurrency; wrapping callback APIs as promises, streaming work through async consumers, moving heavy work off the main thread and back, and diagnosing unhandled rejections, race conditions and leaked subscriptions. Excludes message-queue and pub/sub system design, server throughput and thread-pool tuning, per-language threading and memory models, rebuilding standard APIs from scratch, and fetch caching or state architecture.
What is a promise and what states can it be in? Walk through what happens when you attach a handler before it settles and after it settles, why a handler never runs synchronously, and what a thenable is.
Sample Answer
Direct answer
A promise is an object that stands for the eventual result of an asynchronous operation. It starts pending and settles exactly once, either fulfilled (with a value) or rejected (with a reason, usually an Error). After it settles it never changes. You attach handlers with .then, .catch and .finally. A handler attached before the promise settles waits in the promise's reaction list (the promise's internal list of handlers waiting for it to settle); a handler attached after it settled is queued straight away. Either way the handler never runs synchronously: the engine always runs it later as a microtask, so a caller never sees a callback fire before the line that registered it has finished. A thenable is any object with a then method; resolve(), Promise.resolve() and await adopt it (take over its outcome, so the new promise settles however the thenable settles) by calling its then, which is how different promise libraries interoperate.
States and the one-way rule
| State | Meaning | Can change to |
|---|---|---|
| pending | Work not finished | fulfilled or rejected |
| fulfilled | Finished with a value | nothing (final) |
| rejected | Failed with a reason | nothing (final) |
"Settled" means fulfilled or rejected. Calling resolve or reject a second time has no effect, which the example below demonstrates.
Handlers before and after settling, and why they are never synchronous
The program below puts every case in one run and prints the order.
const out = [];
const log = (m) => out.push(m);
// 1. Handler attached after the promise already settled: it still runs later, never inline.
const settled = Promise.resolve('value');
log('sync: before then()');
settled.then((v) => log('handler on already-settled promise got ' + v));
log('sync: after then()');
// 2. Handler attached before settlement: queued until resolve is called.
let resolveLater;
const pending = new Promise((res) => { resolveLater = res; });
pending.then((v) => log('handler attached while pending got ' + v));
log('sync: resolving now, handler has not run');
resolveLater('later');
// 3. A thenable: any object with a then method is adopted by resolve / await.
const thenable = { then(onFulfilled) { log('then() of the thenable called'); onFulfilled('from thenable'); } };
Promise.resolve(thenable).then((v) => log('adopted value: ' + v));
// 4. finally: runs on either outcome, gets no argument, passes the original result through.
Promise.reject(new Error('boom'))
.finally((...args) => log('finally ran with ' + args.length + ' arguments'))
.catch((e) => log('catch still sees ' + e.message));
// 5. Wrapping a callback API with new Promise
function legacyRead(cb) { setTimeout(() => cb(null, 'file contents'), 1); }
const readP = () => new Promise((resolve, reject) => legacyRead((err, data) => (err ? reject(err) : resolve(data))));
readP().then((v) => log('wrapped callback API gave ' + v));
// 6. States are one-way: a second resolve is ignored
const once = new Promise((res, rej) => { res('first'); res('second'); rej(new Error('ignored')); });
once.then((v) => log('settled once with ' + v));
setTimeout(() => {
console.log(out.join('\n'));
console.log('handlers never ran inline:', out.indexOf('sync: after then()') < out.indexOf('handler on already-settled promise got value'));
}, 30);
Run in a Node 22 container, it prints:
sync: before then()
sync: after then()
sync: resolving now, handler has not run
handler on already-settled promise got value
handler attached while pending got later
then() of the thenable called
finally ran with 0 arguments
settled once with first
adopted value: from thenable
catch still sees boom
wrapped callback API gave file contents
handlers never ran inline: true
Reading the output. Handlers go into the microtask queue in the order the promises were ready for them, and a job that queues more work puts it at the back. After the synchronous code finishes, the queue holds five jobs, in source order: the handler on the already-settled promise (case 1), the handler on the promise resolved by resolveLater (case 2), the job that will call the thenable's then (case 3), the finally handler (case 4) and the settled once handler (case 6). They run in that order, which gives lines 4 to 8, except that the thenable's handler is not in the queue yet:
-
The thenable job calls
then()of the thenable (line 6). That call resolves the promise, and only then is theadopted valuehandler queued, at the back of the queue, behind thefinallyandsettled oncejobs. That is whyadopted value(line 9) prints aftersettled once(line 8), andthen() of the thenable called(line 6) prints beforefinally ran(line 7): the thenable job was queued before thefinallyhandler, but its handler needs a second queue pass. -
The
catch still sees boomline (line 10) comes later still, becausefinallyitself returns an internal promise that must settle before the rejection continues down the chain. -
Attached after settling:
Promise.resolve('value').then(...)registers a handler on an already-fulfilled promise. Thesync:lines show the handler did not run inline; it ran after the script's synchronous code finished. -
Attached before settling: the handler waits while the promise is pending; calling
resolveLatermoves it into the microtask queue, but still not inline. -
Why never synchronous: if a handler could sometimes run immediately (already settled) and sometimes later (pending), the same code would have two different orderings depending on timing. Always deferring gives one predictable order, and callers can rely on finishing their own setup first. The same reason applies to the thenable line:
Promise.resolve(thenable)does not callthenable.thenimmediately, it queues that call as a microtask, so the adopted value arrives one queue pass later than an ordinary resolved value: first a job calls the thenable'sthen, then the handler is queued. -
Thenable: the object with a
then(onFulfilled)method was adopted: itsthenwas called with resolver functions, and its value became the promise's result. -
finally: runs on success or failure, receives no argument (0 arguments in the output), and passes the original outcome through, so the followingcatchstill saw the originalboomerror. -
Settle once:
res('first'); res('second'); rej(...)kept only the first.
Wrapping a callback API with new Promise
Callback APIs use cb(err, data). Wrap them once so the rest of the code can use promises or await:
const readP = () => new Promise((resolve, reject) =>
legacyRead((err, data) => (err ? reject(err) : resolve(data))));
The executor is the function passed to new Promise((resolve, reject) => ...). It runs synchronously and immediately; only the handlers are deferred. For Node's standard error-first functions, util.promisify does this wrapping for you.
Callbacks versus promises
| Callback | Promise | |
|---|---|---|
| Who controls when your code runs | The API that receives your function; it could call it twice, never, or synchronously | The promise: settles once, and handlers run once, asynchronously |
| Errors | Passed as the first argument, you must check each time | A rejection travels down the chain to the next .catch |
| Composition | Nested functions | Chains, Promise.all, and await |
Pitfalls
- Forgetting to
returna promise inside a.then: the next step does not wait for it. - Throwing inside a
new Promiseexecutor works (it rejects the promise), but throwing inside a plain callback inside it, after the executor returned, does not. The first promise below is rejected and caught; the second stays pending forever and the error escapes as a process-leveluncaughtException.
process.on('uncaughtException', (e) => console.log('uncaughtException:', e.message));
// Throwing directly in the executor rejects the promise.
new Promise(() => { throw new Error('sync throw'); })
.catch((e) => console.log('caught:', e.message));
// Throwing inside a timer callback started by the executor does not: the executor
// has already returned, so the error is not turned into a rejection.
const p = new Promise(() => { setTimeout(() => { throw new Error('late throw'); }, 0); });
p.catch(() => console.log('never printed'));
Run in a node:22 container as late_throw.js (Node 22), it prints:
caught: sync throw
uncaughtException: late throw
- Treating
finallyas a place to transform the result: its return value is ignored unless it throws or returns a rejected promise.
Running the code
docker run --rm --ulimit core=0 -v "$PWD":/w -w /w node:22 node promise_states.js
docker run --rm --ulimit core=0 -v "$PWD":/w -w /w node:22 node late_throw.js
Save the large block as promise_states.js and the pitfall block as late_throw.js. Both are CommonJS files and need no install or config.
In a Node.js service, an engineer schedules follow-up work with several different mechanisms and sees an order they did not expect, and under load the service stops serving I/O. Explain how Node schedules those callbacks, the order they run in, and how one of them can starve the rest and what you would change.
Sample Answer
Direct answer
Start here: in one line, the order is synchronous code, then process.nextTick callbacks, then promise callbacks, then the event loop phases, where a recursive nextTick or promise chain stops the phases from ever running.
Node (a JavaScript runtime built on the V8 engine and on libuv, the C library that implements the event loop and non-blocking I/O) runs your script, then empties two queues that sit outside the event loop phases: first the process.nextTick queue, then the promise microtask queue. After that the event loop proper takes over and works through its phases, in this order, once per loop turn: timers (setTimeout/setInterval callbacks whose delay has elapsed), pending callbacks (a few deferred system-level callbacks, such as certain TCP errors), poll (waits for and runs I/O callbacks: a finished file read, data arriving on a socket), check (setImmediate callbacks), and close callbacks (for example a socket's 'close' handler). I/O means input/output, work that waits on the disk or the network. Starvation happens when something keeps refilling a queue that must be emptied before the loop can move on: the classic case is a recursive process.nextTick, which stops the loop ever reaching the poll phase, so no I/O callbacks run (the loop is stuck emptying the nextTick queue and never gets to the step where it picks up finished file reads and incoming network data). The fix is to schedule the follow-up work with setImmediate (or break the work into slices, or move it to a worker thread) so each step returns control to the loop.
How Node orders the mechanisms
| Mechanism | Where it runs | Rule |
|---|---|---|
process.nextTick(fn) | Queue drained right after the current operation, in whatever phase the loop is in | Node's docs: it is not part of the event loop, and all nextTick callbacks resolve before the loop continues |
Promise reaction / await continuation | Microtask queue, drained after the nextTick queue (CommonJS) | Same "empty it completely" rule as in browsers |
setTimeout(fn, 0) | Timers phase | Runs on a later loop turn, once the delay has elapsed |
setImmediate(fn) | Check phase, right after poll | Runs after I/O callbacks in the current loop turn |
The Node event loop documentation describes the phases this way: timers run setTimeout and setInterval callbacks; poll retrieves new I/O events and runs I/O callbacks; check runs setImmediate callbacks. It also notes that since libuv 1.45.0 (Node 20) timers run after the poll phase in each iteration, where earlier versions ran them before polling. This detail only matters when reasoning about timer versus I/O ordering across Node versions; the nextTick, promise and setImmediate rules in the table do not depend on it.
Observed order
The script below schedules the same four mechanisms twice: once from the main module and once from inside an I/O callback (fs.readFile), and checks the orders that are guaranteed. Each schedule(tag) call logs one sync line immediately and queues the other four, so out ends up holding every line in the order it happened. The final setTimeout after 100 ms waits until everything has run, then prints the main: lines without the two racy ones, and prints the io: lines in full. The indexOf comparisons at the bottom turn the two guaranteed orders into true or false.
const fs = require('node:fs');
const out = [];
const log = (m) => out.push(m);
function schedule(tag) {
setTimeout(() => log(tag + ' setTimeout 0'), 0);
setImmediate(() => log(tag + ' setImmediate'));
Promise.resolve().then(() => log(tag + ' promise microtask'));
process.nextTick(() => log(tag + ' nextTick'));
log(tag + ' sync');
}
schedule('main:');
fs.readFile(__filename, () => {
schedule('io:');
});
setTimeout(() => {
const main = out.filter(s => s.startsWith('main:'));
const io = out.filter(s => s.startsWith('io:'));
console.log(main.filter(s => !/setTimeout|setImmediate/.test(s)).join('\n'));
console.log('main: setTimeout 0 and setImmediate both ran (order varies):', main.length === 5);
console.log('--- inside the readFile callback');
console.log(io.join('\n'));
console.log('main: nextTick before promise:', main.indexOf('main: nextTick') < main.indexOf('main: promise microtask'));
console.log('io: setImmediate before setTimeout:', io.indexOf('io: setImmediate') < io.indexOf('io: setTimeout 0'));
}, 100);
Run as a CommonJS file in a Node 22 container (Node 22.23.3), it prints:
main: sync
main: nextTick
main: promise microtask
main: setTimeout 0 and setImmediate both ran (order varies): true
--- inside the readFile callback
io: sync
io: nextTick
io: promise microtask
io: setImmediate
io: setTimeout 0
main: nextTick before promise: true
io: setImmediate before setTimeout: true
- Fixed: nextTick, then promise microtask, then everything else. Inside an I/O callback,
setImmediatealways runs beforesetTimeout(fn, 0): the callback runs in the poll phase, and the check phase follows it before the loop returns to the timers phase. Node's documentation states this guarantee too. - Not fixed (main module):
setTimeout(fn, 0)againstsetImmediatedepends on how fast the process reaches the timers phase. Across 15 separate container runs of a script that only logged those two, both orders appeared, withimmediatefirst in most runs. Do not rely on either.
The module-system surprise
CommonJS is Node's original module format (require() and module.exports; files ending in .js by default or .cjs). An ES module is the standard import/export format (files ending in .mjs, or .js with "type": "module"). The nextTick-before-promise rule holds in a CommonJS file. In an ES module the order flips: the promise callback runs before the nextTick callback. This tiny file shows it:
const out = [];
process.nextTick(() => out.push('nextTick'));
Promise.resolve().then(() => out.push('promise'));
setTimeout(() => console.log('ES module main:', out.join(' then ')), 10);
Run as a .mjs file in the same container, it prints:
ES module main: promise then nextTick
The reason, from the Node documentation: every time the nextTick queue is drained, the microtask queue is drained immediately after, so in CommonJS nextTick callbacks run first. An ES module, however, is itself evaluated as part of the microtask queue, so Node is already draining microtasks when your top-level code schedules its callbacks, and the promise callbacks run before the nextTick ones.
So an engineer who tests with .cjs and ships .mjs (or the reverse) can see exactly the "unexpected order" in the question.
How one mechanism starves the rest
A recursive process.nextTick keeps the nextTick queue non-empty, so the loop never reaches poll; I/O callbacks, timers and setImmediate callbacks all wait. A recursive promise chain does the same through the microtask queue. A recursive setImmediate does not, because each callback schedules the next one for a later check phase and the loop gets to run its other phases in between.
const LIMIT = 1_000_000;
function run(kind, done) {
let n = 0, ioAt = null;
setImmediate(() => { ioAt = n; }); // stands in for any pending I/O or check-phase work
const next = kind === 'nextTick' ? process.nextTick : setImmediate;
(function step() {
if (++n < LIMIT) next(step); else setImmediate(() => done(ioAt));
})();
}
run('nextTick', (ioAt) => {
console.log('recursive nextTick: other work waited for all steps:', ioAt === 1_000_000);
run('setImmediate', (ioAt2) => {
console.log('recursive setImmediate: other work ran early:', ioAt2 < 1_000_000);
});
});
Run in the same container, it prints:
recursive nextTick: other work waited for all steps: true
recursive setImmediate: other work ran early: true
The first line shows a pending setImmediate callback only ran after all 1,000,000 recursive nextTick steps finished. In a real server, that waiting callback is any accepted socket or response, which is why throughput under load collapses to zero while the CPU sits at 100%.
What to change
- Replace recursive
process.nextTickand self-requeuing promise loops withsetImmediate(orsetTimeout) between slices of work. KeepnextTickfor the cases it exists for: running code after the current function but before any I/O, such as emitting an event after a constructor returns. - Put a bound on every self-scheduling loop (a batch size or a maximum number of steps per turn).
- If the slices are CPU-heavy, move the work to a
worker_threadsWorker (a separate thread with its own event loop, started from thenode:worker_threadsmodule) so the loop thread stays free for I/O. - Detect it in production with event loop delay metrics (
perf_hooks.monitorEventLoopDelayfrom thenode:perf_hooksmodule records how late the loop runs its scheduled work) and by taking a CPU profile (a sampled record of which functions were on the stack, for example fromnode --cpu-prof) when latency spikes: a starved loop shows one function re-entering itself with no I/O frames.
Pitfalls
- Using
setTimeout(fn, 0)andsetImmediateas if interchangeable; only inside an I/O callback is their order guaranteed. - Assuming the CommonJS ordering carries over to ES modules (shown above).
- Treating a promise chain as "safe" because it is async: it is a microtask and starves I/O the same way.
The same async code can order its callbacks differently in a browser and in Node.js. Explain how scheduling works in each environment, where the main scheduling primitives of each land relative to one another, and what you would do to write async code whose behaviour does not depend on the environment.
Sample Answer
Direct answer
Start here: a browser and Node both run one callback at a time, and both finish all pending promise callbacks before taking the next timer or I/O callback. Almost every ordering difference you will meet comes from what each adds around that shared rule.
Both environments run one callback at a time from queues, and both fully drain a queue of microtasks (promise reactions, queueMicrotask) before moving to the next macrotask (timer, message, I/O callback). That shared rule is why promise code orders the same way everywhere. They differ in everything around it. A browser has task queues plus a rendering step between tasks. Node has a fixed ring of phases (timers, poll, check and others) (the loop is implemented by libuv, the C library under Node that handles timers, file and network events), and two extra primitives that browsers lack: process.nextTick (a queue that Node drains before it returns to the loop) and setImmediate (runs in the loop's check phase). To write environment-independent async code, order work with promises and await, never with the relative order of setTimeout(0), setImmediate, MessageChannel or nextTick.
How scheduling works in a browser
- A task is one unit of work chosen from the task queues: running a script, dispatching an event, a timer callback, a
MessageChannelmessage (MessageChannelis a browser and Node API that creates two connected ports; a message posted on one port arrives on the other as a new task). The event loop (the loop that repeatedly picks the next task and runs it to completion) runs one at a time. - When the JavaScript stack empties after a task, the microtask queue is drained completely. Promise reactions,
queueMicrotaskcallbacks andMutationObservercallbacks (MutationObserveris a browser API that reports changes made to the DOM, the tree of page elements) all use it, and microtasks queued by microtasks also run before anything else (MDN, "Using microtasks in JavaScript with queueMicrotask"). - Then the browser may render (style, layout, paint;
requestAnimationFramecallbacks run in that step), and then the loop picks the next task. A long chain of microtasks therefore delays painting as well as other tasks. - Different task sources (timers, messages, user input) are separate queues, and the HTML Standard says the browser picks which queue to serve next "in an implementation-defined manner" (each browser vendor decides), so the relative order of a
setTimeout(0)and aMessageChannelmessage is not something to depend on.
How scheduling works in Node.js
Node's loop cycles through phases, documented at nodejs.org: timers (setTimeout, setInterval), pending callbacks (system-operation callbacks the loop deferred, for example some TCP errors such as a refused connection on certain systems), idle/prepare (used only internally), poll (new I/O events and their callbacks, and where Node blocks waiting when idle), check (setImmediate callbacks) and close callbacks. From libuv 1.45.0 (Node.js 20) timers run after the poll phase in each iteration; earlier versions ran them before.
process.nextTick is not part of the loop. Node's docs say its queue is processed after the current operation completes, regardless of phase, and before the loop continues; recursive nextTick calls can starve I/O. Promise microtasks also drain between callbacks. Between the two, in the usual CommonJS case the tick queue runs first and then the promise queue.
Where each primitive lands, measured
"Isomorphic" means the same code runs unchanged in both environments. The files below are named so they can be reproduced: the first listing is order_core.js, the one-run Node script is node_once.cjs, the 100-process driver is node_runs.cjs, and the browser driver is browser_runs.mjs; the commands are under Running the code. The same isomorphic script (shown first) records the order in which each primitive's callback runs. It exports collectOrder for Node and is evaluated as plain script in the pages.
// Isomorphic: runs unchanged in Node and in a browser page. Resolves with the order callbacks ran in.
function collectOrder() {
return new Promise(done => {
const log = [];
const L = s => log.push(s);
L('sync start');
setTimeout(() => L('setTimeout 0'), 0);
Promise.resolve().then(() => L('promise.then'));
queueMicrotask(() => L('queueMicrotask'));
if (typeof process !== 'undefined' && process.nextTick) process.nextTick(() => L('process.nextTick'));
if (typeof setImmediate === 'function') setImmediate(() => L('setImmediate'));
if (typeof MutationObserver === 'function') {
const el = document.createElement('div');
new MutationObserver(() => L('MutationObserver')).observe(el, { attributes: true });
el.setAttribute('x', '1');
}
if (typeof MessageChannel === 'function') {
const mc = new MessageChannel();
mc.port1.onmessage = () => { L('MessageChannel message'); mc.port1.close(); };
mc.port2.postMessage(0);
}
L('sync end');
setTimeout(() => done(log), 100);
});
}
if (typeof module !== 'undefined') module.exports = { collectOrder };
Node, one run from the top level of a CommonJS file, repeated in 100 separate processes:
// One run from the top level of a CommonJS file.
require('./order_core.js').collectOrder().then(log => console.log(log.join(' > ')));
const { execFileSync } = require('node:child_process');
const seen = new Set();
for (let i = 0; i < 100; i++) {
seen.add(execFileSync(process.execPath, ['node_once.cjs']).toString().trim());
}
console.log('Node ' + process.version + ', CommonJS top level, distinct orders over 100 separate processes:');
for (const k of [...seen].sort()) console.log(' ' + k);
Node v22.23.3, CommonJS top level, distinct orders over 100 separate processes:
sync start > sync end > process.nextTick > promise.then > queueMicrotask > MessageChannel message > setImmediate > setTimeout 0
sync start > sync end > process.nextTick > promise.then > queueMicrotask > setTimeout 0 > MessageChannel message > setImmediate
The first four steps are the same in every process. The tail varies: setTimeout 0 usually runs before MessageChannel message and setImmediate, but in a few processes (3 of 100 in one measured run on a Docker host; the count changes from run to run, and a given run of the driver may print only the second line) it runs after them.
Browsers (Playwright 1.48.2 driving Chromium 130, Firefox 131 and WebKit 18; WebKit here is the engine Safari uses on desktop, not Safari on iOS), 10 runs each:
import { chromium, firefox, webkit } from 'playwright';
import fs from 'node:fs';
const core = fs.readFileSync('./order_core.js', 'utf8');
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage();
await page.goto('about:blank');
await page.evaluate(core);
const seen = new Map();
for (let i = 0; i < 10; i++) {
const k = (await page.evaluate('collectOrder()')).join(' > ');
seen.set(k, (seen.get(k) || 0) + 1);
}
console.log(`${name} ${browser.version()}: distinct orders over 10 runs = ${seen.size}`);
for (const k of seen.keys()) console.log(' ' + k);
await browser.close();
}
chromium 130.0.6723.31: distinct orders over 10 runs = 1
sync start > sync end > promise.then > queueMicrotask > MutationObserver > setTimeout 0 > MessageChannel message
firefox 131.0: distinct orders over 10 runs = 1
sync start > sync end > promise.then > queueMicrotask > MutationObserver > setTimeout 0 > MessageChannel message
webkit 18.0: distinct orders over 10 runs = 1
sync start > sync end > promise.then > queueMicrotask > MutationObserver > setTimeout 0 > MessageChannel message
Side by side (the Node column is from the CommonJS run, the browser column from all three engines):
| Order | Node 22 | Chromium, Firefox, WebKit |
|---|---|---|
| 1 | sync start, sync end | sync start, sync end |
| 2 | process.nextTick | (no equivalent) |
| 3 | promise.then, queueMicrotask | promise.then, queueMicrotask |
| 4 | (no equivalent) | MutationObserver |
| 5 | setTimeout 0, MessageChannel message, setImmediate (usually in this order; setTimeout 0 occasionally comes last) | setTimeout 0, MessageChannel message (no setImmediate; WebKit occasionally swaps the two) |
Reading the two together:
- Synchronous code first, then the microtask queue in registration order (
promise.then,queueMicrotask, andMutationObserverin the browsers), then tasks. - Node adds
process.nextTickahead of the promise callbacks in this CommonJS run; browsers have no equivalent. MutationObserverexists only in the browsers,setImmediateonly in Node.- The relative order of the task-sources (
setTimeout 0,MessageChannel, andsetImmediatein Node) is not fixed. Over 100 Node processessetTimeout 0sometimes came aftersetImmediate, which matches Node's documentation that the order ofsetTimeout(0)andsetImmediatecalled from the main module is non-deterministic. Chromium and Firefox printed one order in every one of 12 executions of the browser driver; WebKit printed a second order (MessageChannel messagebeforesetTimeout 0) in 2 of those 12 executions. This fits the HTML Standard letting the browser choose among task queues, so the printed block above is one sample run, not a guarantee.
Details that change the order inside Node
Inside an I/O callback, setImmediate always runs before setTimeout(0), because the loop moves from the poll phase straight to the check phase (Node docs: "if you move the two calls within an I/O cycle, the immediate callback is always executed first"). A nextTick scheduled from inside a promise job waits for the promise queue to drain first:
const fs = require('node:fs');
// 1. Inside an I/O callback the order of setTimeout 0 and setImmediate is fixed.
fs.readFile(__filename, () => {
const log = [];
setTimeout(() => log.push('setTimeout 0'), 0);
setImmediate(() => log.push('setImmediate'));
process.nextTick(() => log.push('process.nextTick'));
Promise.resolve().then(() => log.push('promise.then'));
setTimeout(() => console.log('inside fs.readFile callback: ' + log.join(' > ')), 50);
});
// 2. process.nextTick scheduled from a promise job runs after the promise queue drains.
const log2 = [];
Promise.resolve().then(() => {
log2.push('p1');
process.nextTick(() => log2.push('tick scheduled in p1'));
Promise.resolve().then(() => log2.push('p2 scheduled in p1'));
});
setTimeout(() => console.log('nextTick scheduled inside a promise job: ' + log2.join(' > ')), 20);
nextTick scheduled inside a promise job: p1 > p2 scheduled in p1 > tick scheduled in p1
inside fs.readFile callback: process.nextTick > promise.then > setImmediate > setTimeout 0
The tick-versus-promise order also depends on whether the code is CommonJS or an ES module, because an ES module body itself runs inside a promise job:
const log = [];
process.nextTick(() => log.push('process.nextTick'));
Promise.resolve().then(() => log.push('promise.then'));
setTimeout(() => console.log('CommonJS top level: ' + log.join(' > ')), 20);
CommonJS top level: process.nextTick > promise.then
// An ES module body itself runs inside a promise job, so the promise queue is drained before the tick queue.
const log = [];
process.nextTick(() => log.push('process.nextTick'));
Promise.resolve().then(() => log.push('promise.then'));
setTimeout(() => console.log('ES module top level: ' + log.join(' > ')), 20);
ES module top level: promise.then > process.nextTick
Step by step in the ES module case: the module body runs as part of a promise job, so the Promise.resolve().then callback it queues joins the promise queue that is still draining and runs inside the same drain; Node processes the nextTick queue only after that drain ends. In the CommonJS case the file body runs outside any promise job, so Node empties the tick queue as soon as the body finishes and only then runs the promise queue. The same two lines of code print in opposite orders. This is a real way for Node code to reorder when a file is converted from CommonJS to ES modules.
Writing code that does not depend on the environment
The first rule matters most; the other four keep it from being undone.
- Order with promises and
await. Promise reactions behave identically in Node and every browser tested above. If B must run after A, make A return a promise and await it; do not rely on A's timer firing first. - Use
queueMicrotaskwhere you need "after the current code, before anything else". It exists in both runtimes. Avoidprocess.nextTickin shared code, since browsers have no such thing and it jumps ahead of promises in Node. - Treat
setTimeout(0),setImmediate,MessageChannelandrequestAnimationFrameas unordered with respect to one another. For "let the UI breathe" in the browser use a task boundary (a timer or a message) orrequestAnimationFrameif the work should line up with painting; do not write feature checks that infer order from the others. - Make an API always async or always sync. A function that calls back synchronously on a cache hit and asynchronously on a miss makes callers' orderings depend on state. Wrapping the fast path in
queueMicrotaskor returning a resolved promise fixes the order. - Test in both. The browser rendering step and Node phases are the parts that are exercised only in their own runtime, so run the ordering-sensitive suite in Node and in a real browser (Playwright makes this cheap).
Running the code
# The three Details listings, saved as fs_and_tick.js, tick_cjs.js and tick_esm.mjs (the last one MUST end in .mjs, otherwise Node runs it as CommonJS and prints the CommonJS order):
docker run --rm -v "$PWD":/w -w /w node:22 sh -c 'node fs_and_tick.js; node tick_cjs.js; node tick_esm.mjs'
# Node: save order_core.js, node_once.cjs, node_runs.cjs next to each other
docker run --rm -v "$PWD":/w -w /w node:22 node node_runs.cjs
# Browsers: save browser_runs.mjs and order_core.js in the same folder
docker run --rm -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy sh -c 'npm i playwright@1.48.2 && node browser_runs.mjs'
Pitfalls
- Believing
setTimeout(fn, 0)runs "immediately". It queues a task after at least the current task and every pending microtask. - Recursive microtasks or recursive
nextTick: the loop never gets to the next task, so timers, I/O and (in a browser) painting starve. - Porting a Node test that asserts "tick before promise" to ES modules or to a browser and being surprised.
Take one asynchronous operation that can fail and show it written three ways: as nested callbacks, as a promise chain, and with async/await. For each version, explain how an error travels and where it would be lost if you were careless, and which version you would want to maintain.
Sample Answer
Direct answer
I would maintain the async/await version. All three can carry an error to the caller, but they differ in what you must do by hand. With nested callbacks every level has to check and forward the error itself, and a thrown exception cannot be caught from outside. With a promise chain, a rejection skips forward to the nearest .catch, but a missing return silently detaches part of the chain. With async/await the same rejection becomes an ordinary exception caught by try/catch, and the control flow reads top to bottom.
One operation, three ways
The operation is "load a user, then load that user's orders"; either step can fail. The legacy functions use the error-first callback convention (cb(err, value): the callback's first argument is the error or null, the second is the result). util.promisify turns such callback functions into promise-returning ones, which is the usual migration path, and the program uses it for the promise and async/await versions. The program also uses top-level await (allowed in an ES module, so await can appear outside a function) and Node's two process-wide safety nets: the unhandledRejection event, which fires when a promise is rejected and nothing is attached to handle it, and the uncaughtException event, which fires when an exception travels all the way up the stack with no catch.
import { promisify } from 'node:util';
// The operation: asynchronous, can fail. Error-first callback style.
function loadUser(id, cb) {
setTimeout(() => (id === 0 ? cb(new Error('user ' + id + ' not found')) : cb(null, { id, name: 'user' + id })), 1);
}
function loadOrders(user, cb) {
setTimeout(() => (user.id === 2 ? cb(new Error('orders service down')) : cb(null, [user.name + '-order'])), 1);
}
const loadUserP = promisify(loadUser);
const loadOrdersP = promisify(loadOrders);
// 1. Nested callbacks: every level must forward err itself.
function viaCallbacks(id, done) {
loadUser(id, (err, user) => {
if (err) return done(err);
loadOrders(user, (err2, orders) => {
if (err2) return done(err2);
done(null, orders);
});
});
}
// 2. Promise chain: one catch at the end sees every earlier failure.
function viaPromises(id) {
return loadUserP(id).then((user) => loadOrdersP(user)); // returning the inner promise keeps the chain connected
}
// 3. async/await: ordinary try/catch.
async function viaAwait(id) {
const user = await loadUserP(id);
return await loadOrdersP(user);
}
const results = [];
const note = (m) => results.push(m);
const cbResult = (id) => new Promise((res) => viaCallbacks(id, (e, v) => res(e ? 'error: ' + e.message : 'ok: ' + v)));
for (const id of [1, 0, 2]) {
note(`id ${id} callbacks -> ` + await cbResult(id));
note(`id ${id} promises -> ` + await viaPromises(id).then((v) => 'ok: ' + v, (e) => 'error: ' + e.message));
try { note(`id ${id} await -> ok: ` + await viaAwait(id)); } catch (e) { note(`id ${id} await -> error: ` + e.message); }
}
console.log(results.join('\n'));
// Where careless code loses the error
const lost = [];
process.on('unhandledRejection', (r) => lost.push('unhandledRejection: ' + r.message));
process.on('uncaughtException', (e) => lost.push('uncaughtException: ' + e.message));
// callbacks: a throw inside an async callback skips the surrounding try/catch
try {
loadUser(1, () => { throw new Error('thrown in callback'); });
} catch (e) { lost.push('outer catch saw it (it should not)'); }
// promises: forgetting `return` detaches the inner promise from the chain
Promise.resolve().then(() => { loadUserP(0); }).then(() => lost.push('chain continued as if fine'));
// async: calling without await in the try block
async function forgot() { try { loadUserP(0); } catch (e) { lost.push('caught (it should not be)'); } }
forgot();
await new Promise((r) => setTimeout(r, 50));
console.log(lost.sort().join('\n'));
console.log('every careless case surfaced only as a global event:', lost.filter(s => s.startsWith('outer') || s.startsWith('caught')).length === 0);
Run in a Node 22 container, it prints:
id 1 callbacks -> ok: user1-order
id 1 promises -> ok: user1-order
id 1 await -> ok: user1-order
id 0 callbacks -> error: user 0 not found
id 0 promises -> error: user 0 not found
id 0 await -> error: user 0 not found
id 2 callbacks -> error: orders service down
id 2 promises -> error: orders service down
id 2 await -> error: orders service down
chain continued as if fine
uncaughtException: thrown in callback
unhandledRejection: user 0 not found
unhandledRejection: user 0 not found
every careless case surfaced only as a global event: true
The first nine lines show all three styles give the same results for a success, a failure at step one, and a failure at step two. The next four lines come from the careless block, which sorts them alphabetically, so they are not in the order they happened. Each maps to one mistake:
chain continued as if fine: the promise-chain mistake (.then(() => { loadUserP(0); })). The step returned nothing, so the next.thenran straight away as if the step had succeeded.uncaughtException: thrown in callback: the callback mistake. Thethrowhappened after the surroundingtry/catchhad already finished, so it reached the top of the stack and fired the process-wide event.- two
unhandledRejection: user 0 not foundlines: one from the dropped promise in the chain mistake and one from the missingawaitinforgot(). Both promises rejected with no handler attached.
How an error travels in each version
| Style | Path of the error | Who is responsible for forwarding it |
|---|---|---|
| Nested callbacks | Passed as the first argument of each callback | You, at every level: if (err) return done(err) |
| Promise chain | A rejection skips every .then until the next .catch (or the second argument of a .then) | The promise machinery, as long as each .then returns its inner promise |
async/await | await throws the rejection as an exception inside the async function | try/catch; if you do not catch, the returned promise rejects and the caller deals with it |
Where the error gets lost if you are careless
The last block of the program triggers one careless mistake per style. The four lines after the results show that none of the mistakes reached the local error handling. Each surfaced only as a process-wide event (one uncaughtException, two unhandledRejections) or not at all ("chain continued as if fine"), which in production is a crash or a log line far from the cause:
- Callbacks: a
throwinside an asynchronous callback is not caught by atry/catcharound the call that started the work, because thattryblock has already finished by the time the callback runs. The exception becomes anuncaughtExceptionfor the whole process. Also, forgettingreturnafterdone(err)makes the code continue into the success path; forgetting to checkerrat all swallows it. - Promise chain:
.then(() => { loadUserP(0); })starts a promise but does not return it (a "floating" promise: started, with nothing waiting on it), so the chain is detached from that step and continues as if the step succeeded, and the rejection has no handler (unhandledRejection). With the fix the same line reads.then(() => loadUserP(0)), and the chain waits for the step and its error flows to the next.catch. In Node's default--unhandled-rejections=throwmode (the command-line setting that decides what Node does with an unhandled rejection), an unhandled rejection is raised as an uncaught exception, which ends the process unless you handle it. Alwaysreturnthe inner promise. - async/await: calling an async function without
awaitinside atrymeans thecatchnever sees the failure; the rejection is again unhandled. The same happens withreturn somePromiseinsidetry(usereturn awaitwhen you need the localcatchto apply).
Which to maintain, and why
async/await wins on readability (flat code, one error-handling mechanism, normal loops and conditionals), on stack traces (the list of calls shown with an error; async stack traces through await are generally easier to follow than through callbacks), and on how little each step must remember. Keep callbacks only at the edge of a legacy API and wrap them once with new Promise or util.promisify. Choose a promise chain over await only for short, linear pipelines or when composing with combinators such as Promise.all (helpers that combine several promises into one). What would flip this: a hot path (code run extremely often, where small per-call costs add up) where creating a promise per event matters more than clarity, or a library whose API is callback-only and cannot be wrapped.
Complexity and edge cases
- Complexity: each version does two sequential awaits, so latency is the sum of the two operations; time is O(1) steps and no extra memory beyond the closures or promises. If the two calls were independent,
Promise.allwould make latency the maximum instead of the sum. - Edge cases: failure of the first step must not start the second; the callback must be called exactly once (a common bug is writing
if (err) done(err);withoutreturn:donereceives the error, execution falls through into the success path, anddonecan then be called a second time or run with a missing value); an error thrown synchronously before the first await in anasyncfunction still becomes a rejection, not a throw.
Running the code
# save the program as errors.mjs (.mjs enables import and top-level await)
docker run --rm --ulimit core=0 -v "$PWD":/w -w /w node:22 node errors.mjs
Write retryFetch(url, options, retries, backoffBaseMs) that retries only failures that are worth retrying, spaces attempts so many clients do not retry in lockstep, and stops a single hung attempt from blocking the rest. Explain which responses you would not retry and why.
Sample Answer
Direct answer
Retry only when repeating the identical request has a real chance of succeeding and cannot do harm: network failures, a timed-out attempt, and the transient statuses 408, 429, 500, 502, 503 and 504, and only for requests that are safe to repeat. Wait between attempts with exponential backoff (a delay ceiling that doubles each time) and full jitter (the actual delay is a random number between 0 and that ceiling), give every attempt its own deadline so one hung connection cannot eat the whole budget, and make every wait cancellable. Three decisions carry the design: which outcomes are worth retrying (the table below), how long to wait (backoff, jitter and the server's Retry-After header, which tells the client how many seconds to wait), and when to stop (the retry count, the per-attempt deadline and the caller's abort).
What to retry and what not to
| Outcome | Retry? | Why |
|---|---|---|
fetch rejects with a TypeError (DNS failure, connection reset, offline) | Yes | Nothing reached a handler, the next attempt may find a working path |
The attempt's own deadline fires (TimeoutError) | Yes | A hung connection says nothing about the next one |
| 408 Request Timeout | Yes | MDN (Mozilla's web documentation): the server closed the connection and the client may repeat the request on a new one |
| 429 Too Many Requests | Yes, after the wait the server asks for | Rate limiting is temporary by definition; Retry-After says how long |
| 500, 502, 503, 504 | Yes, with a small retry count | 502 and 504 come from a gateway that got a bad answer or none from the server behind it; 503 means overloaded or in maintenance; 500 may be a one-off fault or a deterministic bug, so keep the count low |
| 400, 401, 403, 404, 405, 409, 410, 422 | No | The server understood and refused: the same request gets the same answer. For 401, refresh the token and send a new request instead of replaying the old one |
| 501 Not Implemented | No | The server will never support it |
Any response when the call is a POST or PATCH without an idempotency key | No | Those methods are not guaranteed idempotent (repeating them may repeat the effect, such as a second charge), so a retry after an ambiguous failure can double-apply. With an Idempotency-Key header the server can de-duplicate, and the code below then allows retries |
| The caller aborted | No | The caller's decision outranks the policy |
Retry-After (seconds or an HTTP date, per MDN) is honoured as a minimum wait. A value larger than a sane limit is not obeyed: the 429 is returned to the caller instead of sleeping for an hour.
Why jitter, in numbers
Suppose 1000 clients all got a 503 at the same instant (a deploy restarted the backend). With plain exponential backoff, all 1000 retry together at the same moment, the backend gets the same spike again, fails again, and the pattern repeats: a thundering herd (many clients acting in lockstep). With full jitter each client picks its own random delay below the ceiling, so the retries spread out. The harness below replays that with a seeded generator, so the numbers are repeatable: for the third retry (ceiling 200 ms x 2^2 = 800 ms) it prints the size of the busiest 100 ms window.
Code and test harness
retryFetch takes the four requested parameters and a fifth options object that exists so tests can inject the random source and the sleep function. retries counts retries after the first attempt, so retries = 3 means up to 4 attempts. Each attempt gets AbortSignal.timeout(attemptTimeoutMs) merged with the caller's signal through AbortSignal.any (which combines several signals into one that aborts when any of them does), and the backoff wait is an abortable sleep that rejects the moment the caller's signal fires. In the options object, capMs is the highest value the exponential ceiling may reach, maxWaitMs is the longest Retry-After the function will obey, and random and sleep can be replaced in tests. An idempotency key is a unique token sent in the Idempotency-Key header so the server can recognise a repeat of the same operation and apply it once.
import http from 'node:http';
import assert from 'node:assert/strict';
const RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
function abortableSleep(ms, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) return reject(signal.reason);
const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms);
function onAbort() { clearTimeout(timer); reject(signal.reason); }
signal?.addEventListener('abort', onAbort, { once: true });
});
}
function retryAfterMs(res) {
const h = res.headers.get('retry-after');
if (!h) return 0;
if (/^\d+$/.test(h)) return Number(h) * 1000;
const t = Date.parse(h);
return Number.isNaN(t) ? 0 : Math.max(0, t - Date.now());
}
export async function retryFetch(
url, options = {}, retries = 3, backoffBaseMs = 200,
{ attemptTimeoutMs = 5000, capMs = 10000, maxWaitMs = 30000, random = Math.random, sleep = abortableSleep } = {},
) {
const method = (options.method ?? 'GET').toUpperCase();
const replayable = SAFE_METHODS.has(method) || new Headers(options.headers).has('Idempotency-Key');
const maxRetries = replayable ? retries : 0;
for (let attempt = 0; ; attempt++) {
// One signal per attempt: the caller's cancel OR this attempt's own deadline.
const signals = [AbortSignal.timeout(attemptTimeoutMs)];
if (options.signal) signals.push(options.signal);
let res;
try {
res = await fetch(url, { ...options, signal: AbortSignal.any(signals) });
} catch (err) {
if (options.signal?.aborted) throw err; // caller cancelled: stop
if (attempt >= maxRetries) throw err; // out of retries
// otherwise: network failure (TypeError) or this attempt's TimeoutError: retry
await sleep(Math.floor(random() * Math.min(capMs, backoffBaseMs * 2 ** attempt)), options.signal);
continue;
}
if (!RETRYABLE_STATUS.has(res.status) || attempt >= maxRetries) return res;
const ceiling = Math.min(capMs, backoffBaseMs * 2 ** attempt);
const serverWait = retryAfterMs(res);
if (serverWait > maxWaitMs) return res; // "come back in an hour": surface the 429 instead of hanging
const delay = Math.max(Math.floor(random() * ceiling), serverWait); // full jitter, but never earlier than Retry-After
await res.body?.cancel(); // release the connection of the discarded response
await sleep(delay, options.signal);
}
}
// ---------------- harness ----------------
const hits = {};
const plans = {
'/flaky': [503, 503, 200],
'/missing': [404, 200],
'/bad': [400, 200],
'/limited': [429, 200],
'/banned': [429, 200],
'/hang1': ['hang', 200],
'/always': [503, 503, 503, 503, 503],
'/post': [503, 200],
'/hangall': ['hang'],
'/hang2': ['hang', 200],
'/cap': [503],
'/dated': [429, 200],
};
const HERD_PLAN = [503, 503, 503, 200]; // every /herd?c=N client fails three times, then succeeds
const server = http.createServer((req, res) => {
const n = (hits[req.url] = (hits[req.url] ?? 0) + 1);
const plan = req.url.startsWith('/herd') ? HERD_PLAN : (plans[req.url] ?? [200]);
const step = plan[Math.min(n - 1, plan.length - 1)];
if (step === 'hang') return; // never answers
if (step === 429) res.setHeader('Retry-After', req.url === '/banned' ? '3600' : req.url === '/dated' ? new Date(Date.now() + 5000).toUTCString() : '2');
res.statusCode = step; res.end(String(step));
}).listen(0);
const base = `http://127.0.0.1:${server.address().port}`;
const reset = () => { for (const k of Object.keys(hits)) delete hits[k]; };
const delays = [];
const fakeSleep = async (ms) => { delays.push(ms); };
const almostMax = () => 0.999;
// 1. 503, 503, 200 => success on 3rd attempt, delays below the exponential ceilings 200 and 400
let res = await retryFetch(`${base}/flaky`, {}, 3, 200, { random: almostMax, sleep: fakeSleep });
const delaysSeen = delays.splice(0);
console.log('flaky:', res.status, 'attempts =', hits['/flaky'], 'delays =', delaysSeen);
assert.equal(res.status, 200); assert.equal(hits['/flaky'], 3);
// full jitter: delay = floor(random * ceiling), so 0.999 gives 199 then 399 (a version without jitter would give 200 and 400)
assert.deepEqual(delaysSeen, [199, 399]);
// 2. 404 and 400 are returned at once, never retried
for (const p of ['/missing', '/bad']) {
res = await retryFetch(base + p, {}, 3, 200, { sleep: fakeSleep });
console.log(p, '->', res.status, 'attempts =', hits[p]);
assert.equal(hits[p], 1);
}
// 3. 429 with Retry-After: 2 waits at least 2000 ms even when jitter picks 0
res = await retryFetch(`${base}/limited`, {}, 3, 200, { random: () => 0, sleep: fakeSleep });
const limitedDelays = delays.splice(0);
console.log('limited:', res.status, 'delays =', limitedDelays);
assert.equal(res.status, 200); assert.deepEqual(limitedDelays, [2000]);
// 3c. Retry-After as an HTTP date (about 5 s ahead, whole seconds) is honoured as well
res = await retryFetch(`${base}/dated`, {}, 3, 200, { random: () => 0, sleep: fakeSleep });
const datedDelays = delays.splice(0);
console.log('dated:', res.status, 'waited between 3500 and 5000 ms:', datedDelays[0] >= 3500 && datedDelays[0] <= 5000);
assert.equal(res.status, 200); assert.equal(datedDelays.length, 1);
assert.ok(datedDelays[0] >= 3500 && datedDelays[0] <= 5000);
// 3b. a Retry-After far beyond the wait limit is not obeyed: the caller gets the 429 at once
res = await retryFetch(`${base}/banned`, {}, 3, 200, { sleep: fakeSleep });
console.log('banned:', res.status, 'attempts =', hits['/banned'], 'delays =', delays.splice(0));
assert.equal(res.status, 429); assert.equal(hits['/banned'], 1);
// 4. a hung first attempt is cut off by the per-attempt deadline, then retried
const watchdog = new Promise((_, reject) => setTimeout(() => reject(new Error('hung attempt was never cut off')), 3000).unref());
res = await Promise.race([retryFetch(`${base}/hang1`, {}, 2, 10, { attemptTimeoutMs: 150 }), watchdog]);
console.log('hang1:', res.status, 'attempts =', hits['/hang1']);
assert.equal(res.status, 200); assert.equal(hits['/hang1'], 2);
// 4b. after a timed-out attempt the retry also waits a jittered backoff before the next attempt
res = await retryFetch(`${base}/hang2`, {}, 2, 10, { attemptTimeoutMs: 150, random: almostMax, sleep: fakeSleep });
const hangDelays = delays.splice(0);
console.log('hang2:', res.status, 'attempts =', hits['/hang2'], 'delays =', hangDelays);
assert.equal(res.status, 200); assert.equal(hits['/hang2'], 2); assert.deepEqual(hangDelays, [9]);
// 5. out of retries on 5xx: the last response is returned (caller sees the 503)
res = await retryFetch(`${base}/always`, {}, 2, 5, { sleep: fakeSleep });
console.log('always:', res.status, 'attempts =', hits['/always']); delays.length = 0;
assert.equal(res.status, 503); assert.equal(hits['/always'], 3);
// 5b. capMs stops the ceiling from growing: ceilings 200, 400, then 500 (not 800, 1600, 3200)
res = await retryFetch(`${base}/cap`, {}, 5, 200, { random: almostMax, capMs: 500, sleep: fakeSleep });
const capDelays = delays.splice(0);
console.log('capped:', res.status, 'attempts =', hits['/cap'], 'delays =', capDelays);
assert.equal(res.status, 503); assert.equal(hits['/cap'], 6); assert.deepEqual(capDelays, [199, 399, 499, 499, 499]);
// 6. POST is not replayed on 503 unless it carries an Idempotency-Key
res = await retryFetch(`${base}/post`, { method: 'POST' }, 3, 5, { sleep: fakeSleep });
console.log('POST no key:', res.status, 'attempts =', hits['/post']);
assert.equal(hits['/post'], 1);
reset();
res = await retryFetch(`${base}/post`, { method: 'POST', headers: { 'Idempotency-Key': 'k1' } }, 3, 5, { sleep: fakeSleep });
console.log('POST with key:', res.status, 'attempts =', hits['/post']);
assert.equal(hits['/post'], 2);
// 7. abort during a backoff wait ends the call promptly with no further attempt
reset();
const ctl = new AbortController();
setTimeout(() => ctl.abort(), 100);
const t0 = performance.now();
await assert.rejects(
retryFetch(`${base}/always`, { signal: ctl.signal }, 5, 60000, { random: almostMax }),
(e) => e.name === 'AbortError',
);
const elapsed = performance.now() - t0;
console.log('abort in backoff: rejected, attempts =', hits['/always'], ', returned within 1 s:', elapsed < 1000);
assert.equal(hits['/always'], 1); assert.ok(elapsed < 1000);
// 7b. abort while an attempt is in flight: the call ends and no backoff wait is scheduled
reset(); delays.length = 0;
const ctl2 = new AbortController();
setTimeout(() => ctl2.abort(), 100);
await assert.rejects(
retryFetch(`${base}/hangall`, { signal: ctl2.signal }, 3, 5, { sleep: fakeSleep }),
(e) => e.name === 'AbortError',
);
console.log('abort during an attempt: rejected, backoff waits scheduled =', delays.length);
assert.equal(delays.length, 0);
// 8. jitter, measured through retryFetch itself: 1000 clients fail together; when does each make its third retry?
function mulberry32(a) { return () => { a |= 0; a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const rnd = mulberry32(42);
const thirdRetry = [];
for (let c = 0; c < 1000; c++) {
const mine = [];
const r = await retryFetch(`${base}/herd?c=${c}`, {}, 3, 200, { random: rnd, sleep: async (ms) => { mine.push(ms); } });
assert.equal(r.status, 200);
thirdRetry.push(mine[2]); // ceiling for the third retry: 200 * 2^2 = 800 ms
}
const noJitter = thirdRetry.map(() => 800); // what plain exponential backoff would do
const busiest = (xs) => { const b = {}; for (const x of xs) b[Math.floor(x / 100)] = (b[Math.floor(x / 100)] ?? 0) + 1; return Math.max(...Object.values(b)); };
console.log('busiest 100 ms window, no jitter:', busiest(noJitter), '| full jitter:', busiest(thirdRetry));
assert.equal(busiest(noJitter), 1000); assert.ok(busiest(thirdRetry) < 200);
server.closeAllConnections(); server.close(); await new Promise((resolve) => process.stdout.write('', resolve)); // flush piped output before exiting
process.exit(0);
Run in a node:22 container (Node 22.23), it prints:
flaky: 200 attempts = 3 delays = [ 199, 399 ]
/missing -> 404 attempts = 1
/bad -> 400 attempts = 1
limited: 200 delays = [ 2000 ]
dated: 200 waited between 3500 and 5000 ms: true
banned: 429 attempts = 1 delays = []
hang1: 200 attempts = 2
hang2: 200 attempts = 2 delays = [ 9 ]
always: 503 attempts = 3
capped: 503 attempts = 6 delays = [ 199, 399, 499, 499, 499 ]
POST no key: 503 attempts = 1
POST with key: 200 attempts = 2
abort in backoff: rejected, attempts = 1 , returned within 1 s: true
abort during an attempt: rejected, backoff waits scheduled = 0
busiest 100 ms window, no jitter: 1000 | full jitter: 140
About mulberry32: it is a short seeded pseudo-random number generator, a function that returns the same "random" sequence every time it starts from the same seed (42 here). The odd constants are the algorithm's fixed bit-mixing steps and can be treated as a black box; it is used instead of Math.random only so the printed 140 is repeatable.
Reading it: the two delays 199 and 399 are the largest values the test's fixed random source allows under the ceilings 200 and 400; 404 and 400 are returned after one attempt; the 429 with Retry-After: 2 waits 2000 ms even though jitter picked 0; a Retry-After: 3600 is not obeyed; a Retry-After given as an HTTP date is honoured too; the hung first attempt is cut off by its own deadline and the second attempt succeeds, and a timed-out attempt is followed by a jittered wait (9 ms for a 10 ms ceiling) before the next one; retries = 2 against a permanently failing endpoint makes 3 attempts and then returns the last 503 response, so the caller can still read the status and body; the POST is replayed only with a key; aborting during the backoff wait ends the call within a second without a second attempt; aborting while an attempt is in flight ends the call with no backoff wait scheduled; and the herd drops from 1000 requests in the busiest window to 140. The ceiling is 800 ms, so the delays fall into 800 / 100 = 8 windows of 100 ms; 1000 clients spread evenly would put 1000 / 8 = 125 in each, and random spreading puts a little more than that in the busiest one (140 for this seed). Every line is guarded by an assert: the delays [199, 399] and [2000] are compared exactly, the abort test asserts the elapsed time, the hung-attempt test is raced against a 3 second watchdog so a missing deadline fails instead of hanging, and the herd figure is measured by calling retryFetch for 1000 simulated clients and collecting each one's third wait. Removing the jitter, the Retry-After floor, the per-attempt deadline, the abortable sleep, the caller-abort check, the backoff wait after a timed-out attempt, the capMs ceiling or the HTTP-date branch of the Retry-After parser from retryFetch makes the run exit with an assertion error.
Budget arithmetic
With the defaults (retries = 3, backoffBaseMs = 200, 5000 ms per attempt) the worst case is 4 attempts x 5000 ms plus the largest possible waits 200 + 400 + 800 ms:
4 x 5000 + (200 + 400 + 800) = 20000 + 1400 = 21400 ms
This figure holds for failures without a Retry-After header. A 429 or 503 that carries one can add up to maxWaitMs (30000 ms) to each wait, three times over with retries = 3, so a call that must stay inside a fixed budget needs the caller signal below rather than the arithmetic alone.
If the screen cannot wait that long, pass a caller signal such as AbortSignal.timeout(8000): it caps the whole call, because the per-attempt signal and the backoff sleep both listen to it.
Trade-offs and pitfalls
- Retries multiply load. One layer allowing 4 attempts can send 4 times the traffic to a struggling backend. If the browser, a gateway and a service each retry 4 times, one user action can become 4 x 4 x 4 = 64 requests at the bottom. Retry at one layer, and let the others fail fast.
- Cap the ceiling. Exponential growth without
capMsreaches minutes quickly. - Release discarded responses. A retried 503 still holds a connection until its body is read or cancelled, hence
res.body?.cancel(). - Do not retry what the user already abandoned. The
options.signalcheck inside thecatchis what stops a cancelled call from looking like a network failure and being retried. - Observe it. Log attempt number and reason; a rising retry rate is an early outage signal that a clean success rate hides.
Running the code
# save the listing as retry_fetch_test.mjs (Node 22 needs no install)
docker run --rm -v "$PWD":/w -w /w node:22 node retry_fetch_test.mjs
Unlock Full Question Bank
Get access to all 10 Asynchronous and Event-Driven Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.