🔄 The Newest Request Isn’t Always the One That Finishes Last
A user types quickly into a live-search box, firing off a request on every keystroke. The requests don’t always come back in the order they were sent – and when an older, slower response arrives AFTER a newer, faster one, it silently overwrites the correct, up-to-date results with stale ones.
🐞 The Problem
searchInput.addEventListener('input', () => {
fetch(`/api/search?q=${searchInput.value}`)
.then(res => res.json())
.then(results => renderResults(results));
// Whichever request happens to FINISH last wins,
// regardless of which one was actually sent last.
});
🔍 Why This Happens
Each keystroke fires an independent network request, and network timing is not guaranteed to preserve send order - a request for "ca" might take longer than a later request for "cat" if the server load or network conditions vary even slightly between them. Whichever .then() callback happens to run LAST simply overwrites the DOM with whatever it has, with no awareness of whether a newer request is still in flight or already finished first.
✅ The Fix: Track and Ignore Stale Responses
- Tag each request with an incrementing counter (or the query itself) before sending it, and when a response comes back, only render it if it matches the MOST RECENT request sent — discard anything older.
- Where supported, use
AbortControllerto actively cancel the previous in-flight request the moment a new one starts, so a stale response never even has the chance to arrive and race. - Add a short debounce (150-300ms) on the input event itself so a fast typist doesn’t fire a request per keystroke in the first place — this reduces how often the race condition can even occur.
📦 Correct Version (Request Tracking)
let currentRequestId = 0;
searchInput.addEventListener('input', () => {
const thisRequestId = ++currentRequestId;
fetch(`/api/search?q=${searchInput.value}`)
.then(res => res.json())
.then(results => {
if (thisRequestId === currentRequestId) {
renderResults(results); // only render the LATEST request
}
// otherwise: a newer request has since been sent, discard this
});
});
The bug was never about a slow response — it was about trusting arrival order to match send order, which the network never actually promised.
