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.
A page freezes and stops painting even though no single function looks slow: a long promise chain keeps scheduling more promise work. Explain why timers and rendering never get a turn, show code that causes it, and how you would restructure it so the page stays responsive.
Sample Answer
Direct answer
The page freezes because promise callbacks are microtasks, and the browser empties the whole microtask queue, including microtasks added while it is emptying, before it moves on to the next task (a timer callback, an input event) or to painting. A chain in which every callback schedules another promise callback keeps the queue from ever becoming empty, so the event loop never reaches the timers or the renderer. No single function is slow; the loop just never gets control back. The fix is to stop using a promise job as a way of "waiting": wait on the thing you are really waiting for, or process in slices and hand control back to the event loop between slices.
How the event loop orders things
- The event loop (the browser's scheduler that runs your code piece by piece) takes one task from a task queue. Timer callbacks, user input events and network callbacks are tasks.
- When that task finishes and the call stack is empty, it runs all pending microtasks: promise reactions (
.then,.catch,.finallycallbacks, the continuation after anawait) andqueueMicrotaskcallbacks. - The wording in MDN (Mozilla's web documentation) for step 2: "microtasks can enqueue new microtasks and those new microtasks will execute before the next task begins to run, and before the end of the current event loop iteration."
- Only then may the browser do rendering and painting, and start the next iteration with the next task. MDN describes an iteration as at most one task, then any pending microtasks, then any needed rendering.
So microtasks are ahead of everything else in line. A timer set with setTimeout(fn, 0) is a task, so it waits for the microtask queue to drain, however long that takes. The same applies to await on an already-settled promise: while (true) { await Promise.resolve(); } never lets a timer or a paint run, even though it looks "asynchronous".
Code that causes it
spinWaitFor polls a flag by re-queuing a promise job. The only code that sets the flag is a timer callback, which cannot run while the spin goes on: a deadlock (each side waits for the other, so neither moves) with no error. In production the same shape hides in a retry or polling helper whose check resolves from a cache without ever waiting on I/O (function poll() { return check().then(done => done ? done : poll()) } with a check that returns an already-resolved promise). The code lives in starve.mjs; two short runner files follow it, run-node.mjs for Node and run-browser.mjs for browsers. The harness gives the spin a limit of one million turns so that it can report instead of hanging, and it contains both fixes.
// Works unchanged in Node (as a module) and in a browser page.
const log = [];
const note = (m) => log.push(m);
// BUG: waits for a flag by re-queuing a promise job. A timer is the only thing that sets the flag.
function spinWaitFor(isReady, maxSpins) {
let spins = 0;
return new Promise((resolve) => {
(function step() {
if (isReady()) return resolve(`ready after ${spins} spins`);
if (++spins >= maxSpins) return resolve(`gave up after ${spins} spins, flag still false`);
Promise.resolve().then(step); // another microtask, so the timer below never gets a turn
})();
});
}
// FIX: wait for the thing itself. A timer callback (a macrotask) resolves the promise.
function waitForFlag(delayMs) {
return new Promise((resolve) => setTimeout(() => resolve('flag set by timer'), delayMs));
}
// FIX for real CPU-bound chains: process in slices and hand the loop back between slices.
const yieldToLoop = () => new Promise((resolve) => setTimeout(resolve, 0));
async function processInSlices(items, sliceSize, work) {
for (let i = 0; i < items.length; i += sliceSize) {
for (const item of items.slice(i, i + sliceSize)) work(item);
await yieldToLoop(); // timers, input and rendering can run here
}
}
export async function run() {
let flag = false;
setTimeout(() => { flag = true; note('timer callback ran'); }, 0);
note(await spinWaitFor(() => flag, 1_000_000));
note('--- after the spin ---');
await new Promise((r) => setTimeout(r, 20)); // now the loop is free
note(`flag is ${flag}`);
// slices: a timer queued before the work runs between slices, not after all of them
let ticks = 0;
const t = setInterval(() => { ticks++; }, 0);
await processInSlices(Array.from({ length: 50 }, (_, i) => i), 10, (n) => n * n);
clearInterval(t);
note(`interval fired during sliced work: ${ticks > 0}`);
note(await waitForFlag(5));
return log;
}
run-node.mjs:
import { run } from './starve.mjs';
for (const line of await run()) console.log(line);
run-browser.mjs loads the same file as a page script in all three Playwright engines (npm i playwright@1.48.2 first):
import { chromium, firefox, webkit } from 'playwright';
import fs from 'node:fs';
const src = fs.readFileSync('./starve.mjs', 'utf8').replace('export async function run', 'window.run = async function run');
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage();
await page.setContent('<body></body>');
await page.addScriptTag({ content: src });
const lines = await page.evaluate(() => window.run());
console.log(`[${name} ${browser.version()}]`); for (const l of lines) console.log(' ' + l);
await browser.close();
}
Run in a node:22 container (node run-node.mjs) it prints:
gave up after 1000000 spins, flag still false
--- after the spin ---
timer callback ran
flag is true
interval fired during sliced work: true
flag set by timer
In the Playwright v1.48.2 container (Chromium 130.0, Firefox 131.0, WebKit 18.0) the browser run prints the same six lines under each of [chromium ...], [firefox 131.0] and [webkit 18.0]. The order is the point: "timer callback ran" appears only after the spin has given up and the loop got control back, even though the timer was scheduled before the spin started and with a 0 ms delay. With an unbounded spin the timer never runs at all, and in a browser the tab stops painting and responding.
How to restructure it
- Wait on the real event. If a timer or an event sets the flag, return a promise that the timer or event resolves (
waitForFlagin the harness). Nothing spins, and the loop is free while waiting. - Slice real CPU work.
processInSliceshandles 10 items, then awaitssetTimeout(resolve, 0). The timeout is a task, so a yield through it lets timers, input and rendering run before the next slice; the harness proves it by counting an interval timer that fires during the sliced work.scheduler.yield()does the same job where it exists, but MDN lists it as not Baseline (MDN's label for features that work across all the major current browsers), so feature-detect it and fall back tosetTimeout. - Move the work to a Worker when it is heavy rather than long-waiting.
- Put a ceiling on any promise-driven loop (maximum iterations or a deadline) so a logic bug becomes an error message rather than a frozen tab.
Diagnosing it in a real app
Open the DevTools Performance panel and record: a frozen page shows one task that never ends, or a very long one with the promise-callback stack repeated inside it, and no frames drawn in the frame timeline. Breaking in the debugger lands inside the then callback each time. The Long Tasks API reports any stretch where the main thread is busy for 50 ms or longer (MDN), which is how production monitoring finds the milder versions of this.
Pitfalls
queueMicrotaskin browsers andprocess.nextTickin Node both run ahead of timers, so a chain of either can starve them.process.nextTickandsetImmediateare Node.js APIs (setImmediateruns its callback in the loop phase right after I/O callbacks); they show that the same starvation shape exists on a server, which matters to full-stack code. Node's documentation saysnextTickcallbacks run before the event loop continues; the check below confirms that a million-stepnextTickchain finishes before a 0 ms timer and asetImmediatecallback get to run:
let n = 0;
const order = [];
setTimeout(() => order.push('timer'), 0);
setImmediate(() => {
order.push('immediate');
setImmediate(() => { // runs on the next loop iteration, after the timer and the first immediate
console.log('first to finish:', order[0], '| timer and immediate both ran later:', order.includes('timer') && order.includes('immediate'));
if (order[0] !== 'nextTick chain done') throw new Error('timer ran before the nextTick chain finished');
if (!order.includes('timer') || !order.includes('immediate')) throw new Error('timer or immediate never ran');
});
});
(function spin() {
if (++n < 1_000_000) process.nextTick(spin); // each step schedules the next one
else order.push('nextTick chain done');
})();
It prints first to finish: nextTick chain done | timer and immediate both ran later: true (Node 22, node:22 container) and exits 0 on every run; the report waits for a second setImmediate, which runs on the loop iteration after both the timer and the first immediate, so it does not depend on how long the million-step chain takes. A fixed setTimeout(report, 50) is not a safe way to wait here: the chain itself takes about 45 ms on one CPU, so a 50 ms timer can fire in the same timers phase as the 0 ms timer, before the immediate, and the report then prints false.
- A recursive chain of
setTimeout(fn, 0)does not starve rendering, because each step is a task and rendering can happen between tasks; it is the right shape for polling, with a real delay. - Do not "fix" starvation by wrapping the spin in
async/await. That is still a microtask.
Users rapidly click different items and occasionally the detail panel ends up showing the wrong item. Review the code below, explain exactly how that happens, and fix it so only the response for the most recent click is ever rendered.
let current = {};
function fetchAndSet(id) {
fetch(`/data/${id}`).then(res => res.json()).then(data => { current = data; render(current); });
}
Sample Answer
Direct answer
Every click starts an independent fetch, and each one writes to current and calls render when its own reply comes back. Nothing ties a reply to the click that is current now, so if the reply for an earlier click arrives after the reply for a later click, the earlier one runs last and the panel shows the wrong item. The fix is to give each click an identity and refuse to render anything that is not the latest: abort the previous request with an AbortController and also compare a per-click counter before rendering. The first stops the work; the second protects every step that cannot be aborted. Handle errors only for the current click.
Exactly how it goes wrong
Take the clicks "item 1" at 0 ms and "item 2" at 30 ms, where item 1's reply is slow (300 ms) and item 2's is quick (20 ms).
fetchAndSet(1)starts request 1 and returns. Its.thencallbacks wait for the reply.fetchAndSet(2)starts request 2. Two requests are in flight.- Request 2's reply arrives first:
current = {id: 2},rendershows item 2. The user sees the right panel. - Request 1's reply arrives later and runs the same callbacks:
current = {id: 1},rendershows item 1. The newest data is overwritten by the oldest.
The wrongness lives in the time between the click and the reply, which is why it is intermittent: it needs a slower reply for the earlier click. The code is also missing three other things: res.ok is never checked (a 404 or 500 still resolves and res.json() may then throw on an error page), no .catch exists (a failure becomes an unhandled promise rejection), and current is a shared variable that every in-flight request can overwrite.
The code, with the fix and the optimistic case
The program has a local server whose item 1 is slow, runs the original code, then the fix, then two optimistic rename scenarios. An optimistic update shows the result of an action on screen immediately and sends the request in the background, undoing the change if the server refuses; the last section of the program uses it. The output lines map to the sections of the program like this: line 1 is the original code (section 1); lines 2 and 3 are the fix with and without the counter (sections 2, 2a); lines 4 and 5 are the slow-step variants (section 2b); lines 6 and 7 are the late-failure variants (section 2d); line 8 is the failure case (section 2c); lines 9 to 11 are the optimistic renames (section 3). A "non-abortable step" in section 2b stands for work after the reply that has no cancel option, such as a call into an SDK or a write to a local database.
import http from 'node:http';
import assert from 'node:assert/strict';
// ---------- test server: per-item reply delays, one item that 404s, a renameable name ----------
const DETAIL_DELAY = { 1: 300, 2: 20, 3: 50 }; // item 1 is slow, so it answers after item 2
const RENAME = { B: { delay: 200, ok: false }, C: { delay: 50, ok: true }, D: { delay: 200, ok: true }, E: { delay: 50, ok: false } };
let serverName = 'A';
const cancelledByClient = []; // ids whose request the client dropped before the reply was sent
const server = http.createServer((req, res) => {
const u = new URL(req.url, 'http://x');
if (u.pathname.startsWith('/data/')) {
const id = Number(u.pathname.split('/')[2]);
if (!(id in DETAIL_DELAY)) { res.statusCode = 404; return res.end('no such item'); }
res.on('close', () => { if (!res.writableEnded) cancelledByClient.push(id); });
return setTimeout(() => res.end(JSON.stringify({ id })), DETAIL_DELAY[id]);
}
if (u.pathname === '/rename') {
const n = u.searchParams.get('name'), cfg = RENAME[n];
return setTimeout(() => {
if (!cfg.ok) { res.statusCode = 500; return res.end('fail'); }
serverName = n; res.end('ok');
}, cfg.delay);
}
if (u.pathname === '/name') return res.end(JSON.stringify({ name: serverName }));
});
await new Promise(r => server.listen(0, r));
const base = `http://localhost:${server.address().port}`;
const sleep = ms => new Promise(r => setTimeout(r, ms));
// ---------- 1. the code from the question ----------
function makeOriginal(renders) {
let current = {};
return function fetchAndSet(id) {
fetch(`${base}/data/${id}`).then(res => res.json()).then(data => { current = data; renders.push(current.id); });
};
}
// ---------- 2. the fix: abort the previous request AND ignore anything that is no longer the latest ----------
function makeFixed(renders, errors, { guard = true, enrich = async d => d } = {}) {
let controller;
let latest = 0;
return async function select(id) {
controller?.abort(); // 1. stop the previous request, including its body read
controller = new AbortController();
const { signal } = controller;
const mine = ++latest; // 2. remember which click this call belongs to
try {
const res = await fetch(`${base}/data/${id}`, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await enrich(await res.json()); // enrich() stands for any step that cannot be aborted
if (guard && mine !== latest) return; // superseded while that step was running
renders.push(data.id);
} catch (e) {
if (e.name === 'AbortError' || (guard && mine !== latest)) return; // expected, not an error
errors.push(e.message); // a real failure of the CURRENT click
}
};
}
// ---------- 3. optimistic rename: show the new name at once, undo it if the server refuses ----------
function makeRenamer({ safe }) {
const ui = { name: 'A' };
let inflight = 0, dirty = false;
const resync = async () => { ui.name = (await (await fetch(`${base}/name`)).json()).name; };
async function rename(name) {
const previous = ui.name;
ui.name = name; // optimistic
inflight++;
try {
const res = await fetch(`${base}/rename?name=${name}`, { method: 'PUT' });
if (!res.ok) throw new Error('HTTP ' + res.status);
} catch {
if (!safe) ui.name = previous; // roll back to the value before THIS action
else dirty = true; // note it; reconcile with the server later
} finally {
inflight--;
if (safe && dirty && inflight === 0) { dirty = false; await resync(); }
}
}
return { ui, rename };
}
// ---------- driver ----------
async function clicks(fn, plan) { // plan: [[atMs, arg], ...]
const started = []; let last = 0;
for (const [at, arg] of plan) { await sleep(at - last); last = at; started.push(fn(arg)); }
await Promise.all(started);
}
// 1. original code: click item 1 (slow), then item 2 (fast)
let renders = [];
const original = makeOriginal(renders);
original(1); await sleep(30); original(2); await sleep(500);
console.log('original code, clicks 1 then 2 -> renders in order:', JSON.stringify(renders), '(panel ends on item', renders.at(-1) + ')');
assert.deepEqual(renders, [2, 1]);
// 2. fixed code, same clicks
renders = []; let errors = [];
let select = makeFixed(renders, errors);
await clicks(select, [[0, 1], [30, 2]]); await sleep(400);
console.log('abort + guard, clicks 1 then 2 -> renders:', JSON.stringify(renders), 'errors:', JSON.stringify(errors));
assert.deepEqual(renders, [2]); assert.deepEqual(errors, []);
// 2a. abort alone, and what it does on the wire: the server sees request 1 dropped before it answered
renders = []; errors = []; cancelledByClient.length = 0;
select = makeFixed(renders, errors, { guard: false });
await clicks(select, [[0, 1], [30, 2]]); await sleep(400);
console.log('abort only, clicks 1 then 2 -> renders:', JSON.stringify(renders), 'requests dropped by the client:', JSON.stringify(cancelledByClient));
assert.deepEqual(renders, [2]); assert.deepEqual(cancelledByClient, [1]);
assert.deepEqual(errors, []); // the aborted request's AbortError is swallowed, not reported
// 2b. a non-abortable step after the response: abort alone is not enough, the guard is
const slowEnrich = async d => { await sleep(d.id === 1 ? 400 : 5); return d; }; // item 1's post-processing takes 400 ms
for (const guard of [false, true]) {
renders = []; errors = [];
select = makeFixed(renders, errors, { guard, enrich: slowEnrich });
// item 1's reply (300 ms) is in and its slow post-processing is running when click 2 happens
await clicks(select, [[0, 1], [350, 2]]);
console.log(`abort ${guard ? '+ guard' : 'only '}, slow non-abortable step -> renders:`, JSON.stringify(renders));
assert.deepEqual(renders, guard ? [2] : [2, 1]);
}
// 2d. a superseded click that fails late: only the guard keeps its error out of the current view
const failingEnrich = async d => { await sleep(d.id === 1 ? 400 : 5); if (d.id === 1) throw new Error('post-processing failed'); return d; };
for (const guard of [false, true]) {
renders = []; errors = [];
select = makeFixed(renders, errors, { guard, enrich: failingEnrich });
await clicks(select, [[0, 1], [350, 2]]); await sleep(100);
console.log(`abort ${guard ? '+ guard' : 'only '}, old click fails late -> renders:`, JSON.stringify(renders), 'errors:', JSON.stringify(errors));
assert.deepEqual(renders, [2]); assert.deepEqual(errors, guard ? [] : ['post-processing failed']);
}
// 2c. failures: a 404 for the current click is reported, never thrown unhandled
renders = []; errors = [];
select = makeFixed(renders, errors);
await select(99);
console.log('404 for the current click -> renders:', JSON.stringify(renders), 'errors:', JSON.stringify(errors));
assert.deepEqual(errors, ['HTTP 404']);
// 3. optimistic updates
for (const [label, safe] of [['naive rollback ', false], ['reconcile after', true]]) {
serverName = 'A';
const r = makeRenamer({ safe });
await clicks(r.rename, [[0, 'B'], [50, 'C']]); // B will fail after 200 ms, C succeeds after 50 ms
await sleep(50);
console.log(`${label} rename B (fails) then C (ok) -> screen shows ${r.ui.name}, server has ${serverName}`);
assert.equal(safe ? r.ui.name : 'x', safe ? serverName : 'x');
if (!safe) assert.notEqual(r.ui.name, serverName);
}
{
serverName = 'A';
const r = makeRenamer({ safe: true });
await clicks(r.rename, [[0, 'D'], [50, 'E']]); // D succeeds after 200 ms, E fails after 50 ms
await sleep(50);
console.log(`reconcile after rename D (ok) then E (fails) -> screen shows ${r.ui.name}, server has ${serverName}`);
assert.equal(r.ui.name, serverName); assert.equal(serverName, 'D');
}
server.close(); server.closeAllConnections();
In section 3, ui.name is the name on screen, inflight counts rename requests that have not finished, and dirty means "a request failed, so the screen may no longer match the server". The naive version, on failure, restores the snapshot (the value saved before that action). The safe version only sets dirty; when inflight drops to 0 it calls resync, which reconciles (fetches the server's real name and replaces the screen's guess with it).
Run in a node:22 container (Node 22.23), it prints the following. The delays are fixed, with margins of tens of milliseconds, and each line is checked by an assert, so a wrong fix makes the program exit with an error.
original code, clicks 1 then 2 -> renders in order: [2,1] (panel ends on item 1)
abort + guard, clicks 1 then 2 -> renders: [2] errors: []
abort only, clicks 1 then 2 -> renders: [2] requests dropped by the client: [1]
abort only , slow non-abortable step -> renders: [2,1]
abort + guard, slow non-abortable step -> renders: [2]
abort only , old click fails late -> renders: [2] errors: ["post-processing failed"]
abort + guard, old click fails late -> renders: [2] errors: []
404 for the current click -> renders: [] errors: ["HTTP 404"]
naive rollback rename B (fails) then C (ok) -> screen shows A, server has C
reconcile after rename B (fails) then C (ok) -> screen shows C, server has C
reconcile after rename D (ok) then E (fails) -> screen shows D, server has D
Request id versus abort
| Mechanism | What it protects | What it cannot do |
|---|---|---|
AbortController: abort the previous request when a new click arrives | The request and its body read are cancelled, so the superseded reply never reaches your code and the connection is freed. | Only covers operations that accept the signal. A post-processing step after the response (decoding, an SDK call, a store write) keeps running. The server may still do the work. |
Per-click counter (mine !== latest) | Works for any async step, because the check is made right before the state is touched. | The superseded work still runs to completion and costs bandwidth and CPU. |
The third output line shows what abort does on its own: the server saw request 1 dropped before it answered, and only item 2 rendered even with no counter, and the aborted request reported no error (the AbortError check, which the program asserts here because the counter is switched off in this scenario). The fourth and fifth output lines show the difference: with a 400 ms non-abortable step after the response, abort alone lets the stale item 1 render after item 2, and abort plus the counter does not. The sixth and seventh lines run the error path: an old click whose post-processing fails late puts an error in the current view with abort only, and stays silent with the counter. Use both for a data-fetching panel. Abort alone is enough when fetch plus res.json() are the only awaited steps; the counter alone is enough when you cannot cancel anything.
In the code, AbortError is swallowed because aborting is the normal path, and any other error is shown only if the click that failed is still the latest. Without that check, an error from an old click could replace the panel's content with an error message; the sixth output line shows exactly that happening when the counter is removed.
When the stale action is an optimistic update
An optimistic update shows the result of an action immediately and sends the request in the background, undoing the change if the server refuses. The same race appears in a different shape: action one fails after action two has already succeeded.
- The naive rollback restores "the value before this action". Rename
AtoB(the server will refuse it after 200 ms), then toCat 50 ms (accepted at 100 ms). WhenBfails, the screen reverts toA, while the server hasC(the "naive rollback" line). - The safer rule does not guess. On a failure it marks the state dirty, and when no request is left in flight it fetches the server's value once and shows that. The "reconcile after" lines show the screen matching the server in both orders of success and failure.
- A request id alone ("ignore a failure if a newer action exists") handles the first scenario but not the second. Timeline for
D(accepted after 200 ms) thenE(refused after 50 ms): at 0 ms the screen showsD; at 50 ms it showsE; at 100 msEis refused, and the server still holdsAbecauseDhas not been accepted yet, so there is no confirmed value to roll back to; at 200 msDis accepted and the server holdsD. The safe rule waits until nothing is in flight and then shows what the server holds,D, which is the value the last output line reports. Reconciling with the server once nothing is in flight handles both orders.
One server-side hazard remains: writes can be applied in a different order than they were sent, so for data that matters, send a version number the server checks, or send one write per item at a time.
Pitfalls
- Resetting the panel to a loading state on every click but not cancelling: the spinner shows while an old reply can still land.
- Keying the guard on the wrong thing. Compare the click identity, not just the item id: clicking item 1, item 2, then item 1 again produces two requests for item 1.
- Forgetting to guard the error path, so a slow failure from an old click overwrites the current view.
- Rolling back an optimistic change to a stale snapshot.
Running the code
# save the listing as cases.mjs (ES modules and top-level await need the .mjs extension)
docker run --rm -v "$PWD":/w -w /w node:22 node cases.mjs
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.
You have an array of functions that each return a promise, for example 500 uploads. Write runWithConcurrency(tasks, limit) that keeps at most limit running at once, returns results in the original order, and lets the caller choose between stopping at the first failure and collecting every outcome. How does it behave when limit exceeds the task count or a task throws synchronously?
Sample Answer
Direct answer
Start limit workers. Each worker loops: take the next unstarted index from a shared counter, run that task, store the result at that same index, and repeat until the tasks run out. At most limit tasks are ever in flight, results keep input order because they are written by index (not pushed in finishing order), and a task that finishes immediately frees its worker to start the next one (a sliding window: the group of running tasks moves along the list one task at a time, instead of waiting for a whole group to finish). A settle option picks the failure policy: reject on the first failure and start nothing new, or record every outcome. The tasks must be functions that create the promise (factories), because a promise that already exists is already running and no pool can delay it. A "factory" here is just a function that, when called, creates and starts the work: () => upload(file) is a factory, upload(file) is the promise it makes.
Implementation
import assert from 'node:assert/strict';
/**
* Runs task functions with at most `limit` in flight. Results keep the input order.
* settle=false: reject with the first failure and start nothing new.
* settle=true: never reject because of a task; resolve with {status, value|reason} per task.
*/
export function runWithConcurrency(tasks, limit, { settle = false } = {}) {
if (!Number.isInteger(limit) || limit < 1) {
return Promise.reject(new RangeError('limit must be an integer >= 1'));
}
const n = tasks.length;
const results = new Array(n);
let next = 0; // index of the next task to start (shared by all workers)
let failed = false; // set on the first failure in fail-fast mode
const worker = async () => {
while (!failed && next < n) {
const i = next++;
try {
// Calling inside the try turns a synchronous throw into a normal failure.
const task = tasks[i];
const value = await (typeof task === 'function' ? task() : task);
results[i] = settle ? { status: 'fulfilled', value } : value;
} catch (reason) {
if (!settle) { failed = true; throw reason; }
results[i] = { status: 'rejected', reason };
}
}
};
// Never more workers than tasks, so limit > tasks.length just starts every task.
const workers = Array.from({ length: Math.min(limit, n) }, worker);
return Promise.all(workers).then(() => results);
}
// ---------------- tests ----------------
const sleep = (ms, v) => new Promise(r => setTimeout(r, ms, v));
function tracked(durations, fail = {}) {
const stats = { active: 0, peak: 0, started: [] };
const tasks = durations.map((ms, i) => async () => {
stats.started.push(i);
stats.active++; stats.peak = Math.max(stats.peak, stats.active);
try {
await sleep(ms);
if (fail[i] === 'async') throw new Error(`task ${i} failed`);
return i * 10;
} finally { stats.active--; }
});
return { tasks, stats };
}
// 1. never exceeds the limit, and results are in input order even though they finish out of order
{
const { tasks, stats } = tracked([30, 5, 20, 1, 10, 2, 15, 3, 8, 4]);
const out = await runWithConcurrency(tasks, 3);
assert.deepEqual(out, [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]);
assert.equal(stats.peak, 3);
console.log('1 order kept, peak in flight =', stats.peak, 'results =', JSON.stringify(out));
}
// 2. limit larger than the task count
{
const { tasks, stats } = tracked([5, 5]);
const out = await runWithConcurrency(tasks, 100);
assert.deepEqual(out, [0, 10]); assert.equal(stats.peak, 2);
// A limit of 2 ** 32 only works because the worker count is capped at the task count:
// Array.from({ length: 2 ** 32 }) would throw "Invalid array length".
assert.deepEqual(await runWithConcurrency(tracked([1, 1]).tasks, 2 ** 32), [0, 10]);
console.log('2 limit 100 and limit 2 ** 32 with 2 tasks: peak =', stats.peak);
}
// 3. empty input and invalid limits
{
assert.deepEqual(await runWithConcurrency([], 4), []);
for (const bad of [0, -1, 1.5, NaN, undefined]) {
await assert.rejects(runWithConcurrency([() => 1], bad), RangeError);
}
console.log('3 empty input -> [], limits 0, -1, 1.5, NaN, undefined -> RangeError');
}
// 4. fail-fast on an async failure: rejects with it and starts no new task afterwards
{
const { tasks, stats } = tracked([5, 5, 5, 5, 5, 5, 5, 5, 5, 5], { 2: 'async' });
await assert.rejects(runWithConcurrency(tasks, 2), /task 2 failed/);
await sleep(50); // let in-flight tasks drain
assert.ok(stats.started.length < 10);
console.log('4 fail-fast: rejected with the task 2 error, fewer than 10 tasks were started:', stats.started.length < 10);
}
// 5. a task that throws synchronously (before returning a promise)
{
const started = [];
const mk = i => () => { started.push(i); if (i === 1) throw new TypeError('sync boom'); return sleep(5, i); };
const tasks = [0, 1, 2, 3, 4].map(mk);
await assert.rejects(runWithConcurrency(tasks, 2), TypeError);
console.log('5 fail-fast sync throw: rejected with TypeError, started =', JSON.stringify(started));
started.length = 0;
const out = await runWithConcurrency(tasks, 2, { settle: true });
assert.deepEqual(out.map(o => o.status), ['fulfilled', 'rejected', 'fulfilled', 'fulfilled', 'fulfilled']);
assert.ok(out[1].reason instanceof TypeError);
console.log('5 settle mode: statuses =', JSON.stringify(out.map(o => o.status)));
}
// 6. settle mode collects every outcome
{
const { tasks } = tracked([3, 3, 3, 3], { 1: 'async', 3: 'async' });
const out = await runWithConcurrency(tasks, 2, { settle: true });
assert.deepEqual(out.map(o => o.status), ['fulfilled', 'rejected', 'fulfilled', 'rejected']);
console.log('6 settle: ', out.map(o => o.status === 'fulfilled' ? o.value : o.reason.message).join(' | '));
}
// 7. Promise.all over every task starts them all at once; the pool does not
{
const a = tracked(Array(1000).fill(1));
await Promise.all(a.tasks.map(t => t()));
const b = tracked(Array(1000).fill(1));
await runWithConcurrency(b.tasks, 10);
assert.equal(a.stats.peak, 1000); assert.equal(b.stats.peak, 10);
console.log('7 1000 tasks: Promise.all peak =', a.stats.peak, ', pool(10) peak =', b.stats.peak);
}
// 8. plain promises are already running: no pool can limit them
{
let running = 0;
const make = () => { running++; return sleep(5); };
const promises = [make(), make(), make(), make(), make()]; // created, therefore started
const startedBeforePool = running;
await runWithConcurrency(promises, 1);
console.log('8 five promises created before the pool saw them: running at that moment =', startedBeforePool, 'with limit 1');
assert.equal(startedBeforePool, 5);
}
console.log('all checks passed');
Run in a node:22 container (Node 22.23), the checks print:
1 order kept, peak in flight = 3 results = [0,10,20,30,40,50,60,70,80,90]
2 limit 100 and limit 2 ** 32 with 2 tasks: peak = 2
3 empty input -> [], limits 0, -1, 1.5, NaN, undefined -> RangeError
4 fail-fast: rejected with the task 2 error, fewer than 10 tasks were started: true
5 fail-fast sync throw: rejected with TypeError, started = [0,1]
5 settle mode: statuses = ["fulfilled","rejected","fulfilled","fulfilled","fulfilled"]
6 settle: 0 | task 1 failed | 20 | task 3 failed
7 1000 tasks: Promise.all peak = 1000 , pool(10) peak = 10
8 five promises created before the pool saw them: running at that moment = 5 with limit 1
all checks passed
Every line is deterministic, and each check is an assert call, so a broken implementation exits with a non-zero status instead of printing a plausible line.
Tracing the ten-task example
Check 1 uses ten tasks with durations 30, 5, 20, 1, 10, 2, 15, 3, 8 and 4 ms, and limit 3. Idealised timing (every task takes exactly its duration, and when two workers free up at the same instant the lower-numbered one goes first), the three workers pick up indexes like this:
| Task index (duration) | Claimed by | Starts at (ms) | Ends at (ms) |
|---|---|---|---|
| 0 (30) | worker 1 | 0 | 30 |
| 1 (5) | worker 2 | 0 | 5 |
| 2 (20) | worker 3 | 0 | 20 |
| 3 (1) | worker 2 | 5 | 6 |
| 4 (10) | worker 2 | 6 | 16 |
| 5 (2) | worker 2 | 16 | 18 |
| 6 (15) | worker 2 | 18 | 33 |
| 7 (3) | worker 3 | 20 | 23 |
| 8 (8) | worker 3 | 23 | 31 |
| 9 (4) | worker 1 | 30 | 34 |
Worker 1 spends nearly the whole run on the 30 ms task while worker 2 gets through five tasks. The pool finishes at 34 ms. Fixed batches of three (30, 5, 20 then 1, 10, 2 then 15, 3, 8 then 4) would each wait for their slowest member and take 30 + 10 + 15 + 4 = 59 ms. The results array still reads [0, 10, ..., 90], because each worker writes to results[i] for the index it claimed, not to the next free position. Real timers add small jitter, so which worker claims which index can differ between runs; the order of the results and the peak of 3 in flight do not.
How it works
nextis a shared index. JavaScript runs one piece of code at a time on a single thread, soconst i = next++cannot be interleaved by another worker. There is no lock to write.Array.from({ length: Math.min(limit, n) }, worker)callsworkeronce for each of theMath.min(limit, n)slots (Array.fromaccepts a length-only object and a mapping function). Each call runs the worker synchronously up to its firstawait, which claims an index and starts its task, and returns a promise; the array of those promises is whatPromise.allreceives. This is how all the workers start immediately. Each worker is anasyncfunction. At itsawaitit hands control back, other workers run, and when its task settles it comes back to thewhiletest and claims the next index. Because the next task starts the instant any one finishes, throughput stays atlimitfor the whole run.results[i] = valuewrites by input position, so ordering is independent of completion order (check 1 finishes tasks in a scrambled order and still returns[0,10,...,90]).Promise.all(workers)is the failure policy for the fail-fast mode. When one worker throws,Promise.allrejects immediately with that error. The sharedfailedflag stops every other worker from claiming further tasks, so only the tasks already in flight finish (check 4 shows fewer than all tasks were started). The late settlements of those in-flight tasks are still handled byPromise.all, so they do not become unhandled rejections.- In
settlemode thecatchrecords{ status: 'rejected', reason }and the loop continues, so no worker ever throws and the final promise always resolves with one entry per task.
What each check proves: check 1 proves ordering and the limit (the durations are chosen so tasks finish out of order); check 2 proves limit above the task count is harmless, and its 2 ** 32 call fails with "Invalid array length" if the Math.min cap on the worker count is removed; check 3 proves empty input and invalid limits; check 4 proves fail-fast stops new work after an asynchronous failure; check 5 proves a synchronous throw is treated like a rejection in both modes; check 6 proves settle mode returns one outcome per task; check 7 proves Promise.all over factories starts everything while the pool does not; check 8 proves plain promises cannot be limited. In check 5 the output started = [0,1] follows from the code: with limit 2 both workers claim an index at once (0 and 1), task 1 throws before returning, failed becomes true, and when worker 1's task 0 finishes its while test fails, so no third task starts. A RangeError is the built-in error type for a value outside its allowed range, which is why a bad limit produces one.
Edge cases the question asks about
limitlarger than the number of tasks:Math.min(limit, n)workers are created, so every task starts at once and nothing waits (check 2: peak in flight is 2 withlimit100 and two tasks, and alimitof2 ** 32still works because only two workers are created; without theMath.mincap that call throws "Invalid array length"). No empty workers are left idle.- A task that throws synchronously (it throws before returning a promise, for example on bad arguments): the call
task()sits inside thetryin anasyncfunction, so the throw is caught exactly like a rejection. Without that, a synchronous throw would escape the loop in a way that skips your failure policy. In fail-fast mode the pool rejects with that error and stops starting tasks (check 5 started only the first two). Insettlemode it is recorded as a rejected entry and the rest still run. - Empty array: no workers,
Promise.all([])resolves, the result is[]. limitof 0, negative, fractional,NaNor missing: rejected with aRangeError. Alimitof 0 would otherwise create no workers and return an array of holes that looks like success, so the guard matters.- Cancellation: fail-fast stops new work but cannot stop tasks already running. If they should stop, pass an
AbortSignalinto each factory and abort it when the pool rejects.
Why factories, and why not Promise.all over everything
A promise is a handle to work that began when the expression that created it ran. uploads.map(file => upload(file)) has already started every upload before any pool sees the array, so check 8 shows five promises all running while the pool is told limit 1. A pool can only delay work that it is the one to start, which is why the parameter is an array of functions. The code tolerates plain promises and values for convenience (typeof task === 'function' test), but those entries are not limited, and a rejected one that is not yet awaited when another task fails can surface as an unhandled rejection.
Promise.all(tasks.map(t => t())) over 10,000 requests starts all 10,000 at once. The environment pays for that in sockets, memory for the in-flight requests, server and rate-limit rejections, and the browser or runtime may queue many of them anyway. Check 7 shows the difference exactly: 1000 tasks reach a peak of 1000 in flight with Promise.all and 10 with the pool.
The sliding window beats processing in fixed batches (chunk the array, await Promise.all each chunk). With durations 100, 10, 10, 10 ms and limit 2, batches take 100 + 10 = 110 ms (the second batch cannot start until the 100 ms task ends), while the sliding window takes 100 ms, because the second worker runs the three short tasks back to back (10 + 10 + 10 = 30 ms) while the first is still busy.
Complexity
Scheduling is O(n) in total, with O(limit) extra for the workers and O(n) for the results array. Time to finish is roughly the total task time divided by limit, bounded below by the longest single task.
Pitfalls
- Using
results.push(value)instead ofresults[i]: output order then follows completion order. - Starting
limittasks, then awaiting all of them before starting more (batching), which wastes the slack on short tasks. - Choosing a limit without knowing the real bottleneck: a limit above what the server, the connection or the rate limit allows only moves the queue somewhere you cannot see.
- Retrying inside the task is fine, but a retry that re-enqueues at the back of the pool changes ordering and fairness; keep retries inside the task so the slot stays occupied.
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.
Unlock Full Question Bank
Get access to all 23 Asynchronous and Event-Driven Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.