← Back to Frontend, page 3

frontend-0057 · Hard senior

A search box sometimes shows results for an older query after the user has typed more. Why does it happen, and how do you fix it?

Responses do not always come back in the order the requests were sent. If each response writes to the screen when it arrives, a slow old response can overwrite a newer one. Cancel the previous request with an AbortController, and also ignore any response that is not for the latest query.

Full answer

A user types "r", then "re", then "rea". Three requests leave in that order. Network and server time vary, so the answer for "r" can take 90 ms and the answer for "re" 10 ms. The page shows "re" first, then the late "r" result replaces it. The input says "rea" and the list shows results for "r". This is a race condition, and it is hard to reproduce on a fast local server.

Fixes, from basic to complete:

  1. Abort the previous request. fetch(url, { signal }) accepts the signal of an AbortController. When a new query starts, call controller.abort() on the old one. The old promise rejects with an AbortError, which the code must treat as normal, not as a failure. Aborting also saves bandwidth, though the server may still do the work.
  2. Guard with a token. Keep a counter or the latest query. When a response arrives, compare it with the latest, and drop it if it is old. This protects code paths where abort is not available, for example a library call.
  3. Debounce the input, so that fewer requests are sent while the user is typing. This reduces load but does not remove the race, because two requests can still overlap.
  4. Ignore results after unmount. A component that is gone must not set state. Aborting in the cleanup of an effect does both.
  5. Show loading and error states per latest query only, so that an old failure does not replace a new success.

Libraries such as TanStack Query and SWR handle keys, cancellation and caching, but the idea is the same, and an interviewer expects you to explain it.

The script simulates a search with different delays per query. The first version applies every response and ends with the result for "r". The second aborts the earlier calls and guards with an id, and shows only the latest. fetch with a real URL works the same way, because the signal is passed in the options.

javascript
const delays = { r: 90, re: 10, rea: 50 };
function search(query, signal) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve('results for ' + query), delays[query]);
    signal?.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
    });
  });
}

// Version 1: every response is applied when it arrives.
let shown = '';
const naive = (q) => search(q).then((r) => { shown = r; });
await Promise.all(['r', 're', 'rea'].map(naive));
console.log('naive shows:', shown);

// Version 2: abort the old request and ignore old responses.
let controller, latest = 0, fixed = '';
async function onInput(q) {
  controller?.abort();
  controller = new AbortController();
  const id = ++latest;
  try {
    const r = await search(q, controller.signal);
    if (id === latest) fixed = r;
  } catch (e) {
    if (e.name !== 'AbortError') throw e;
  }
}
await Promise.all(['r', 're', 'rea'].map(onInput));
console.log('fixed shows:', fixed);

Run with Node 24.22.1. The output matched the text in the answer in two runs.

Key points

  • Responses can arrive out of order, so late old responses overwrite new ones.
  • Abort the previous request with AbortController, and treat AbortError as normal.
  • Also compare with the latest query id as a guard.
  • Debounce reduces load but does not remove the race.
  • Cancel in cleanup when the component goes away.

Common mistakes

  • Debouncing and thinking the race is solved.
  • Treating AbortError as a user-facing error.
  • Testing only on a fast local server where order is stable.
  • Letting an old failure replace a newer success.

Follow-ups

  • How would you test this race in a unit test?
  • What does abort do to a request that has already reached the server?
  • How do query libraries avoid the problem?

Tips

  • Explain the failure with a concrete order of responses.
  • Give abort and guard together as the answer.