SEARCH AUTOCOMPLETE

Top suggestions in under 50 ms, while the trends change

L318 MINSYSTEM DESIGN
PREDICT

Suggestions come from a trie of past queries. The simple lookup walks to the node for the typed prefix, then scans every term below it to find the best five. A user types 't', then 'ta', then 'tap'. Which keystroke costs the most?

Autocomplete is a trie of past queries, each with a popularity score. The naive lookup walks to the prefix node and then visits its whole subtree to find the best k. That cost grows with the dictionary, and it is worst on one-letter prefixes. The standard design caches the top k in every node, so a keystroke costs the prefix length and nothing else. The price is freshness: cached lists only change when someone updates them. A periodic rebuild leaves a trending term invisible for up to an hour. An incremental update along the term’s path, or a small trending list merged at query time, closes that gap.

▶ SIMULATION
SEARCH BOX
prefix —
—
TRIE (scan subtree per keystroke)
terms 4,000 · nodes 18,097
last query visited — nodes
pending updates 0
SERVERS (8 cores)
mix mean service — · utilisation —
p99 — / 50 ms
—
clock0:00
load model2,000 keystrokes/s over 8 cores, 2 µs per node; mix "t", "ta", "tap" in equal parts; p99 = ln(100) / (μ − λ) per core
✓ p99 <= 50 ms at 2,000 keystrokes/s✓ a trending term appears for its prefix within 60 s
SCHEDULE
01[SERVER]serve: walk to the prefix, scan its subtree, sort, take 5
02[USER 1]user 1 types "t"
03[USER 1]user 1 types "ta"
04[USER 1]user 1 types "tap"
05[TREND]"tapioca tea" goes viral: 90,000 searches in 2 min
06[CLOCK]five minutes pass (next hourly rebuild is at 60 min)
07[USER 2]user 2 types "t"
08[USER 2]user 2 types "ta"
09[USER 2]user 2 types "tap"
10[CLOCK]report
Start of scan the subtree scenario. 10 steps.
// build (offline, from the query log):
for each node, bottom-up: node.top = best K of (node.term, children's top lists)

// serve: O(prefix length), independent of dictionary size
suggest(prefix):
  n = root; for ch in prefix: n = n.children[ch] or return []
  return n.top                                  // precomputed, no subtree walk

// freshness: a new score for term T
update(T, score):                               // O(|T| · K), for a rising score
  for each node on the path root → T:
    put (T, score) into node.top, keep the best K
// a falling score can drop T out of a node's top K, and the term that should
// replace it is not in the cached list: keep K + slack per node, or rebuild
// (or: serve a small "trending" list next to the trie and merge it in)

All three designs see the same keystrokes and the same viral term. At the default 4,000 terms the scan is fast enough; drag DICTIONARY up and watch its p99 climb to the knee of the queueing curve. The p99 assumes the fleet serves one-, two- and three-letter prefixes in equal parts, like these two users. CACHED TOP-K stays at microseconds at any size, but the freshness invariant turns red: “tapioca tea” is five minutes old and still absent, waiting in the pending log for the hourly rebuild. The FIX pays a 12-node update when the term trends and keeps both invariants green.

BREAK IT NOT YET

Scanning the subtree is fine on a small dictionary. Grow DICTIONARY until the scan blows the 50 ms p99 budget at 2,000 keystrokes per second.

GOAL: the scan design breaks p99 <= 50 ms

FIX IT NOT YET

Return the top k suggestions for prefix without walking the subtree: every node carries top, its subtree's best 10 terms from the last rebuild. Merge in trending, the terms scored since that rebuild, so a hot term shows up now (a fresher score for the same term wins). The grader counts node visits.

Mental model:

Move the work from read time to write time: reads happen on every keystroke, writes happen when scores change, so precompute the answer in every node. Then own the consequence. A precomputed answer is a cache, and every cache has a staleness budget. Pay for freshness on the write path too, with an incremental update (cheap for rising scores; falling ones need slack or a rebuild) or a small fast-path list, rather than going back to scanning on reads.

IN PRODUCTION

Search boxes, address and product lookups, command palettes, tag pickers. Backed by tries or FSTs (Lucene's completion suggester, Elasticsearch search_as_you_type), Redis sorted sets per prefix, or a dedicated typeahead service fed by a query-log pipeline.

IN INTERVIEWS

“Design search autocomplete.” Start with requirements: top 5 suggestions, under 50 ms p99, per keystroke, so the read rate is several times the search rate. Draw a trie, show why scanning the subtree is too slow on short prefixes, and cache top-k per node. Then cover the data path: query logs aggregated by a stream or batch job into scores, a periodic rebuild, and the staleness that creates. Fix trending with incremental path updates or a fast-path trending list merged at read time. Mention sharding by prefix, replicas for read load, client-side debouncing and caching of short prefixes, and filtering of offensive terms.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: PAYMENT LEDGER →