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.
Users report intermittent out-of-order updates in a production app that you cannot reproduce locally. How do you find out whether async responses are being applied out of order, what would you instrument and how do you keep the data volume sane, and how would you turn the finding into a reliable test?
Sample Answer
Direct answer
Out-of-order updates happen when two requests are in flight, the older one is slower, and its response is applied last, so old data overwrites new data. You cannot see that from "the data was wrong" alone, so the first move is to record, for every response applied, which request it answered and whether a newer request already existed. Do that in production with a cheap sequence number, send only the anomalies plus a small sample of whole sessions, and read the result by endpoint, release and device. Then pin the bug in a test that decides the arrival order itself (a deferred promise per request, plus one browser test with delayed responses), watch it fail, apply the fix ("only the latest request may update the screen"), and watch it pass.
Step 1: confirm the precondition before adding code
Out-of-order application needs variable latency. Check what you already have, in this order:
- Symptom shape in the reports and in session replay (a recording of what the user saw). A search or filter box showing results for an earlier query, a list that flickers between two states, or a final screen that matches the second-to-last action are all the signature. A symptom that occurs on every attempt is a different bug.
- Latency spread of the endpoint. In your API logs, compare the median and the 99th percentile (the value 99% of requests are faster than) for the affected endpoint. If the slowest 1% takes ten times the median, a newer request can overtake an older one often enough to matter. If latency is uniform, suspect something else (a cache, a retry that re-sends an old request, two components writing the same state).
- Whether the server reorders anything. Compare request ids' arrival order with the order the client sent them (a request id header makes this a join in the logs). If the server processes them in order but responses overtake each other on the network or at a proxy, the fix is on the client; if the server itself reorders writes, the fix includes the server.
Step 2: instrument, with a data budget
The tracer below gives every request a sequence number when it starts (issue()), and when a response is about to update the screen it records two facts: outOfOrder (an older response landed after a newer one was already shown) and stale (a newer request was already in flight when this one was shown, even if it later resolves correctly). It sends an event for every anomaly and for all events of a sampled session, and nothing else.
What to attach to each event: the sequence number, the highest issued number, the endpoint name, a hash of the query (never the raw text, which may be personal), the response latency measured with performance.now(), the release version, and the route. Send events in groups with navigator.sendBeacon, which queues a small POST asynchronously and, per MDN (Mozilla's web documentation), does not delay the next navigation; the payload is limited to 64 KiB, so keep each group below that, and flush on visibilitychange (the event that fires when the tab becomes hidden, for example on a tab switch or when the page is closed) when the page becomes hidden, which MDN calls the most reliable moment, rather than on unload.
Keeping the volume sane. Sample whole sessions (for example the sessions whose id hashes into 1%), not individual events, so a sampled session is a complete timeline and anomalies in unsampled sessions still arrive in full. Illustrative arithmetic with assumed traffic of 100,000 sessions a day and 40 searches per session: logging everything is 100,000 x 40 = 4,000,000 events a day; at an assumed 200 bytes each that is 800,000,000 bytes (800 MB). Anomalies plus a 1% session sample, with an assumed anomaly rate of 0.2%, is 4,000,000 x 0.01 + 4,000,000 x 0.002 = 40,000 + 8,000 = 48,000 events, and 48,000 x 200 bytes = 9,600,000 bytes, about 9.6 MB (an upper bound, since anomalies inside sampled sessions are counted twice). The assumed rates are inputs to replace with your own; the method scales the same way.
Step 3: read the data
Group anomalies by endpoint, release, and device or network class. A cluster on one endpoint with high latency variance confirms the hypothesis; a jump at one release points at the change that removed a guard or added a second fetch. For the sampled sessions, plot issue time and apply time per sequence number: crossing lines are the overtaking. If anomalies are zero where users still report wrong data, the cause is not ordering (look at caches, retries replaying an old request, or optimistic updates not being reconciled).
Step 4: turn it into a reliable test
The test must control arrival order rather than hope the network produces it. A deferred promise is a promise whose resolve function is kept where the test can call it, so the test, not the network, decides when it settles: new Promise((resolve) => pending.push({ query, resolve })) in deferredFetch below stores each request's resolve, and answer(i) calls it. That lets the test resolve the responses in any order. The harness below replays all 3 x 2 x 1 = 6 arrival orders of three searches (a, ab, abc; the digits in each line are the zero-based indexes of the requests in the order their responses arrive), checks that the fixed code always ends on the last search, and checks that without the guard the screen is stale in exactly 4 of the 6 orders (the bug reproduces on demand, so the test cannot pass vacuously). In the order 102 the final screen is correct but the tracer still flags a flicker, which is why users report "intermittent" updates.
import assert from 'node:assert/strict';
// ---- instrumentation: always on; sends an event when something is wrong, and every event of sampled sessions ----
// sampledSession is decided once per session (for example 1% of session ids), so sampled sessions keep complete timelines.
function createTracer({ send, sampledSession = false }) {
let issued = 0;
let lastShown = 0;
return {
issue: () => ++issued,
isLatest: (seq) => seq === issued,
shown(seq, meta) {
const outOfOrder = seq < lastShown; // an older response landed after a newer one was already shown
const stale = seq < issued; // a newer request was already in flight when this was shown
lastShown = Math.max(lastShown, seq);
if (outOfOrder || stale || sampledSession) send({ seq, issued, outOfOrder, stale, ...meta });
},
};
}
// ---- the data path: guard=false is the bug as shipped, guard=true is the fix ----
function createSearch({ fetchResults, render, tracer, guard }) {
return async function search(query) {
const seq = tracer.issue();
const results = await fetchResults(query);
if (guard && !tracer.isLatest(seq)) return; // a newer search exists: drop this response
render({ query, results });
tracer.shown(seq, { query });
};
}
// ---- deterministic test: the test, not the network, decides when each response arrives ----
function deferredFetch() {
const pending = [];
const fetchResults = (query) => new Promise((resolve) => pending.push({ query, resolve }));
return { fetchResults, answer: (i) => pending[i].resolve(`results for "${pending[i].query}"`) };
}
async function scenario(order, guard) {
const events = [];
let screen = null;
const { fetchResults, answer } = deferredFetch();
const search = createSearch({
fetchResults, guard,
render: ({ results }) => { screen = results; },
tracer: createTracer({ send: (e) => events.push(e), sampledSession: false }),
});
const calls = ['a', 'ab', 'abc'].map((q) => search(q));
for (const i of order) { answer(i); await Promise.resolve(); } // answer in the order under test
await Promise.all(calls);
return { screen, events };
}
const orders = [[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]];
let staleWithoutGuard = 0;
for (const order of orders) {
const bad = await scenario(order, false);
const good = await scenario(order, true);
if (bad.screen !== 'results for "abc"') staleWithoutGuard++;
assert.equal(good.screen, 'results for "abc"'); // the fix survives every arrival order
console.log(`arrival ${order.join('')}: without guard shows ${bad.screen.replace('results for ', '')}, flagged events: ${bad.events.filter((e) => e.outOfOrder).length} out-of-order`);
}
console.log(`without guard: stale screen in ${staleWithoutGuard} of ${orders.length} arrival orders`);
assert.equal(staleWithoutGuard, 4); // fails loudly if the bug stops reproducing
// ---- the tracer's own contract: anomalies always, other events only for sampled sessions, and nothing else ----
function traceInOrder(sampledSession) {
const sent = [];
const t = createTracer({ send: (e) => sent.push(e), sampledSession });
for (let n = 0; n < 3; n++) { const seq = t.issue(); t.shown(seq, {}); } // each response is shown before the next request starts
return sent.length;
}
assert.equal(traceInOrder(false), 0); // no anomaly, unsampled session: nothing is sent
assert.equal(traceInOrder(true), 3); // sampled session: every event is sent
// anomalies are sent even when the session is not sampled
const sent = [];
const t = createTracer({ send: (e) => sent.push(e), sampledSession: false });
const first = t.issue(); const second = t.issue();
t.shown(second, {}); // newest response first: not an anomaly, nothing sent
t.shown(first, {}); // older response lands last: out of order, and stale
assert.equal(sent.length, 1);
assert.equal(sent[0].outOfOrder, true);
const t2sent = [];
const t2 = createTracer({ send: (e) => t2sent.push(e), sampledSession: false });
const early = t2.issue(); t2.issue();
t2.shown(early, {}); // shown while a newer request is in flight: stale only
assert.equal(t2sent.length, 1);
assert.equal(t2sent[0].outOfOrder, false);
assert.equal(t2sent[0].stale, true);
console.log('tracer sends 0 events for a clean unsampled session, 3 for a clean sampled one, and 1 for each kind of anomaly in an unsampled one');
Reading scenario: it starts all three searches (each one waits on its own deferred promise), then answers them in the order under test. The await Promise.resolve() after each answer(i) pauses the loop for one microtask turn, so the search whose promise was just resolved runs its continuation and renders before the next response is delivered, and the output reads as one response at a time. Removing it does not change the printed result of this particular harness, because continuations of promises resolved in sequence run in that same sequence; the order is controlled by when the test calls answer(i). calls is awaited at the end so every search has finished before the screen is read.
Run in a node:22 container (Node 22.23), it prints:
arrival 012: without guard shows "abc", flagged events: 0 out-of-order
arrival 021: without guard shows "ab", flagged events: 1 out-of-order
arrival 102: without guard shows "abc", flagged events: 1 out-of-order
arrival 120: without guard shows "a", flagged events: 1 out-of-order
arrival 201: without guard shows "ab", flagged events: 2 out-of-order
arrival 210: without guard shows "a", flagged events: 2 out-of-order
without guard: stale screen in 4 of 6 arrival orders
tracer sends 0 events for a clean unsampled session, 3 for a clean sampled one, and 1 for each kind of anomaly in an unsampled one
The last line comes from the tracer's own checks, all asserted: with every response shown before the next request starts, an unsampled session sends nothing and a sampled session sends all three events; in an unsampled session an out-of-order response is sent (it is also stale), and a response shown while a newer request is in flight is sent as stale only. Together these assert "every anomaly and all events of a sampled session, and nothing else", so deleting the anomaly condition from the tracer fails the script. The count 4 is 6 - 2 = 4: the screen is correct only when the last response to arrive is the answer to the last request, which is 2 of the 6 orders (012 and 102).
A unit test shows the logic; one browser test shows the real fetch path. This Playwright test serves a tiny page, delays the response to the first request by 500 ms with page.route, fires two searches, waits for both responses, and reads the screen with and without the guard:
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
const html = `<body><div id="out"></div><script>
const out = document.getElementById('out');
let latest = 0;
async function search(q, guard) {
const seq = ++latest;
const res = await fetch('/api/search?q=' + q);
const text = await res.text();
if (guard && seq !== latest) return; // drop answers to older searches
out.textContent = text;
}
</script></body>`;
async function run(guard) {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.route('http://app.test/**', async (route) => {
const url = new URL(route.request().url());
if (url.pathname === '/') return route.fulfill({ contentType: 'text/html', body: html });
const q = url.searchParams.get('q');
if (q === 'a') await new Promise((r) => setTimeout(r, 500)); // the first request is the slow one
return route.fulfill({ body: `results for ${q}` });
});
await page.goto('http://app.test/');
await page.evaluate((g) => { search('a', g); search('ab', g); }, guard);
await page.waitForTimeout(900); // both responses have arrived by now
const shown = await page.textContent('#out');
await browser.close();
return shown;
}
const without = await run(false);
const withGuard = await run(true);
console.log('without guard, screen shows:', without);
console.log('with guard, screen shows: ', withGuard);
assert.equal(without, 'results for a'); // the bug reproduces on demand
assert.equal(withGuard, 'results for ab'); // and the fix holds
With playwright@1.48.2 in the Playwright v1.48.2 container (Chromium), it prints:
without guard, screen shows: results for a
with guard, screen shows: results for ab
Both assert.equal lines make the script fail if the bug stops reproducing or the guard stops working. Delays set inside the test are deterministic by construction (the 500 ms request is slower than a request that answers at once), so the test does not depend on real network timing.
The fix and how to verify it
Apply a response only if it answers the newest request (the seq !== latest check above), or cancel older requests with an AbortController so their responses never arrive; keeping the check as well covers calls that ignore cancellation. In libraries, the equivalent is a query-key-based cache or switchMap/mapLatest style operators. Verify in three places: the new test goes green, the production anomaly rate for the endpoint drops to zero after release (the tracer stays on), and user reports for the symptom stop.
Pitfalls
- Logging the raw query leaks personal data; hash it.
- Sampling events instead of sessions destroys the timelines you need.
- A fix that only handles the last response misses flicker (order
102above): intermediate states can still appear; cancelling old requests removes them. - Do not trust a local repro that "works". Fast local latency hides this class of bug; the test must set the order itself.
Running the code
Save the two programs as harness.mjs and browser.mjs (both use import and top-level await, so they need the .mjs extension). node harness.mjs needs only Node 22. For the browser test run npm i playwright@1.48.2 and then node browser.mjs in the Playwright v1.48.2 container, which provides Chromium.
A profile screen needs the user's data and their avatar. The avatar request can fail without breaking the screen: show a placeholder and still render the user data. Write the fetching code so both requests run at the same time and the failure of one does not discard the other.
Sample Answer
Direct answer
Create both promises first, before awaiting either, so both requests are on the wire together. Then await them with Promise.allSettled, which waits for both and reports each outcome instead of rejecting on the first failure. The user outcome is required (if it failed, rethrow so the screen shows an error); the avatar outcome is optional (if it failed, use null and render the placeholder). Two details decide whether this is correct in practice (the "wire" below means the network connection: a request is on the wire once it has been sent): fetch does not reject on an HTTP 404 or 500, so check res.ok, and allSettled waits for the slower call, so each request needs its own timeout.
The fetching code in short
The whole idea is the short loadProfile function (five statements): start both requests, then wait for both outcomes. The rest of the listing below is a small local server so the program can run by itself. Here getJson and getBlob fetch a URL and return JSON or a Blob (a chunk of binary data such as an image file), and AbortSignal.timeout(ms) is a signal that aborts the request after that many milliseconds. Run in a node:22 container (Node 22), the program prints the line shown after it, with the avatar endpoint failing:
import http from 'node:http';
async function getJson(url, signal) {
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
async function getBlob(url, signal) {
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.blob();
}
async function loadProfile(base, id) {
const userP = getJson(`${base}/api/users/${id}`, AbortSignal.timeout(5000));
const avatarP = getBlob(`${base}/api/users/${id}/avatar`, AbortSignal.timeout(2000));
const [user, avatar] = await Promise.allSettled([userP, avatarP]);
if (user.status === 'rejected') throw user.reason;
return { user: user.value, avatar: avatar.status === 'fulfilled' ? avatar.value : null };
}
// A local server whose avatar endpoint always fails with HTTP 500.
const server = http.createServer((req, res) => {
if (req.url.includes('avatar')) { res.statusCode = 500; return res.end('boom'); }
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ id: 1, name: 'Ada' }));
});
await new Promise(r => server.listen(0, r));
const profile = await loadProfile(`http://localhost:${server.address().port}`, 1);
console.log('user:', profile.user.name, '| avatar:', profile.avatar ?? 'placeholder');
server.close();
user: Ada | avatar: placeholder
The code with failure, timeout and concurrency checks
The listing below wraps the same function in checks. Its server picks a behaviour per path (ok, fail for HTTP 500, notfound for HTTP 404, hang for never answering), the hits array records the order in which requests reach the server (so the "both in flight" claim can be asserted), assert.rejects passes only if the call rejects with a matching error, within fails a call that never settles, and closeAllConnections at the end drops any connection left open by the hung requests so the process can exit.
import http from 'node:http';
import assert from 'node:assert/strict';
// ---- a tiny server whose behaviour per path the tests choose ----
const behaviour = { user: 'ok', avatar: 'ok' }; // ok | fail | notfound | hang
const hits = []; // order in which requests ARRIVE at the server
const server = http.createServer((req, res) => {
const which = req.url.includes('avatar') ? 'avatar' : 'user';
hits.push(which);
const mode = behaviour[which];
if (mode === 'hang') return; // never answers
if (mode === 'fail') { res.statusCode = 500; return res.end('boom'); }
if (mode === 'notfound') { res.statusCode = 404; return res.end('none'); }
setTimeout(() => {
res.setHeader('content-type', which === 'user' ? 'application/json' : 'image/png');
res.end(which === 'user' ? JSON.stringify({ id: 1, name: 'Ada' }) : Buffer.from([1, 2, 3, 4]));
}, 30);
});
await new Promise(r => server.listen(0, r));
const base = `http://localhost:${server.address().port}`;
// ---- the code under discussion ----
// fetch() only rejects on network failure or abort. A 404 or 500 still RESOLVES, so check res.ok.
async function getJson(url, signal) {
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
async function getBlob(url, signal) {
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.blob();
}
export async function loadProfile(id, { userTimeoutMs = 5000, avatarTimeoutMs = 2000 } = {}) {
// Both requests start here, before either is awaited.
const userP = getJson(`${base}/api/users/${id}`, AbortSignal.timeout(userTimeoutMs));
const avatarP = getBlob(`${base}/api/users/${id}/avatar`, AbortSignal.timeout(avatarTimeoutMs));
const [user, avatar] = await Promise.allSettled([userP, avatarP]);
if (user.status === 'rejected') throw user.reason; // the screen cannot render without the user
return {
user: user.value,
avatar: avatar.status === 'fulfilled' ? avatar.value : null, // null => show the placeholder
avatarError: avatar.status === 'rejected' ? avatar.reason.name + ': ' + avatar.reason.message : null,
};
}
// ---- checks ----
// A check that would hang (for example a request with no timeout) must fail loudly instead.
const within = (ms, p, label) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error('hung: ' + label)), ms).unref())]);
const show = p => ({ user: p.user.name, avatar: p.avatar ? `blob(${p.avatar.size} bytes, ${p.avatar.type})` : 'placeholder', avatarError: p.avatarError });
behaviour.user = 'ok'; behaviour.avatar = 'ok'; hits.length = 0;
let p = await loadProfile(1);
assert.equal(p.avatar.size, 4); assert.equal(p.avatarError, null);
console.log('both ok ', JSON.stringify(show(p)));
for (const mode of ['fail', 'notfound']) {
behaviour.avatar = mode;
p = await loadProfile(1);
assert.equal(p.user.name, 'Ada'); assert.equal(p.avatar, null);
console.log(`avatar ${mode.padEnd(8)}`, JSON.stringify(show(p)));
}
behaviour.avatar = 'hang';
p = await within(1500, loadProfile(1, { avatarTimeoutMs: 150 }), 'avatar hang');
assert.equal(p.user.name, 'Ada'); assert.equal(p.avatar, null); assert.match(p.avatarError, /^TimeoutError/);
console.log('avatar hangs ', JSON.stringify(show(p)));
behaviour.user = 'fail'; behaviour.avatar = 'ok';
await assert.rejects(loadProfile(1), /HTTP 500/);
console.log('user fails loadProfile rejects with HTTP 500 (the caller shows the error screen)');
// Both requests really are in flight together: with the user call held open, the avatar call still reaches the server.
behaviour.user = 'hang'; behaviour.avatar = 'ok'; hits.length = 0;
const pending = loadProfile(1, { userTimeoutMs: 200, avatarTimeoutMs: 100 }).catch(() => {});
await new Promise(r => setTimeout(r, 60));
assert.deepEqual([...hits].sort(), ['avatar', 'user']);
console.log('concurrent server saw both requests while the user call was still unanswered');
await within(1500, pending, 'user hang'); // allSettled waits for BOTH calls, so the hung user call is cut off by its own timeout
// The hazard that Promise.allSettled avoids: awaiting two promises one after the other.
let unhandled = 0;
process.on('unhandledRejection', () => { unhandled++; });
behaviour.user = 'ok'; behaviour.avatar = 'fail';
{
const u = getJson(`${base}/api/users/1`);
const a = getBlob(`${base}/api/users/1/avatar`); // rejects while we are still awaiting u
await u;
await new Promise(r => setTimeout(r, 20)); // the avatar rejection lands with no handler attached
assert.equal(unhandled, 1);
await a.catch(() => {});
}
console.log('sequential await of two started promises: unhandledRejection events =', unhandled);
server.close(); server.closeAllConnections();
Run in a node:22 container (Node 22.23) against the local server in the file, it prints:
both ok {"user":"Ada","avatar":"blob(4 bytes, image/png)","avatarError":null}
avatar fail {"user":"Ada","avatar":"placeholder","avatarError":"Error: HTTP 500"}
avatar notfound {"user":"Ada","avatar":"placeholder","avatarError":"Error: HTTP 404"}
avatar hangs {"user":"Ada","avatar":"placeholder","avatarError":"TimeoutError: The operation was aborted due to timeout"}
user fails loadProfile rejects with HTTP 500 (the caller shows the error screen)
concurrent server saw both requests while the user call was still unanswered
sequential await of two started promises: unhandledRejection events = 1
The file ends with assert calls, so a version that discards the user on an avatar failure, or that serialises the two requests, exits with an error instead of printing these lines. The within helper turns a call that never settles (for example a request whose timeout was removed) into an error after 1.5 s, so that mistake also exits with a non-zero status instead of hanging. The last check deliberately leaves a rejection unhandled for a moment, so Node also writes a PromiseRejectionHandledWarning to stderr when the handler is attached afterwards; that warning is expected and stdout is exactly the lines above.
Why it is written this way
- Start both, then await.
const userP = getJson(...)andconst avatarP = getBlob(...)each callfetchimmediately and return a pending promise. The requests are in flight together because neither line awaits. Writingconst user = await getJson(...)followed byconst avatar = await getBlob(...)would send the avatar request only after the user reply, so the screen would take the sum of the two durations instead of the longer one. The "concurrent" line shows the avatar request reaching the server while the user call is still unanswered. Promise.allSettled, notPromise.all.Promise.allrejects as soon as any input rejects, which would send the screen to its error state because of an avatar.allSettledalways fulfils with an array of{ status: 'fulfilled', value }or{ status: 'rejected', reason }entries, in input order.- The required call rethrows. Partial failure is a policy decision per request, not a blanket rule. Here the user data is mandatory, so its rejection is rethrown and the caller shows the error screen; the avatar is optional, so its rejection becomes
null. - Check
res.ok. The promise returned byfetchrejects only for network failures and aborts. A server reply of 404 or 500 resolves normally, so withoutif (!res.ok) throw ...the avatar's error page body would be treated as a successful image. The 500 and 404 lines show both are turned into the placeholder. - Timeouts on both calls.
allSettleddoes not settle until every input has. A request that never answers would hold the whole screen at the loading state.AbortSignal.timeout(ms)aborts the request after the delay and the promise rejects with aTimeoutError(aDOMException, the standard error object that browsers and Node use for aborts and timeouts, whosenameisTimeoutError, notAbortError), which the avatar branch converts to the placeholder. An unanswered user call is bounded the same way byuserTimeoutMs.
The mistake the pattern avoids
Starting two promises and then awaiting them one after the other looks harmless:
const u = getJson(userUrl);
const a = getBlob(avatarUrl); // may reject while we are still waiting for u
await u;
await a;
If a rejects while await u is still pending, nobody has attached a rejection handler to a yet. The runtime reports an unhandled rejection (a rejected promise with no handler attached by the end of the current turn of the event loop; the last line of the output shows exactly one unhandledRejection event), and in current Node the default behaviour for that is to raise an uncaught exception that terminates the process unless a handler is registered. allSettled attaches handlers to both at once, so this window never opens.
Related patterns worth knowing
- Paint the user as soon as it arrives. With
allSettled, the screen waits for the slower call. If the avatar is usually slower, give each request its own state (user: loading | ready | error,avatar: loading | ready | placeholder) and update each when its own promise settles, so the name appears first and the avatar swaps in later. The two requests are still started together. - Rendering a Blob. In the browser, turn the avatar
Blobinto an<img>source withURL.createObjectURL(blob)and callURL.revokeObjectURLwhen the component goes away, or simply use the avatar URL as thesrcof the image and let the<img>handle failure with itsonerrorevent. The second form needs no fetch at all.
Pitfalls
- Using
Promise.alland an.catchon the whole thing: you cannot tell which request failed and the user data is lost. - Swallowing the avatar error silently: log it or send it to your error monitor, because a broken avatar service looks identical to "no avatar".
- Treating all failures as optional: the user failure must still surface.
Complexity: both requests run concurrently, so elapsed time is about the longer of the two (or the timeout, if lower), not their sum.
Running the code
# save the short program as profile_short.mjs and the checks as profile_checks.mjs, then:
docker run --rm -v "$PWD":/w -w /w node:22 node profile_short.mjs
docker run --rm -v "$PWD":/w -w /w node:22 node profile_checks.mjs
A gallery page loads many images and thumbnails. When does it make sense to wait for every request, and when for only the first to answer? Give a concrete frontend case for each, and say what each approach does when one of the requests fails and what the user ends up seeing.
Sample Answer
Direct answer
Start here: ask what the screen needs. If it needs every result, wait for all of them; if one good answer is enough, take the first; if one failure must not spoil the rest, collect each outcome separately.
Wait for every request when the screen is only correct with all the results, and wait for the first when any one answer is enough. Concretely, a gallery's thumbnail grid needs every thumbnail, but a failure of one should not blank the rest, so use Promise.allSettled (wait for all, never short-circuit). A hero image that exists on three CDN mirrors (identical copies of the file on different content-delivery-network servers, so any one of them will do) needs only the first mirror that works, so use Promise.any (first success). The plain versions, Promise.all and Promise.race, both short-circuit on the first rejection (they settle immediately with that failure instead of waiting for the remaining inputs), so on a failing request they hand the user an error instead of a partial page. Use them only when that is the behaviour you want.
The four combinators
A promise combinator is a function that takes several promises and returns one promise built from their outcomes.
| Combinator | Resolves with | Rejects when | Failure leaves the other requests |
|---|---|---|---|
Promise.all | Array of all values, in input order | The first input rejects | Still running (nothing cancels them) |
Promise.allSettled | Array of {status, value} or {status, reason}, one per input | Never; it always waits for every input | Waited for |
Promise.race | The first input to settle, success or failure | The first settled input is a rejection | Still running |
Promise.any | The first input to fulfill | Every input rejected: an AggregateError whose errors array holds the reasons in input order | Still running after the first success |
(MDN documents the any semantics, the AggregateError, and that a result does not cancel the other operations.)
Each one on a gallery, with what the user sees
AggregateError is a built-in error type that bundles several errors into one: its errors array holds each underlying failure. The script uses fake loaders with fixed delays (20, 40, 60 ms etc.) so the outcomes are reproducible, and it prints each result. Reading the helpers: load(url, ms, fail, signal) returns a promise that settles after ms milliseconds, resolving with the url or rejecting, and it also rejects early if the optional signal (an AbortSignal, the cancellation token an AbortController hands out) fires. show(label, p) waits for p, then prints the label padded to 22 characters followed by either the JSON of the result or the error's name and message; for an AggregateError it joins the messages from e.errors. Each await show(...) line below therefore matches one line of the output.
// Fake image loader: resolves with the url after `ms`, or rejects if `fail` is true.
const load = (url, ms, fail = false, signal) => new Promise((resolve, reject) => {
const t = setTimeout(() => (fail ? reject(new Error(url + ' failed')) : resolve(url)), ms);
signal?.addEventListener('abort', () => { clearTimeout(t); reject(signal.reason); });
});
const show = async (label, p) => console.log(label.padEnd(22), await p.then((v) => JSON.stringify(v), (e) => e.name + ': ' + (e.errors ? e.errors.map((x) => x.message).join(', ') : e.message)));
const thumbs = () => [load('t1.jpg', 60), load('t2.jpg', 20, true), load('t3.jpg', 40)];
await show('all (one fails)', Promise.all(thumbs()));
await show('allSettled', Promise.allSettled(thumbs()).then((rs) => rs.map((r) => r.status === 'fulfilled' ? r.value : 'rejected: ' + r.reason.message)));
await show('any (mirrors)', Promise.any([load('cdn-a/hero.jpg', 50, true), load('cdn-b/hero.jpg', 80), load('cdn-c/hero.jpg', 30, true)]));
await show('any (all fail)', Promise.any([load('a', 10, true), load('b', 20, true)]));
await show('race (fast failure)', Promise.race([load('slow-ok', 60), load('fast-fail', 10, true)]));
// race as a timeout: the losing request keeps running unless it is aborted
let finished = false;
const slow = new Promise((r) => setTimeout(() => { finished = true; r('slow body'); }, 80));
const timeout = (ms) => new Promise((_, rej) => setTimeout(() => rej(new Error('timed out')), ms));
await show('race timeout', Promise.race([slow, timeout(20)]));
console.log('slow request still ran to completion:', await new Promise((r) => setTimeout(() => r(finished), 120)));
let abortedRan = false;
const ac = new AbortController();
const abortable = new Promise((resolve, reject) => {
const t = setTimeout(() => { abortedRan = true; resolve('slow body'); }, 80);
ac.signal.addEventListener('abort', () => { clearTimeout(t); reject(ac.signal.reason); });
});
const timer = setTimeout(() => ac.abort(new Error('aborted by caller')), 20);
await show('race with abort', abortable.finally(() => clearTimeout(timer)));
console.log('aborted request ran to completion:', await new Promise((r) => setTimeout(() => r(abortedRan), 120)));
console.log('empty input: all ->', JSON.stringify(await Promise.all([])), '| any ->', await Promise.any([]).catch((e) => e.name));
Run in a Node 22 container, it prints:
all (one fails) Error: t2.jpg failed
allSettled ["t1.jpg","rejected: t2.jpg failed","t3.jpg"]
any (mirrors) "cdn-b/hero.jpg"
any (all fail) AggregateError: a failed, b failed
race (fast failure) Error: fast-fail failed
race timeout Error: timed out
slow request still ran to completion: true
race with abort Error: aborted by caller
aborted request ran to completion: false
empty input: all -> [] | any -> AggregateError
allwith one failing thumbnail rejects witht2.jpg failedand the other two successful results are thrown away. The user sees an error state for the whole gallery. Right when the page cannot render without every piece (for example a checkout page needing both cart and prices).allSettledreturns all three outcomes. The gallery renders two thumbnails and one placeholder with a retry button. This is the right default for independent tiles.anyover mirrors resolved withcdn-b/hero.jpg, the first to succeed, ignoring the two failures. If every mirror fails you get anAggregateError(shown on theany (all fail)line) and should render the fallback image. Right for redundant sources of the same thing.racewith a fast failure rejects with the failure even though a slower request would have succeeded. Right for "first answer of any kind", rarely for images.raceas a timeout is the common use: race the request against a timer that rejects. The output shows the pitfall:slow request still ran to completion: true. The loser keeps running, using bandwidth and possibly updating state later.- Fix: give the request an
AbortController(a browser and Node API for cancelling work); on timeout callabort()and the request is torn down. Therace with abortlines show the aborted request never completed (false). Withfetchyou pass{ signal }in the options; the request then rejects once aborted. - Empty input behaves differently:
Promise.all([])resolves with[], whilePromise.any([])rejects with anAggregateError. A gallery with zero images must not be treated as a failure.
Recommendation
Thumbnails: allSettled, render fulfilled ones, placeholders for rejected ones, one retry per tile. Hero image: any over the mirrors with an AbortController per request so the losers are cancelled once one wins. Page data that the screen needs in full: all, with a single error state. Timeouts: race against a timer, but always with abort() on the loser.
Pitfalls
- Using
allfor independent tiles and then wondering why one 404 blanks the page. - Reading the
allSettledarray as values: each entry is an object; checkstatusfirst. - Assuming
raceoranycancel the losers. They do not. - Unbounded fan-out (starting many requests at the same moment): firing hundreds of requests at once wastes bandwidth and competes with more important requests; cap concurrency when the count is large.
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
A large frontend codebase keeps producing intermittent unhandled promise rejection warnings and nobody can tell where they come from. What would you change in the code, the tooling and the review process so they stop appearing and any that remain are visible?
Sample Answer
Direct answer
An unhandled rejection means a promise rejected and no code ever attached a handler to it. A promise that is created and then ignored (not awaited, not returned, no handler) is called a floating promise. In a large codebase they stay mysterious for one reason: the rejection happens far from the line that started the work, and the warning carries no context. So fix the problem in four layers, in this order: (1) make the leftovers visible first with a global handler that reports the reason, its stack and where the user was, so the next week of data tells you where they come from; (2) change the code so that requests go through one wrapper that rejects with a rich error and unawaited work goes through one helper that owns its failure; (3) change the tooling so that a floating promise cannot be merged (lint) and cannot pass a test run (an end-to-end test fails on any unhandled rejection); (4) change the review process with a short checklist and a ratchet (a limit that can only tighten: today's violation count becomes the ceiling, and it may go down but never up). Anything that still escapes lands in the global handler with enough context to fix.
What the runtime does with an unhandled rejection
- Browser. The runtime fires an
unhandledrejectionevent on the global scope; if the event is not cancelled, the runtime eventually writes an error to the console (MDN, Mozilla's web documentation). Callingevent.preventDefault()suppresses that console message, which is why the reporter below does not call it: you want the console error in development. - Node. Since Node 15 the default mode is
throw: if nounhandledRejectionhook is set, the rejection is raised as an uncaught exception and the process exits (Node CLI documentation). With a hook, the process continues. A server that crashes on one forgotten.catchis a different severity from a browser tab that logs it, so the review rules differ slightly.
The program below runs each Node case in a child process and prints the exit code. node-demo.mjs:
import { spawnSync } from 'node:child_process';
const run = (code) => spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
let r = run(`Promise.reject(new Error('floating boom')); setTimeout(() => console.log('still running'), 100)`);
console.log('default: exit code', r.status, '| still running printed:', r.stdout.includes('still running'));
r = run(`process.on('unhandledRejection', (reason) => console.log('reported:', reason.message)); Promise.reject(new Error('floating boom')); setTimeout(() => console.log('still running'), 100)`);
console.log('with handler: exit code', r.status, '|', r.stdout.trim().split('\n').join(' / '));
Run in a node:22 container (Node 22.23), it prints:
default: exit code 1 | still running printed: false
with handler: exit code 0 | reported: floating boom / still running
Layer 1 and 2: code, a wrapper, a helper and a global net
rejections.js has three pieces and one reporter. Read the file in that order; each block below is annotated with its purpose:
request()is the single place that callsfetch. It turns network failures and non-2xx responses into anApiErrorthat carriesurl,statusand the originalcause, so a rejection that does escape says which endpoint failed and how.fireAndForget(promise, label, report)is the only sanctioned way to start work nobody awaits (analytics, prefetch). It attaches a.catchthat reports with a label.installRejectionReporter(report)listens forunhandledrejectionand reports the message, name,url,status, whether the reason had a stack, and the current route.
export class ApiError extends Error {
constructor(message, { url, status, cause } = {}) {
super(message, { cause });
this.name = 'ApiError';
this.url = url;
this.status = status;
}
}
// One place that turns "fetch" into "a promise that rejects with an ApiError carrying url and status".
export async function request(url, options) {
let res;
try {
res = await fetch(url, options);
} catch (cause) {
throw new ApiError('network failure', { url, cause });
}
if (!res.ok) throw new ApiError(`HTTP ${res.status}`, { url, status: res.status });
return res.json();
}
// The only sanctioned way to start work nobody awaits: the rejection gets an owner and a label.
export function fireAndForget(promise, label, report) {
promise.catch((err) => report({ kind: 'handled', label, message: err.message, url: err.url, status: err.status }));
}
// Safety net: anything that still escapes is reported with enough context to find it.
export function installRejectionReporter(report) {
window.addEventListener('unhandledrejection', (event) => {
const r = event.reason;
report({
kind: 'unhandled',
message: r?.message ?? String(r),
name: r?.name,
url: r?.url,
status: r?.status,
hasStack: Boolean(r?.stack),
route: location.pathname,
});
// no preventDefault(): the browser console still shows the error during development
});
}
The driver (driver.mjs, next to rejections.js) starts one floating request() against a stubbed API that always answers 503, one floating request() to an address whose connection the stub aborts (a network failure), one fireAndForget(request(...)) and one rejection with a bare string, in Chromium, Firefox and WebKit through Playwright (npm i playwright@1.48.2):
import { chromium, firefox, webkit } from 'playwright';
import fs from 'node:fs';
const lib = fs.readFileSync('./rejections.js', 'utf8').replace(/^export /gm, ''); // plain script for the page
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage();
await page.route('http://app.test/**', (route) =>
route.request().url().includes('/offline')
? route.abort()
: route.request().url().includes('/api/')
? route.fulfill({ status: 503, body: '{}' })
: route.fulfill({ contentType: 'text/html', body: '<body></body>' }));
await page.goto('http://app.test/checkout');
await page.addScriptTag({ content: lib });
const reports = await page.evaluate(async () => {
const reports = [];
const report = (r) => reports.push(r);
installRejectionReporter(report);
request('/api/cart'); // floating: nobody owns this rejection
request('/offline'); // floating: the network itself fails
fireAndForget(request('/api/analytics'), 'send analytics', report);
new Promise((_, reject) => reject('a bare string')); // rejected with a non-Error
await new Promise((r) => setTimeout(r, 200));
return reports;
});
console.log(`[${name}]`);
for (const r of reports.sort((a, b) => a.kind.localeCompare(b.kind) || a.message.localeCompare(b.message))) console.log(' ', JSON.stringify(r));
const unhandled = reports.filter((r) => r.kind === 'unhandled');
if (unhandled.length !== 3 || reports.filter((r) => r.kind === 'handled').length !== 1) throw new Error('unexpected report set');
if (!unhandled.some((r) => r.url === '/offline' && r.name === 'ApiError' && r.message === 'network failure')) throw new Error('network failure was not wrapped in ApiError');
await browser.close();
}
In the Playwright v1.48.2 container it prints the same four reports in all three engines (shown for Chromium; the script throws if the report set differs or if the network failure is not wrapped in an ApiError):
[chromium]
{"kind":"handled","label":"send analytics","message":"HTTP 503","url":"/api/analytics","status":503}
{"kind":"unhandled","message":"a bare string","hasStack":false,"route":"/checkout"}
{"kind":"unhandled","message":"HTTP 503","name":"ApiError","url":"/api/cart","status":503,"hasStack":true,"route":"/checkout"}
{"kind":"unhandled","message":"network failure","name":"ApiError","url":"/offline","hasStack":true,"route":"/checkout"}
Read what it shows. The floating request('/api/cart') is now identifiable (endpoint, status, stack, route) instead of an anonymous warning. The aborted request is reported as an ApiError named network failure with its url instead of the bare browser TypeError that fetch rejects with, which carries no endpoint. The fireAndForget call never reaches the global handler because it had an owner. The bare string 'a bare string' has no stack at all, which is the strongest argument for the rule that rejections must be Error objects.
Layer 3: tooling
Lint (typescript-eslint, needs type information). @typescript-eslint/no-floating-promises reports a promise-valued statement unless it is awaited, returned, ends in .catch(...) or a two-argument .then(...), or is prefixed with void. The rule's ignoreVoid option defaults to true, and the documentation itself warns that void does not handle the rejection. Setting ignoreVoid: false makes void promise an error too, so the only accepted way to leave work unawaited is the helper above. no-misused-promises catches an async function passed where a callback that returns nothing is expected (a click handler: the rejection lands nowhere). only-throw-error and prefer-promise-reject-errors keep reasons as Error objects with stacks. Of the four, no-floating-promises is the rule aimed at the exact hole in the question (a promise nobody handles); the other three close neighbouring ways a rejection gets lost or arrives without a stack.
Reading the config: tseslint.configs.base sets up only the parser and plugin options typescript-eslint needs and enables no rules (the typescript-eslint documentation describes it as a minimal ruleset), so every rule here is one listed explicitly. projectService: true makes the parser ask TypeScript's own service for type information about each file, which the promise rules need because they must know which expressions are promises; tsconfigRootDir tells the parser which directory holds the project root. The four entries under rules are the four rules above.
eslint.config.mjs (with typescript@5, eslint@9, typescript-eslint@8 installed):
import tseslint from 'typescript-eslint';
export default tseslint.config(
{ files: ['**/*.ts'], extends: [tseslint.configs.base] },
{
files: ['**/*.ts'],
languageOptions: { parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname } },
rules: {
'@typescript-eslint/no-floating-promises': ['error', { ignoreVoid: false }], // `void p` does not handle a rejection, so it is not accepted either
'@typescript-eslint/no-misused-promises': 'error', // async function passed where a void callback is expected
'@typescript-eslint/only-throw-error': 'error', // throw Error objects so the stack exists
'@typescript-eslint/prefer-promise-reject-errors': 'error',
},
},
);
tsconfig.json (the TypeScript compiler settings the linter reads; include lists the files the project service covers, noEmit stops it producing output):
{ "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", "strict": true, "lib": ["ES2022", "DOM"], "noEmit": true }, "include": ["*.ts"] }
checkout.ts, three bugs and one correct function:
declare function saveCart(id: string): Promise<void>;
declare function fireAndForget(p: Promise<unknown>, label: string): void;
declare function track(event: string): Promise<void>;
export function onSubmit(id: string) {
saveCart(id); // floating: a rejection has no owner
track('submit').then(() => console.log('ok')); // still floating: .then without .catch
}
export function wireButton(button: HTMLButtonElement, id: string) {
button.addEventListener('click', async () => { // async handler where a void callback is expected
await saveCart(id);
});
}
export async function fine(id: string) {
await saveCart(id);
fireAndForget(track('done'), 'track done'); // the sanctioned helper: owns the rejection
void track('late'); // void alone does not handle a rejection
}
npx eslint checkout.ts, run in a node:22 container, prints:
/w/checkout.ts
6:3 error Promises must be awaited, end with a call to .catch, or end with a call to .then with a rejection handler @typescript-eslint/no-floating-promises
7:3 error Promises must be awaited, end with a call to .catch, or end with a call to .then with a rejection handler @typescript-eslint/no-floating-promises
11:36 error Promise returned in function argument where a void return was expected @typescript-eslint/no-misused-promises
19:3 error Promises must be awaited, end with a call to .catch, or end with a call to .then with a rejection handler @typescript-eslint/no-floating-promises
✖ 4 problems (4 errors, 0 warnings)
Lines 6, 7, 11 and 19 are flagged: 6 is a bare call to a promise-returning function, 7 is a .then with no rejection handler, 11 is an async function handed to addEventListener, and 19 is void, rejected because ignoreVoid is false. Line 18 (the helper) is accepted. On a big legacy codebase, turn the rules on as warn, record the count, and let CI (the automated build-and-test run on every change) fail when the count rises or when any file in a cleaned directory regresses; promote directories to error as they reach zero. That makes the cleanup steady instead of a single risky mega-PR.
Tests. An end-to-end test should fail on any unhandled rejection. Playwright's page.on('pageerror', ...) reports uncaught exceptions on the page; the check below injects a floating rejection and prints how many pageerror events each engine produced:
import { chromium, firefox, webkit } from 'playwright';
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage();
const errors = [];
page.on('pageerror', (e) => errors.push(e.message));
await page.setContent('<body></body>');
await page.evaluate(() => { Promise.reject(new Error('floating boom')); });
await page.waitForTimeout(200);
console.log(name, 'pageerror count:', errors.length, errors[0]);
await browser.close();
}
In the Playwright container it prints (WebKit prefixes the message with the error name):
chromium pageerror count: 1 floating boom
firefox pageerror count: 1 floating boom
webkit pageerror count: 1 Error: floating boom
A test fixture (shared setup and teardown code the test runner applies around every test) that collects pageerror and asserts the list is empty at the end of every test turns every existing end-to-end test into an unhandled-rejection detector. For unit tests on Node, run the runner with the default throw mode so the process fails, or register an unhandledRejection hook that records and fails the test.
Layer 4: review process and visibility in production
- Review checklist (three questions on any diff that touches async code): Who awaits or owns this promise? What does the user see if it rejects? Does it reject with an
Errorthat says which operation failed? - Ban silent catches.
.catch(() => {})converts a visible bug into an invisible one; allow a catch only if it reports, recovers or rethrows. - Report from the net, deduplicated. Group reports by a fingerprint (a short key built from the message plus the top stack frame, so repeats of one bug count as one), record release version and route, and alert on a new fingerprint or a rising rate, not on every event. The aim is zero entries; a non-zero count after the cleanup is the bug list.
- Do not hide them in the handler. Calling
preventDefault()in production silences the console but not the bug; report first, and only suppress the console noise once the report exists.
Trade-offs and pitfalls
- Lint rules cost build time because they need type information (the typescript-eslint documentation calls this a performance tradeoff). Allow an
eslint-disableline only with a comment that says who owns the rejection. - A global handler is a net, not a fix. If it becomes the place where errors are routinely "handled", the codebase stays as fragile as before.
- Third-party and cross-origin scripts (scripts served from another origin, such as an ad or analytics vendor's domain). MDN notes that rejections from cross-origin scripts do not fire the event (it could leak data), so that class of failure needs the vendor's own reporting.
Running the code
Save the blocks as node-demo.mjs, rejections.js, driver.mjs, eslint.config.mjs, tsconfig.json, checkout.ts and the last browser check as pageerror.mjs (the .mjs files use import and top-level await). Install once: npm i playwright@1.48.2 typescript@5 eslint@9 typescript-eslint@8. Then run node node-demo.mjs (Node 22), node driver.mjs and node pageerror.mjs (Playwright v1.48.2 container, which has the browsers) and npx eslint checkout.ts (exits 1 because the file has the four errors shown).
Unlock Full Question Bank
Get access to all 24 Asynchronous and Event-Driven Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.