#70 Tries/Prefix Indexes
Search Autocomplete
Suggest cities, airports and hotels as the user types, within about 100 ms, ranked by what people actually pick.
What is being asked
Design the search box that suggests "Goa", "Goa International Airport (GOI)" and "Taj Fort Aguada, Goa" after the user types "go". Every keystroke is a request, so this is one of the highest-traffic endpoints on the site.
Requirements
Functional
- Prefix suggestions for places, airports and hotels.
- Tolerate small typos and alternate names ("Bombay" → Mumbai).
- Rank by popularity, personalised slightly by location and history.
Non-functional
- p99 under 100 ms end-to-end.
- Tens of thousands of requests per second at peak.
- Suggestions can be a day stale; popularity changes slowly.
Design
- An offline builder reads the catalogue and click logs, scores every entity, and builds a trie (or a sorted prefix table) where each node stores its top-10 completions.
- The trie is shipped to every autocomplete server and loaded in memory. A lookup is a walk of a few characters, with no database call.
- Short prefixes ("g", "go") have the same answer for everyone, so they are cached at the CDN.
- The client debounces (waits ~100 ms after typing) and cancels stale requests.
Key decisions and trade-offs
- Pre-computed top-K per node makes lookups O(prefix length) at the cost of memory and a rebuild step.
- Personalisation vs caching. Personal results can't be cached at the edge; a common compromise is a global list re-ranked lightly on the client or server.
- Typo tolerance (edit distance, n-grams) increases recall but costs CPU; apply it only when the exact prefix returns few results.
- Daily rebuild + live overrides. A new hotel can be pushed into a small "fresh" index merged at query time.
Follow-up questions
- How do you support Hindi or other scripts?
- How much memory does the trie need for 2 million entities?
- How would you stop offensive or spam suggestions?
- How do you measure whether suggestions are any good?