Design Search Autocomplete (Typeahead)
Return the top suggestions for a prefix within ~50 ms for millions of keystrokes per second — tries with precomputed top-K per node, the offline aggregation pipeline for query frequencies, sharding the trie, multi-layer caching (browser, CDN, service), freshness for trending queries, personalisation, and filtering.
1. Requirements
Functional
- As the user types, return the top 5–10 suggestions for the current prefix, ranked by popularity (and optionally freshness, personalisation).
- Filter offensive/blocked terms.
Non-functional
- p99 < 100 ms end-to-end (perceptibly instant), server < 20 ms.
- 10B searches/day, ~4 keystroke requests per search (with debounce).
- Eventual freshness: hours for most, minutes for trending.
2. Estimation
| Quantity | Value |
|---|---|
| Suggestion requests | 10B × 4 / 86,400 ≈ 460k/s avg, ~1M/s peak |
| Unique popular queries kept | ~100M after thresholding |
| Trie size | ~100M queries × ~30 B + top-K pointers → tens of GB (fits in RAM on large servers; shard if needed) |
| Cache hit rate | very high for short prefixes (most traffic) |
3. Data structure: trie with top-K per node
import heapq
class Node:
__slots__ = ("children", "top")
def __init__(self):
self.children, self.top = {}, [] # top: list of (score, query), best first
class Typeahead:
def __init__(self, k=10):
self.root, self.k = Node(), k
def build(self, counts: dict[str, float]):
"""Offline: insert every query, then compute top-K bottom-up."""
for q in counts:
node = self.root
for ch in q:
node = node.children.setdefault(ch, Node())
node.top = [(counts[q], q)] # terminal: itself
def fill(node):
cands = list(node.top)
for child in node.children.values():
cands.extend(fill(child))
node.top = heapq.nlargest(self.k, cands)
return node.top
fill(self.root)
def suggest(self, prefix: str) -> list[str]:
node = self.root
for ch in prefix.lower():
node = node.children.get(ch)
if node is None:
return []
return [q for _, q in node.top]
t = Typeahead(k=3)
t.build({"bitcoin": 900, "bing": 700, "bible": 400, "best buy": 1200, "bbc": 650})
print(t.suggest("bi")) # ['bitcoin', 'bing', 'bible']
print(t.suggest("b")) # ['best buy', 'bitcoin', 'bing']
4. High-level design

5. Deep dives
Ranking score
score = Σ count(window) × decay(age) + boosts (freshness, locale, click-through rate of the suggestion) − penalties (low quality). Use exponential decay so last week matters more than last year.
Sharding
Filtering
Blocklists (hate, adult, legal takedowns) applied at build time and at serve time (so removals take effect instantly without waiting for a rebuild).
Client behaviour
- Debounce 100–150 ms; cancel stale requests (
AbortController); ignore out-of-order responses (only render if response prefix = current input). - Cache prefix results in memory for the session; prefetch next likely prefix.
6. Trade-offs
| Decision | Choice | Alternative |
|---|---|---|
| Structure | trie with top-K per node | Elasticsearch completion suggester |
| Freshness | hourly rebuild + streaming overlay | real-time trie updates (complex locking) |
| Scaling | replicate full trie; range-shard when too big | hash sharding (loses prefix locality) |
| Caching | browser + CDN + service | none (would need 10× servers) |
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.