Frontend Case Studies

Topic F9

Autocomplete

A trie, top-K and debounce together: suggestions on every keystroke.

9 min · intermediate

Watch: every letter typed moves one step down the tree of letters. Every word below it is a possible suggestion.

listbalibandungbandabatambekasibogor
  • finished / the result
  • no longer used
Step 1 of 5

A list of cities with popularity scores. The simplest way: on each keystroke, check every city to see if it starts with the typed text.

Autocomplete has to answer on every keystroke, so the cost per keystroke is what counts.

In the browser or on the server

  • Small lists (up to thousands): send them all to the browser once, then search there. No network per keystroke, so suggestions appear instantly. For a few thousand items, even a plain filter is fast enough.
  • Large lists (millions of products, addresses): search on the server with a dedicated index, such as a trie or a prefix index in Elasticsearch, Meilisearch or PostgreSQL (LIKE 'ban%' with a B-tree index, or pg_trgm for matching mid-word).
Code, for programmersA search box that's polite to the server
function useSuggestions(text) {
  const q = useDebounced(text.trim().toLowerCase(), 200);    // wait for a pause
  return useQuery({
    queryKey: ["suggest", q],                                // each prefix cached once
    queryFn: ({ signal }) =>                                 // signal cancels stale requests
      fetch(`/api/suggest?q=${encodeURIComponent(q)}`, { signal }).then((r) => r.json()),
    enabled: q.length >= 2,                                  // skip one-letter searches
    staleTime: 5 * 60_000,
  });
}

Details that make it feel right

  • Normalise: lowercase, trim spaces, and fold accents ("é" and "e") in both the data and the input.
  • Ordering: popularity, the user's history, or nearness. Store a top-K at each trie node so you never walk a whole branch.
  • Keyboard and accessibility: up/down arrows, Enter, Escape, and the ARIA combobox pattern (role="combobox", aria-activedescendant).
  • Highlight the matching part of each suggestion, so users see straight away why it appeared.

Quiz

  1. Why does a trie suit autocomplete?

  2. A list of 300 country names. The simplest option that's still fast?

  3. The user typed 'ban' but sees suggestions for 'ba'. The cause?

0 of 3 answered.