Lesson 32 of 38Case studies
Design Search Autocomplete
Design typeahead suggestions with a top-k trie, an offline pipeline from query logs, edge caching, and client debouncing.
Type "how to" into any search box and ten suggestions appear before you finish the word. That happens on every keystroke for billions of people, in under 100 milliseconds, which makes autocomplete one of the highest-traffic features on the internet. It is a favourite interview question because the best answer is not "query the database faster", it is "do the work ahead of time".
Requirements
Functional
- As the user types, show up to 10 suggested completions for the current prefix.
- Suggestions are ranked by popularity, with some freshness (trending topics) and some personalization (your recent searches).
- Offensive or unsafe suggestions are filtered out.
Non-functional
- Very fast: suggestions within 100 ms end to end, or they feel broken and users type past them.
- Highly available; it is fine to show slightly stale suggestions (updated hourly, with trends within minutes).
- Massive read volume, tiny write volume (writes are just query logs).
Out of scope: the search results page itself, spelling correction (mentioned briefly), multilingual tokenization.
Back-of-the-envelope numbers
| Quantity | Math | Result |
|---|---|---|
| Searches | 5 billion a day | |
| Suggest requests | about 4 per search after debouncing: 20B / 86,400 | about 230,000/s (peak 500,000/s) |
| Distinct queries kept | the most popular after filtering | about 100 million |
| Average query length | about 20 characters | |
| Prefix table | prefixes up to 20 chars, each with a top-10 list | tens of GB, sharded in memory |
Half a million reads a second with a 100 ms budget rules out computing anything per request. Every answer must be precomputed and served from memory, ideally from a cache near the user.
API
GET /v1/suggest?q=how%20to%20m&limit=10&locale=en-GB
200 OK
Cache-Control: public, max-age=300
{ "prefix": "how to m", "suggestions": ["how to make pancakes", "how to meditate", "how to make money online", ...] }It is a GET with the prefix in the URL, which matters: CDNs can cache it. Personalized results for signed-in users are merged in by a separate, uncacheable call or on the client.
Data model
- Query logs: append-only events
(query, user_id, locale, ts)streamed to Kafka and stored in object storage. The raw material. - Query counts: a batch job's output,
(query, locale, score), where score is a decayed count. - Prefix index: a trie (or an equivalent key-value table
prefix → top-10 list), rebuilt from the counts and loaded into memory on the suggestion servers. - User history:
(user_id, query, last_used)for personalization, kept small (last 100 queries).
The trie with top-k at every node
A trie (prefix tree) stores strings character by character: every path from the root spells a prefix. Finding all completions of ca means walking to the ca node and collecting everything below it. That walk is fast, but collecting and sorting a subtree with a million queries under it is not.
The trick: store the top-k completions at every node when you build the trie. A lookup becomes "walk len(prefix) steps, return the stored list". No subtree search at request time.
Query counts: car 900, cat 700, care 400, cart 150, dog 300. Each node stores the 3 most popular queries in its subtree, worked out once at build time.
a cost?Here is a working version. It builds the trie from query counts, stores the top k at each node, and answers prefixes in O(length of prefix).
Press Run (⌘ Enter) to see what happens.Production systems often skip pointer-based tries and store the same thing as a flat key-value map from prefix to its top list ("car" → [...]), sharded by prefix. The lookup is one hash get, and the build is a batch job that emits every prefix of every query.
High-level design
Read path. The user pauses after typing ca. The browser sends GET /v1/suggest?q=ca. Short, popular prefixes are cached at the CDN edge for a few minutes and answered in about 10 ms.
Deep dive 1: building suggestions from query logs
Suggestions come from what people actually search. The offline pipeline:
- Collect submitted queries (not every keystroke) from the log stream.
- Normalize: lowercase, trim spaces, collapse repeats.
- Count with decay: recent searches count more, so last week's news fades. A common formula:
score = Σ count × 0.5^(age / half_life). - Filter: drop queries searched by fewer than N distinct users (privacy: one person's typo must never become a suggestion), and drop offensive or unsafe terms with a blocklist and classifiers.
- Build top-k for every prefix and write a snapshot.
Hourly batches miss breaking news. A separate streaming job counts the last few minutes and boosts sudden spikes ("earthquake" jumping 1,000x), merged in at serving time.
Order the offline suggestion pipeline.
- Tap the steps below in the right order.
Deep dive 2: debouncing on the client
Typing "how to make pancakes" is 20 keystrokes. Sending 20 requests is wasteful, because most results would be replaced before they render. The client debounces: it waits until the user pauses for about 150 ms, then sends one request for the latest prefix. It also cancels in-flight requests for stale prefixes and caches results locally (backspacing to how to m shows the earlier answer instantly).
Press Run (⌘ Enter) to see what happens.What does this print?
// Keys arrive at 0 ms, 100 ms, 200 ms, then nothing. // Debounce wait is 150 ms. When does the single request fire? const lastKey = 200; const wait = 150; console.log(lastKey + wait);
Deep dive 3: ranking and personalization
Popularity gets you most of the way. Real rankers blend more signals at serving time:
- Personal history: you searched
carbonara recipeyesterday, so it ranks first forcarfor you. - Location and language:
footballcompletes differently in London and Dallas. Build separate tries per locale or region. - Freshness: the streaming trend boost from above.
- Quality: queries that led to clicks score higher than ones people abandoned.
The trie returns, say, the top 50 candidates for the prefix; a lightweight ranker rescores them with these signals and keeps 10. The expensive part is still precomputed; the per-request work is sorting 50 items. Spelling tolerance (pancaeks) is a separate fuzzy lookup used when the exact prefix returns too little.
Match the problem to the technique.
Bottlenecks, failures, and 10x scale
- Shard hot spots. Sharding by first letter is uneven (far more queries start with
sthanx). Shard by a hash of the first two or three characters, or by measured load. - Bad snapshot. A broken build could serve garbage everywhere. Validate snapshots (size, sample queries) before loading, keep the previous one, and roll back automatically.
- Unsafe suggestions. Keep a real-time blocklist checked at serving time, so a removal takes effect in seconds, not at the next hourly build.
- Server memory. Cap prefix length (around 20 characters) and k; long-tail prefixes beyond that fall back to a slower search index.
- 10x: more replicas of each trie shard (reads scale with replicas, the data does not grow 10x), more edge caching, and per-region tries close to users.
- trie
- A prefix tree: each path from the root spells a prefix, so all completions of a prefix live under one node.
- top-k per node
- Storing the k best completions at every trie node during the build, making lookups O(prefix length).
- debouncing
- Waiting until input pauses for a short time before acting, so a burst of events causes one request.
- time decay
- Weighting recent events more than old ones, for example halving a count's weight every week.
- snapshot swap
- Building a new index offline and replacing the old one atomically, so readers never see a partial state.