← All posts

Josh Davies

The Last Response Isn't the Latest One

Fire two requests and the network gets to pick which one finishes first. Search boxes, filters, and webhooks all break the same way. Cancel what you can, ignore what's stale, and let newer data win on purpose.

  • typescript
  • react
  • laravel
  • webhooks
  • debugging

Somebody types "lar" into your search box. Then "laravel". Two requests go out.

The "laravel" results come back first and render. Great. Then the "lar" request finally finishes and paints right over them.

Now the input says "laravel" and the list underneath is for "lar". Nobody can reproduce it on localhost, because on localhost everything comes back in a couple of milliseconds and in order.

The network never promised you order

Sending requests in order doesn't mean they finish in order. A broader query can match more rows. One request hits a cold cache and the other doesn't. They land on different servers. Somebody's phone switches from Wi-Fi to cellular halfway through.

Any of those, and the older request finishes last.

Most fetch code has a quiet assumption baked in: whatever came back most recently is the newest answer. That's true right up until it isn't.

Cancel the one you don't care about anymore

If a newer request makes the old one pointless, cancel the old one. In React, the effect cleanup is exactly where that belongs:

useEffect(() => {
  if (!query) {
    setResults([]);
    return;
  }
 
  const controller = new AbortController();
 
  fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
    .then((res) => res.json())
    .then((data: SearchResult[]) => setResults(data))
    .catch((err) => {
      if (err.name !== "AbortError") setError(err);
    });
 
  return () => controller.abort();
}, [query]);

Every time query changes, React runs the cleanup for the previous effect, which aborts the previous request. The aborted fetch rejects with an AbortError, and we drop it on the floor instead of showing the user an error for something they didn't ask about anymore.

Bonus: the browser stops waiting on a response nobody wants.

Aborting isn't the whole fix

Two caveats.

First, aborting stops the browser from waiting. It doesn't reach into your server and stop the query. The backend still does the work. That's fine, just don't confuse "cancelled" with "never happened", especially for anything that writes.

Second, not everything you await takes a signal. If there's a parse step, a second call, or some other async work between the response and setState, the abort can miss. So also make stale results harmless:

let latest = 0;
 
async function search(query: string) {
  const id = ++latest;
 
  const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
  const data: SearchResult[] = await res.json();
 
  if (id !== latest) return; // someone newer already asked
 
  renderResults(data);
}

A counter. That's it. Whatever comes back, only the answer to the most recent question gets rendered. In React, the same idea is the let ignore = false flag you flip in the cleanup, which is the pattern the React docs show for fetching in an effect.

Debounce helps. It doesn't fix it.

Debouncing the input to a few hundred milliseconds cuts down how many requests go out. Do it. Your API will thank you.

But a debounce only shrinks the window. Two requests can still be in flight at the same time, and the slow one can still land second. You still need cancel or ignore.

Let the library do the bookkeeping

If you're already using TanStack Query, this is mostly handled. Results get stored under their query key, so a late "lar" response goes to the "lar" entry and doesn't overwrite what you're showing for "laravel". It also hands your query function a signal:

const { data } = useQuery({
  queryKey: ["search", query],
  queryFn: ({ signal }) =>
    fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal }).then((res) => res.json()),
  enabled: query.length > 0,
});

Pass that signal through and stale requests can actually be cancelled instead of just ignored.

The bug doesn't care that it's a search box, either. Filter dropdowns, tabs that load data, "next page" buttons, a form that autosaves on every keystroke. Anywhere a user can trigger a second request before the first one finishes, the first one can win.

Your backend has the same bug

Webhooks are requests you didn't send, arriving in whatever order the other side's retry logic and network decide. Stripe's docs say outright that events aren't guaranteed to arrive in the order they were generated. Assume every other provider is the same until they promise otherwise.

So a subscription.updated from ten minutes ago can show up after the one from two minutes ago. If your handler blindly copies the payload onto the row, you just rolled your customer back in time.

Same fix as the search box. Only apply data that's newer than what you already have:

$object = $event['data']['object'];
$occurredAt = Carbon::createFromTimestamp($event['created']);
 
$updated = Subscription::where('provider_id', $object['id'])
    ->where(function ($q) use ($occurredAt) {
        $q->whereNull('provider_updated_at')
          ->orWhere('provider_updated_at', '<', $occurredAt);
    })
    ->update([
        'status' => $object['status'],
        'provider_updated_at' => $occurredAt,
    ]);
 
if ($updated === 0) {
    Log::info('Skipped stale webhook', ['event_id' => $event['id']]);
}

The "is this newer?" check lives in the WHERE clause, so two webhooks racing each other can't both read the old timestamp and both decide they win. The database settles it.

A couple of honest caveats. Timestamps in whole seconds can tie, so if the provider gives you a real version number or sequence, use that instead. And some integrations are simpler if you treat the webhook as a nudge: "something changed on subscription X", then fetch the current object from their API and save that. Current state can't be out of order.

Queued jobs get this too. Run more than one worker and two jobs for the same record can finish in either order. The same newer-wins check works there.

The habit

Any time you write code that fires a request and then updates something with the answer, ask one question: what happens if an older answer shows up after a newer one?

On the frontend, cancel what you can and ignore what's stale. On the backend, keep a timestamp or version and let the database refuse anything older.

The network was never going to keep your requests in line. That part's on you.