System design case study C16 · Search · Caching

Design Search Autocomplete (Typeahead)

Suggest the top completions for every keystroke in under 50 ms. The trick is to do almost all the work before anyone types.

What you'll be able to explain
  • Store prefixes in a trie with precomputed top-K suggestions
  • Build the index offline from query logs
  • Serve from memory with sharding and caching
  • Handle trending queries, personalisation and filtering
  • Reduce request volume from clients

Scope

Functional

  • As the user types, return the top 10 suggestions for the current prefix.
  • Ranked by popularity (and freshness); filtered for offensive content; multiple languages (incl. transliterated Hindi, "Hinglish").

Non-functional

  • p99 < 50 ms server time. Highly available (degrade to no suggestions, never to errors).
  • Suggestions reflect trends within ~15 minutes.

Size

  • 100M searches/day, average 8 keystrokes → 800M suggestion requests/day ≈ 10k/s, peak ~30k/s (less with client debouncing).
  • Unique queries: ~100M; the useful head is ~10M queries.

The data structure

A trie maps prefixes to nodes; each node stores the precomputed top-K completions beneath it, so a lookup is just "walk the prefix, return the stored list". No subtree traversal at query time.

EXTERNALrootSERVICEbOKbatop: bank, bangalore…SERVICEbetop: best, bengaluru…SERVICEbantop: bank, bangalore…SERVICEbattop: batman…
A trie with top-K lists cached at each node. "ba" answers instantly from its stored list.

Space-saving variants: compressed tries (radix trees), or FSTs (finite state transducers, used by Lucene) which are very compact. A simpler practical option: a key-value map from every prefix (up to ~20 chars) → top-K list, which shards trivially.

The architecture

CLIENTBrowser / appdebounce 150 msNETWORKCDNpopular prefixesSERVICESuggest servicein-memory indexQUEUE / LOGSearch logsKafkaWORKERBatch builderdailyWORKERTrending job15-min windowsOBJECT STOREIndex snapshotsmissqueriesdeltaload
Offline build from logs, online serving from memory, plus a fast trending path.

The 30-second summary

Say it in the interview

"Suggestions come from an in-memory prefix index where each prefix stores its precomputed top-K, built offline from time-decayed query logs with safety filtering, plus a trending delta from a 15-minute streaming job. Short prefixes are cached at the CDN, clients debounce and filter locally, and personal history is blended in at request time."

Follow-up questions the interviewer may ask

  1. How fast must suggestions be?
  2. How do trending queries appear quickly?
  3. How do you personalise?
  4. How do you filter offensive suggestions?

Model answers to each of these are in the book.