KatInterview

Autocomplete Input with Hand-Rolled Debounce

System DesignModel answer
MediumModel answerSystem Designreactdebounceasync

Last updated

Build a search input that fetches and displays suggestions as the user types, using a debounce you write yourself and handling stale responses, keyboard navigation, and cleanup.

Autocomplete Input with Hand-Rolled Debounce

You are building a text input that displays a dropdown of suggestions as the user types. Suggestions come from an async lookup function — do not import a debounce utility (lodash, etc.); write that logic yourself.

The lookup function has this shape:

declare function getSuggestions(query: string, signal?: AbortSignal): Promise<string[]>;

The component should:

  • Call getSuggestions only after the user has paused typing for a short delay (debounce), not on every keystroke
  • Show a list of suggestions below the input while results are loading or available
  • Let the user pick a suggestion with the mouse or keyboard
  • Clear the list when the input is emptied
  • Avoid showing results from an earlier query if a newer one finishes first

What to address

  1. Debounce implementation — write a debounce function from scratch and explain how it behaves when the component re-renders
  2. Stale response handling — explain how you prevent an out-of-order response from overwriting fresher results
  3. States — loading, empty results, error, and cleared input
  4. Keyboard navigation — arrow keys to move through the list, Enter to confirm, Escape to dismiss
  5. Accessibility — how a screen reader understands the suggestion list
  6. Cleanup — timers and in-flight requests when the component unmounts
  7. Bonus — caching results for queries already seen, and how you would test timer behaviour without real delays

You may use any framework you are comfortable with, or plain DOM APIs. Explain your choices as you go.

Hints

Hint 1

A debounce function returns a new function that resets a setTimeout each time it is called; only when the timeout fires without being reset does it invoke the original function. Think about where you store that timer ID so it survives re-renders without being recreated every render cycle.

Hint 2

An AbortController lets you cancel a fetch that is already in flight. Create a new one each time a request goes out, and call abort() on the previous one before starting the next. This handles both the stale-response problem and cleanup on unmount with a single mechanism.

Hint 3

The ARIA pattern for a combobox uses role='combobox' on the input with aria-expanded and aria-controls pointing to the listbox, and role='option' on each item. aria-activedescendant tracks the keyboard-focused item without moving real focus away from the input.