Skip to content

    Frontend System Design

    Front-End Case Study: Search Autocomplete

    Design a search autocomplete box end to end: debounce, cancellation, a stale-answer guard, ranking, an accessible combobox, and a lab with tests.

    By Published 21 min read

    • frontend-system-design
    • case-study
    • autocomplete
    • combobox
    • accessibility
    Share

    What you'll learn: By the end of this case you will be able to design the front end of a search box that suggests items as the user types: the pipeline from keystroke to list (pause, cancel, ignore stale answers, reuse earlier answers, rank), the state it needs, the keyboard and screen-reader behaviour of an ARIA combobox, the failures that matter, and the trade-offs between the choices. You will also build the whole thing as a pure TypeScript core with a thin React layer, and test it with a deterministic fake backend and a virtual clock.

    A shop assistant who finishes your sentences is helpful until you change your mind halfway. Imagine one who hands you cards while you are still speaking: you say "ba", she hands over cards about bacon and bagels; you continue "bana", and she must take the old cards back and hand over bananas. If she is slow, a card for "ba" can arrive after you have said "bana", and a careless assistant puts it on top. The box on a web page has the same job and the same risk. Most of this case is about the second half of that sentence: not the cards, but handling the ones that arrive late or wrong.

    Frame. This is an educational reference design for a generic online store's search box, in the format described in the case study method lesson. No company is named and nothing here describes a real system. Every number is illustrative (chosen to make the example concrete, to be replaced by your own measurements) unless it comes from a source that is linked. The running product is a store header search: the shopper types, up to six suggestions appear under the input, and picking one fills the box. Pressing Enter with nothing highlighted submits what was typed.

    The core idea

    Three statements carry the design.

    1. A suggestion box is a pipeline from keystrokes to a list. Keystroke, pause, request, answer, ranking, popup. Every stage exists to remove either wasted work (fewer requests, no duplicate answers) or wrong output (an answer for text the user has already replaced).
    2. An answer belongs to a query, not to the box. The state must say which text the visible options are for. Most bugs in this feature come from treating "the latest answer to arrive" as "the right answer".
    3. The input is a text field first. If suggestions are slow, wrong or broken, typing and pressing Enter must still work. The suggestions are an enhancement of a field that already does its job.

    Requirements and targets

    Requirements. The shopper can type, see suggestions, move through them with the keyboard, pick one with the keyboard or the pointer, dismiss them, and submit free text. The box works with a screen reader, does not slow typing, and survives a failed or slow request. Out of scope: spelling correction, personalisation, voice input, and the design of the server's index and ranking, which belong to the back-end search autocomplete case (named here in plain text, not linked).

    Targets (all illustrative):

    Target Value Why it is a target
    Quiet period before a request 150 ms Fewer requests, at the cost of a delay
    Options shown at most 6 Short list, no scrolling
    Shortest text that searches 1 character Simple rule, more requests
    Answers shown for old text never A correctness rule, not a number
    Requests for text already answered none A cache rule

    Architecture

    Figure 1. The browser side of the search box

    The search box view talks to a store that pauses, cancels, caches and ranks before asking an HTTP endpointShopper to Thin view (keys); Thin view to Search store (events); Search store to Thin view (state); Search store to Answer cache (lookup); Search store to HTTP cache (request); HTTP cache to Suggest endpoint (miss)OUR FRONT ENDShopper: types, presses keysShoppertypes, presseskeysThin view: input and listboxThin viewinput and listboxSearch store: pause, cancel, rankSearch storepause, cancel,rankAnswer cache: by normalised queryAnswer cacheby normalisedqueryHTTP cache: browser, CDNHTTP cachebrowser, CDNSuggest endpoint: another teamSuggestendpointanother teamkeyseventsstatelookuprequestmiss

    How to read this: keys reach a thin view, which forwards events to the store. The store answers from its own cache when it can, and otherwise sends a request that may be served by an HTTP cache before it reaches the endpoint. State flows back to the view, which only renders it.

    The store is plain TypeScript with no DOM. The view is a few dozen lines of React that read the store's state with useSyncExternalStore and pass DOM events back. React's documentation describes that hook as a way to subscribe to state that lives outside React, and it requires getSnapshot to return the same value until the data changes: returning a new object on every call causes an infinite loop. The store therefore replaces its state object only when something changes.

    Data and state

    Data Owner Freshness Lives in
    Typed text The shopper Live The store (inputValue)
    Options, with tier and highlight The endpoint, ranked locally Seconds old is fine The store (options)
    The query the options belong to The store Changes with each answer The store (query)
    Which option is highlighted The shopper's keys Live The store (activeIndex)
    Popup open or closed The store Live The store (open)
    Text for the status message The store Changes with the list The store (message)
    Earlier answers The endpoint For this page visit The store's cache, keyed by query

    The status field names where the pipeline is: idle, waiting (the pause is running), loading (a request is out), ready, empty, or error.

    Figure 2. States of the suggestion pipeline

    stateDiagram-v2 accTitle: States of the suggestion pipeline accDescr: Idle moves to waiting when text is typed. Waiting moves to loading when the pause ends, or straight to ready when an earlier answer is reused. Loading moves to ready, empty or error. Typing again from any state returns to waiting, and clearing the text returns to idle. [*] --> idle idle --> waiting: text typed waiting --> loading: pause ends waiting --> ready: earlier answer reused loading --> ready: answer with items loading --> empty: answer with no items loading --> error: request fails ready --> waiting: text typed empty --> waiting: text typed error --> waiting: text typed ready --> idle: text cleared waiting --> idle: text cleared loading --> idle: text cleared

    How to read this: every state returns to waiting when the shopper types again, and clearing the box returns to idle. An error is never a dead end: the next keystroke starts the pipeline again.

    The pipeline, stage by stage

    Illustration 1, the minimal example: a box that sends every keystroke

    The smallest version is the one most tutorials show: on every change, call the endpoint and show whatever comes back.

    input.addEventListener("input", async () => {
      const response = await fetch(`/suggest?q=${encodeURIComponent(input.value)}`);
      render(await response.json());
    });

    It has three problems. It sends one request per keystroke, including keystrokes that are replaced a moment later. Answers can arrive in a different order from the requests, so render may run for old text after new text. And MDN says a fetch() promise does not reject when the server answers with a status such as 404 or 504, so a failed request is parsed as if it were suggestions. The rest of this case fixes these in order.

    Pause before asking

    A debounce waits for a quiet period after the last keystroke and then runs once. The Debouncing and Throttling lesson covers the mechanics; this case uses the trailing-edge form with a 150 ms pause (illustrative). The pause is a trade: it removes requests for text the shopper is about to replace, and it adds the same delay to every suggestion. Two small rules go with it. Text shorter than the minimum never searches, and clearing the box cancels the pause and any request in flight. Enter is the shopper saying "this is what I mean", so in this design it cancels the pause and submits the typed text.

    Cancel what is no longer wanted, and ignore what arrives anyway

    When a new request starts, the store aborts the previous one. MDN says AbortController.abort() is able to abort fetch requests, the consumption of response bodies and streams, and that an aborted fetch() rejects with an AbortError DOMException. If you call abort() without an argument, AbortSignal.reason defaults to an AbortError DOMException. The store passes its own reason, so a log can say why.

    Aborting is a courtesy to the network and the server, and it is not a correctness guarantee. A server or a layer in between may ignore the abort, and an answer can already be on its way. So the store also keeps a single number, the id of the one request whose answer may still be shown, and drops any answer for another id. Here is the core of it, shortened from the lab:

    function fire(q: string): void {
      const id = ++nextId;
      if (inFlight) inFlight.controller.abort(new DOMException("superseded", "AbortError"));
      const controller = new AbortController();
      inFlight = { id, query: q, controller };
      acceptId = id;                       // only this request may be shown
      suggest(q, controller.signal).then(
        (response) => {
          if (id !== acceptId) return;     // stale: not the newest request
          cache.set(q, response);
          show(q, response.items, "network");
        },
        () => {
          if (controller.signal.aborted || id !== acceptId) return; // we gave up on it ourselves
          /* show the error state */
        },
      );
    }

    Figure 3. A slow answer for old text arrives late

    sequenceDiagram accTitle: A slow answer for old text arrives late accDescr: The shopper types ba and the pause ends, so request 1 starts and is slow. The shopper types bana. When that pause ends, request 1 is aborted and request 2 starts and is answered. If the server ignored the abort, the answer to request 1 arrives later and is dropped because it is not the accepted request. participant U as Shopper participant S as Store participant A as Endpoint U->>S: type "ba" S->>A: request 1 "ba" (after the pause) U->>S: type "bana" S->>A: abort request 1 S->>A: request 2 "bana" (after the pause) A-->>S: answer 2 (shown) A-->>S: answer 1 (only if abort was ignored) Note over S: id 1 is not the accepted id, so answer 1 is dropped

    How to read this: the store never shows an answer unless it belongs to the newest request. The abort saves work; the id check is what makes the screen correct.

    The lab runs these two cases on a virtual clock. In the first the endpoint honours the abort; in the second it ignores it. This is the first block of the lab's output:

    Expected output, captured from a real run (the endpoint honours the abort):

    == debounce, abort, and a server that honours the abort ==
    t=   0  type    "b"
    t= 100  type    "ba"
    t= 250  request #1 "ba"
    t= 450  type    "bana"
    t= 600  abort   #1 "ba"
    t= 600  request #2 "bana"
    t= 660  show    #2 "bana" (3 items)
    t=1000  status=ready query="bana" options=[Banana, Banana bread, Banana chips]
    requests started: 2, aborted: 1

    Reading it: the keystrokes at 0 ms and 100 ms produce one request at 250 ms (100 ms plus the 150 ms pause), for "ba". The shopper types "bana" at 450 ms, and its pause ends at 600 ms, when the store aborts request 1 and starts request 2. Only the "bana" answer is ever shown. Times are virtual milliseconds and the latencies are chosen by the lab (illustrative).

    Expected output, captured from a real run (the endpoint ignores the abort):

    == same keystrokes, server ignores the abort (the stale guard drops the late answer) ==
    t=   0  type    "b"
    t= 100  type    "ba"
    t= 250  request #1 "ba"
    t= 450  type    "bana"
    t= 600  abort   #1 "ba"
    t= 600  request #2 "bana"
    t= 660  show    #2 "bana" (3 items)
    t= 850  drop    #1 "ba" (stale answer ignored)
    t=1000  status=ready query="bana" options=[Banana, Banana bread, Banana chips]
    requests started: 2, aborted: 0

    The late answer arrives at 850 ms and is dropped. "aborted: 0" is the endpoint's own count: it never noticed the abort, yet the screen is right.

    Reuse what you already know

    A second request for text the shopper already searched is wasted. The store keeps answers by normalised query (folded to lower case, trimmed). It also does something less obvious: when the shopper extends text that has a complete answer, it filters that answer locally instead of asking again.

    This is safe only because of two properties. The matching rule is monotonic: whatever matches "bana" also matches "ban", so the matches for a longer query are a subset of the matches for a shorter one. And the cached answer is complete: the endpoint reports hasMore as false, meaning it did not cut the list short. A truncated answer cannot be filtered, because the item the shopper wants may be one the server left out. While a request is pending, the store keeps only those previously shown options that still match the new text, so the popup never shows an option that contradicts the input.

    Expected output, captured from a real run (cache and local refinement):

    == cache and local refinement ==
    t=   0  type    "ban"
    t= 150  request #1 "ban"
    t= 210  show    #1 "ban" (3 items)
    t= 300  type    "bana"
    t= 300  local   "bana" from refined (3 items, no request)
    t= 600  type    "banana b"
    t= 600  local   "banana b" from refined (1 item, no request)
    t= 900  type    "ban"
    t= 900  local   "ban" from cache (3 items, no request)
    t=1200  type    "ba"
    t=1350  request #2 "ba"
    t=1410  show    #2 "ba" (8 items)
    t=1500  type    "bag"
    t=1650  request #3 "bag"
    t=1710  show    #3 "bag" (3 items)
    requests sent: "ban", "ba", "bag"
    "ba" was a truncated answer (hasMore), so "bag" needed its own request.

    Three requests served six keystrokes. "bana" and "banana b" were answered from the complete answer for "ban" with no wait at all, going back to "ban" came from the cache, and "bag" needed a request because the answer for "ba" held 8 of the matching items and said it had more.

    Two caches, two jobs. The store's cache lasts for the page visit. The HTTP layer is separate, and the endpoint's response headers decide it. MDN defines Cache-Control: max-age=N as keeping a response fresh until N seconds after it was generated, private as allowing storage only in a private cache such as a browser's, and public as allowing storage in a shared cache. A suggestion response that is the same for everyone can be public and cached at an edge; one that depends on the signed-in shopper must be private. MDN's example of stale-while-revalidate allows a cache to reuse a stale response while it revalidates in the background. The case recommends none of these values; they are the endpoint owner's decision, and the front end's job is to know which kind of response it gets. See HTTP Caching and CDN and Edge Caching.

    Rank what you show

    The endpoint returns candidates, and the client orders them. The lab's rule is: an exact name match first, then names that start with the text, then names where a later word starts with it; inside a tier, higher popularity first, then alphabetical order, so the same input always gives the same list. Popularity numbers in the lab are illustrative.

    Matching is accent-insensitive: the lab folds each character so that "cafe" finds "Café filters". MDN explains why folding is needed: two strings can be canonically equivalent (an "ñ" as one code point, or as "n" plus a combining tilde) and still compare as different, and normalize() with "NFD" or "NFC" produces a form that is the same for all canonically equivalent strings. The lab folds one UTF-16 unit at a time so that an index in the folded text is the same index in the original, which makes the highlight range, the part of the name wrapped in mark, correct.

    Expected output, captured from a real run (ranking, with the highlight in brackets):

    == ranking ==
    query "rice"
      prefix pop=20  [Rice] crackers
      word   pop=65  Basmati [rice]
      word   pop=48  Brown [rice]
      word   pop=15  Wild [rice]
    query "bagel"
      exact  pop=55  [Bagel]
      word   pop=18  Sesame [bagel]
    query "cafe"
      prefix pop=25  [Café] filters

    "Rice crackers" comes first for "rice" although it is less popular, because a name that starts with the text is a closer match than one where a later word starts with it. That is a decision, and a different product might put popularity first.

    The accessible combobox

    An autocomplete box is a combobox. The WAI-ARIA Authoring Practices Guide (APG) defines it as an input widget with an associated popup that lets the user choose a value for the input from a collection. The popup can be a listbox, tree, grid or dialog, and this case uses a listbox.

    Attributes. The input has role combobox. aria-expanded is false when the popup is hidden and true when it is visible. aria-controls refers to the popup, and aria-activedescendant refers to the focused option. The APG list-autocomplete example adds aria-autocomplete="list" and sets aria-selected="true" on the visually focused option, only when it is the one aria-activedescendant names. MDN adds that aria-activedescendant applies to roles such as combobox and textbox, and that the referenced element must be a descendant of the element with focus or owned by it.

    Focus never leaves the input. The APG says DOM focus stays on the combobox while assistive-technology focus moves within the listbox using aria-activedescendant. That is why the box keeps working as a text field: the shopper can keep typing at any moment. It is also why the highlight is a number in the store and not browser focus.

    Keyboard. The list-autocomplete example, with "manual selection" (no suggestion is preselected, and the typed text stays the value if the shopper leaves without choosing), defines these keys, and the lab follows it:

    Key Behaviour in the APG example In the lab
    Down Arrow With the listbox open, moves visual focus to the first suggestion; wraps from the last option to the first Same; if the popup is closed and there are options, it opens
    Up Arrow Moves to the last suggestion; wraps from the first to the last Same
    Alt + Down Arrow Opens the listbox without moving focus or changing selection Same
    Enter In the listbox, sets the textbox to the focused option and closes the listbox Same; with nothing highlighted it submits the typed text (a design choice)
    Escape If the listbox is open, closes it; if it is closed, clears the textbox Same

    The behaviour is a pure function, comboboxKey, that takes the popup state and a key and returns the next state, an effect (select, submit or clear) and whether the browser's default action must be prevented. Down and Up must be prevented, or the text cursor jumps; Enter is prevented only when it selects.

    Figure 4. The popup's states

    stateDiagram-v2 accTitle: States of the combobox popup accDescr: The popup is closed, open with nothing highlighted, or open with one option highlighted. Down arrow opens it and highlights the first option. Alt and down opens it with nothing highlighted. Escape closes it. Enter on a highlighted option chooses it and closes the popup. New options reset the highlight. [*] --> Closed Closed --> OpenNone: Alt+Down, or options arrive Closed --> OpenHighlight: Down or Up OpenNone --> OpenHighlight: Down or Up OpenHighlight --> OpenHighlight: Down or Up (wraps) OpenHighlight --> Closed: Enter chooses OpenHighlight --> Closed: Escape OpenNone --> Closed: Escape OpenHighlight --> OpenNone: new options arrive

    How to read this: the highlight is reset whenever a new list arrives, because the old index would point at a different item. Escape closes before it clears, so one key never does both.

    Expected output, captured from a real run (keyboard and ARIA attributes for the text "rice"):

    == keyboard and ARIA ==
    typed "rice"           text="rice" aria-expanded=true aria-controls=lb status-region="4 suggestions available"
    ArrowDown              text="rice" aria-expanded=true aria-controls=lb aria-activedescendant=opt-0 status-region="4 suggestions available"
    ArrowDown              text="rice" aria-expanded=true aria-controls=lb aria-activedescendant=opt-1 status-region="4 suggestions available"
    ArrowUp                text="rice" aria-expanded=true aria-controls=lb aria-activedescendant=opt-0 status-region="4 suggestions available"
    ArrowUp                text="rice" aria-expanded=true aria-controls=lb aria-activedescendant=opt-3 status-region="4 suggestions available"
    Escape (popup open)    text="rice" aria-expanded=false status-region="4 suggestions available"
    Alt+ArrowDown          text="rice" aria-expanded=true aria-controls=lb status-region="4 suggestions available"
    ArrowDown, Enter       text="Rice crackers" aria-expanded=false status-region=""
    chosen: p21 Rice crackers
    Escape (popup closed)  text="" aria-expanded=false status-region=""

    Note that the text stays "rice" while the highlight moves, that the second ArrowUp wraps to the last option (opt-3), and that aria-controls and aria-activedescendant are present only while the popup is visible.

    Announcing the list. Sighted shoppers see the popup appear; a screen-reader user needs to be told. WCAG 4.1.3 (Status Messages, Level AA) asks that status messages be programmatically determined through a role or properties so assistive technologies can present them without moving focus. W3C's understanding document gives a results count as an example: "18 results returned" and "No results returned" are status messages if they do not take focus, while the result list itself is not. MDN says an element with role="status" is a live region with an implicit aria-live of polite and aria-atomic of true, and that polite changes are spoken when the user is idle. The box therefore renders a visually hidden role="status" element whose text is a count, "4 suggestions available" or "No suggestions", and updates it when the list settles, not on every keystroke.

    MDN's live-region guide says assistive technologies generally announce only dynamic changes, and recommends establishing the live region before updating its content, most reliably by including it in the initial markup. The component therefore renders the status element on the first render and changes only its text. For the focus and keyboard background see Keyboard, Focus and Screen Readers and Accessible Forms and Dynamic Content. What a particular screen reader says in this case was not tested: the lab can assert roles and attributes, not speech.

    Input methods and other edges

    Composition. People typing Chinese, Japanese or Korean use an input method editor (IME) that proposes characters before they are final. MDN says compositionstart fires when a text composition system such as an IME starts a new composition session, and that InputEvent.isComposing reports whether an input event fired after compositionstart and before compositionend. MDN also marks isComposing as having limited availability because it does not work in some widely used browsers. The lab therefore offers two paths: input(value, { composing: true }) records the text without searching, and compositionEnd(value) starts the pipeline. The React layer sets composing from the event when the browser provides it and also listens for compositionend, so it does not depend on isComposing alone. The core path is tested with direct calls (text typed while composing starts no request until compositionEnd); the React wiring of these events was not tested, and no real IME was used.

    Focus. If the box loses focus while a request is out, the answer must not reopen the popup. The store tracks focus and opens the popup only while the input is focused.

    Unmounting. A component that goes away must leave no timer and no request that can land. React's Strict Mode in development runs effect cleanups once on purpose, so the cleanup calls cancelPending(), which stops the timer and abandons any request but leaves the store usable.

    Delivery and performance

    The search box should work before any script runs: a plain GET form to the results page, with suggestions added on top. The enhancement code is small and can load after the page is interactive. The popup holds at most six rows, so no list virtualisation is needed; see List Virtualization for when that changes. Filtering a handful of items on the main thread is cheap, and the work that matters for responsiveness is keeping each keystroke's handler short; see The Event Loop and the Main Thread, INP and Responsiveness and Performance Budgets and Profiling. The case sets no byte or millisecond budget, because any figure would be invented.

    Failure modes

    Failure What the shopper sees Response
    A late answer for old text Nothing wrong Abort plus the accepted-id check
    The endpoint ignores the abort Nothing wrong The id check still drops the answer
    An HTTP error status Nothing, then a message Check Response.ok; show the error state, keep the text
    The request fails or times out "Suggestions are unavailable. Press Enter to search for what you typed." Do not cache the failure; the next keystroke retries
    No matches "No suggestions" announced, popup closed Empty state, not an error
    A truncated answer Fewer options than exist Never filter it locally for longer text
    Too many requests Error responses Backoff and limits; see Client Retries and Backoff
    The box unmounts mid-request Nothing cancelPending on cleanup

    The text a shopper types goes to the endpoint, one partial string at a time. That is a privacy decision to make deliberately: who can see those requests, how long they are kept, and whether a different design (a prefix list shipped to the client) is better for sensitive searches. The lab does not address it.

    Trade-offs

    Decision Choice Cost Revisit when
    Pause before asking 150 ms, trailing edge Every suggestion is that much later Measured latency or the request rate changes
    Abort the old request Yes, and keep the id guard Two mechanisms to maintain Never drop the guard; the abort is optional
    Reuse answers Cache plus refinement of complete answers A wrong rule shows wrong options The matching rule stops being monotonic
    Ranking Client orders, tiers then popularity Client and server can disagree Ranking moves to the server
    Highlight model aria-activedescendant, focus stays Must keep ids and state in step A component library supplies it
    Enter with no highlight Submits the text Differs from the APG example, which only closes the list The results page changes
    Announce Count when the list settles Silent about which items User testing with screen readers

    Build it

    The lab is examples/frontend/labs/autocomplete-combobox: a pure TypeScript core and a thin React component. Time is a virtual clock that moves only when a test says so, and the backend is a deterministic fake with latencies the test chooses. The files are clock.ts, backend.ts (the fake endpoint and a small illustrative catalogue), ranking.ts, combobox.ts, autocomplete.ts (the store) and Autocomplete.tsx (the view).

    cd examples/frontend/labs/autocomplete-combobox
    pnpm test          # 35 tests
    pnpm typecheck
    node src/demo.ts   # prints the blocks shown in this lesson

    The 35 tests passed in the run made for this lesson: 27 in test/core.test.ts (matching and ranking, the fake backend, debounce and cancellation, the cache and refinement, failures, the combobox model, and keyboard through the store) and 8 in test/react.test.tsx. The React tests render into jsdom with Testing Library and check roles and attributes, that DOM focus stays on the input while aria-activedescendant changes, that Enter and click choose an option, that Escape first closes and then clears, that an unmounted box starts no request, and that the box works under Strict Mode. jsdom is a JavaScript model of the DOM, not a browser: no layout, no painting, no real screen reader, no real network, no real IME.

    Break it. In autocomplete.ts, in the success handler of fire, change if (id !== acceptId) { to if (false) {. In the run made for this lesson, the test "drops a stale answer even when the server ignores the abort" failed, and the second demo block showed the late answer for "ba" replacing the answer for "bana". Revert the line. A second experiment: make ArrowDown stop at the last option instead of wrapping, and the wrap test fails.

    The output blocks above are verbatim excerpts of examples/frontend/golden/autocomplete-combobox.txt, captured with node examples/frontend/tools/capture-golden.mjs.

    In practice: a storefront whose suggestions went stale

    The situation

    A storefront team ships a suggestion box in the site header. It works in the office. A week later, support reports that on a slow mobile connection the box sometimes suggests items that do not match what the shopper typed.

    Starting architecture

    • A header input that calls the suggest endpoint on every change.
    • A pause of a few hundred milliseconds, added after launch to cut traffic.
    • Rendering of "the latest response to arrive".
    • No cancellation, no id check, no cache.

    Options considered

    1. Shorten or remove the pause, so answers arrive in step with typing.
    2. Add AbortController cancellation only.
    3. Add cancellation and a guard that shows only the newest request's answer, and track the query each list belongs to.

    The decision

    Option 3. Shortening the pause only hides the race on fast networks. Cancellation alone fails when a request is already past the point of abort or a layer ignores it. The guard is a few lines and makes the rule explicit: an answer is shown only if it is for the newest request.

    Rollout and verification

    The team writes the failing test first: a fake endpoint where the answer for "ba" takes longer than the answer for "bana", and a virtual clock. It watches the old code show "ba" results under "bana", then adds the guard and sees the test pass. It also adds tests for a failed request (the text stays, an error message appears, the next keystroke recovers) and for unmounting during the pause. It ships behind a flag and watches the rate of error responses.

    The 2 a.m. failure

    After a release, an upstream proxy begins to ignore client aborts. Traffic rises because aborted requests now run to completion, and a few answers still arrive late. Because the store drops any answer that is not for the newest request, the screen stays correct and the alert is about request volume, not wrong suggestions. The on-call engineer raises the pause temporarily and opens a ticket with the proxy owner.

    This is a realistic scenario, not a case history.

    The other side of this topic

    The back-end search autocomplete case (named here in plain text) covers what this one assumes: how the endpoint builds and updates its index, how it ranks at scale, and how it caches. The two meet at the contract: what a query is, what hasMore means, how fresh an answer is, and what the endpoint does when the client gives up.

    Architect's notes

    • Keep a correctness mechanism (the id check) separate from an optimisation (the abort). The first must never depend on the second.
    • Track which query an answer belongs to. It makes local reuse possible and stale display impossible.
    • Make the pure core the thing you test; keep the React layer too thin to need much testing.
    • Decide on purpose who may see partial queries, and write the decision down.
    • Treat the keyboard table as a specification and test it as one.

    Common mistakes

    • Showing the latest answer to arrive. Show the answer for the latest request.
    • Filtering a truncated answer. The item the shopper wants may be one the server cut.
    • Moving DOM focus into the list. The shopper can no longer type.
    • Announcing on every keystroke. Announce when the list settles.
    • Not cleaning up. A timer or request that outlives the component updates a component that is gone.
    • Treating fetch() as rejecting on a 500. It does not; check the status.

    Key takeaways

    • A suggestion box is a pipeline; an answer belongs to a query.
    • Pause, cancel, and guard are three different mechanisms; only the guard keeps the screen correct.
    • Reuse answers only when the matching rule is monotonic and the answer is complete.
    • A combobox keeps DOM focus on the input and names the active option with aria-activedescendant; a polite status element announces the count.
    • A virtual clock and a fake backend make timing bugs reproducible in tests.
    • State what the lab cannot show: layout, real screen readers, real IME, real networks.

    Practice exercises

    Exercise 1: Beginner (30 minutes). Run the lab's demo and, for each block, write down which stage of the pipeline produced each line.

    Exercise 2: Intermediate (2 hours). Add a rule that the answer for a query is reused for five virtual seconds only, and write a test that shows the cache expiring.

    Exercise 3: Intermediate (2 hours). Add the Home and End keys as the APG example describes, and a test for each.

    Exercise 4: Advanced (3 hours). Score this case against the ten-part rubric from the case study method lesson, and write the paragraph that would raise its lowest part.

    Official documentation

    In this course

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments