Debounce search race condition: stop stale results

A debounce search race condition survives debouncing: a slow old response can still overwrite a new one. How I let only the newest request write results.

By

Debouncing a search box feels like the whole fix, and it solves half the problem. It cuts the number of requests, but a debounce search race condition is still there: a slow response from an earlier query can land after a fast response from a later one and overwrite it. The user typed the right thing and sees results for something else. I fixed this on the admin image search of a photo marketplace, and the same bug turned up twice in a fitness app in forms that have nothing to do with typing. This post covers the rule behind all three: a response may only write to the screen if it still owns that screen.

Why debouncing leaves the race in place

Before the fix, the admin search fired on every letter. Debouncing was the obvious first step, so search now fires 300ms after typing stops.

Here is what 300ms does not cover. Someone types "cat", pauses long enough for the request to go, then types "cats". Two requests are now in the air:

  1. The request for "cat" leaves first and hits a slow path on the server.
  2. The request for "cats" leaves later and returns quickly. The list shows results for "cats".
  3. The response for "cat" finally arrives and writes over the list.

The search box says "cats" and the results are for "cat". Nothing errored, so nothing gets logged. A debounce controls when requests start. Nothing about it controls the order in which they finish, and that order belongs to the network and the server.

How do you stop a stale response overwriting newer results?

Give every request an owner and check ownership after the await, right before writing state. A counter is enough: each load takes the next number, and only the holder of the latest number may write. Anything older is dropped when it arrives. Debouncing stays, because it saves requests, and this guard is what makes the result correct.

Fixing the debounce search race condition in React

The admin search needed two small pieces: a draft value for the input, so typing doesn't trigger a search directly, and a counter in a ref. With names simplified and the page state left out:

const [draft, setDraft] = useState("");
const [query, setQuery] = useState("");
const latest = useRef(0);

useEffect(() => {
  const next = draft.trim();
  if (next === query) return;
  const timer = setTimeout(() => setQuery(next), 300);
  return () => clearTimeout(timer);
}, [draft, query]);

const load = useCallback(async () => {
  const mine = ++latest.current;
  setLoading(true);
  try {
    const res = await fetch(`/api/images?q=${encodeURIComponent(query)}`);
    const data = await res.json();
    if (mine !== latest.current) return;
    setImages(data);
  } catch {
    if (mine === latest.current) setImages([]);
  } finally {
    if (mine === latest.current) setLoading(false);
  }
}, [query]);

useEffect(() => {
  load();
}, [load]);

Three things are doing work here.

clearTimeout is the debounce. A new keystroke cancels the pending timer, so query only changes once typing has stopped for 300ms.

mine is the ownership. Each load takes a number when it starts and compares it after the await. If a newer load has started since, this one returns without touching the list.

Every exit checks it. The easy mistake is guarding only the success path. An old request that fails would clear a list the newest request just filled, and an old request that finishes would switch off the spinner while the newest is still running, so the list looks final when it isn't.

The React useEffect docs show the same idea with an ignore flag set during cleanup, and say plainly that "network responses may arrive in a different order than you sent them". A data-fetching library that keys its cache by query handles most of this for you, and it's worth knowing what it's protecting you from.

You can also cancel the old request with an AbortController, which stops the browser waiting on a response nobody wants. Your server may still finish the work, and an aborted fetch throws, so the catch has to tell an abort from a real failure. I'd treat that as saving bandwidth on top of the guard, because the guard is what protects your state.

The same bug with no search box: a screen that went away

The next version of this bug had no typing in it. In a fitness app, every post screen in the community feature shows one shared post and its comments. Opening a post from a push notification used to stack a second post screen on top of the first, which caused its own problems, so a post opened from a push now replaces the post screen on top.

Replacing a screen creates the same race. The old screen may still have requests in flight when the new one takes over, and they write to the same shared state. A late response for the old post would land on the post that replaced it.

The fix was to tie the requests to the screen's life: a post screen that goes away cancels its in-flight requests. It's the ownership rule again, tied to a lifecycle this time. Whatever starts work should be the thing that ends it, and the moment to do that is when its owner disappears.

My default now is to ask one question whenever two screens or two requests can write to the same state: what happens if the older one finishes last?

Each load belongs to the list it started on

The third version was in that app's Following and Followers lists. A page could still be in flight when the list was cleared, and it then landed in the new list, mixing old rows into fresh ones.

There's no newer request to compare against here, since the thing that changed was the list. So the load holds on to the list it started on and checks that it's still the current one. A load that finishes after its list has gone writes nothing:

class UserLists extends ChangeNotifier {
  PagedList _current = PagedList();

  void clear() {
    _current = PagedList();
    notifyListeners();
  }

  Future<void> loadNextPage() async {
    final list = _current;
    final page = list.currentPage + 1;
    final rows = await api.fetchPage(page);
    if (!identical(list, _current)) return;
    list.items.addAll(rows);
    list.currentPage = page;
    notifyListeners();
  }
}

Names are changed and the class is trimmed to the guard. Clearing swaps in a new list object, so the old object itself is the ownership token, and identical is the whole check. At a much larger scale, the same instinct is behind keying a ProviderScope with an epoch to throw away every provider on logout.

How to test for it

This bug stays hidden on a fast local API, because responses come back in order. My default is to make the order explicit:

  • In a unit test, replace the fetch with promises you resolve by hand. Start the old request, start the new one, resolve the new one, then resolve the old one, and assert that the new results are still there.
  • In the browser, add an artificial delay on the server for one query, or throttle the network, and type through it.
  • In a mobile app, delay a response and navigate away or clear the list during that delay.

Any async write has this gap between starting and finishing. Database writes have their version of it, where two requests both check for a row and both insert, and the answer there is a constraint, as I showed in fixing race condition duplicates with a unique index. Long-lived responses need an abort path too, which comes up in streaming LLM responses with Server-Sent Events.

The short version

Debouncing decides when a request starts, and it has no say in when the response arrives. Keep it for the saved requests, and add ownership for correctness: only the newest request writes, a screen that goes away cancels what it started, and a load only writes to the list it began on. Then test the bad order on purpose by resolving the old response last.

More of my frontend and mobile work is on the projects page.

Want this kind of work on your product?

Get in touch