Skip to content

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.

18 min read0/5 questions

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

QuantityMathResult
Searches5 billion a day
Suggest requestsabout 4 per search after debouncing: 20B / 86,400about 230,000/s (peak 500,000/s)
Distinct queries keptthe most popular after filteringabout 100 million
Average query lengthabout 20 characters
Prefix tableprefixes up to 20 chars, each with a top-10 listtens 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.

Trie with top 3 cached per node
(root)top: car, cat, carecarecarecartcartcarcar, care, cartcatcatcacar, cat, careccar, cat, caredogdogdodogddogroot

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.

1/4
Quick check
Without top-k lists stored at nodes, what would a lookup for prefix a cost?
Need a nudge? A hint rules out a wrong answer.

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).

Pythonautocomplete.py
import heapq class Node: __slots__ = ("children", "top") def __init__(self): self.children: dict[str, "Node"] = {} self.top: list[tuple[int, str]] = [] # (count, query), best first class Autocomplete: def __init__(self, counts: dict[str, int], k: int = 3): self.root, self.k = Node(), k for query, count in counts.items(): node = self.root self._offer(node, count, query) for ch in query: node = node.children.setdefault(ch, Node()) self._offer(node, count, query) def _offer(self, node: Node, count: int, query: str) -> None: node.top.append((count, query)) node.top = heapq.nlargest(self.k, node.top) # keep only the best k def suggest(self, prefix: str) -> list[str]: node = self.root for ch in prefix: node = node.children.get(ch) if node is None: return [] return [q for _, q in node.top] counts = {"car": 900, "cat": 700, "care": 400, "cart": 150, "dog": 300, "carpet": 520, "cartoon": 610, "category": 80}ac = Autocomplete(counts, k=3)for prefix in ["c", "car", "cart", "d", "x"]: print(f"{prefix!r:8} -> {ac.suggest(prefix)}")
Output
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

Autocomplete architecture
Offline pipelineBrowser: debouncedBrowserdebouncedCDN edge: hot prefixesCDN edgehot prefixesSuggest svcSuggest svcUser historyUser historyTrie shards: in memoryTrie shardsin memoryQuery logs: KafkaQuery logsKafkaAggregator: hourly jobAggregatorhourly jobSnapshots: S3SnapshotsS3GET ?q=missprefixlogbuildload

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.

1/6
Quick check
Autocomplete gets 500,000 requests a second. What is most effective to cache at the CDN edge?
Need a nudge? A hint rules out a wrong answer.

Deep dive 1: building suggestions from query logs

Suggestions come from what people actually search. The offline pipeline:

  1. Collect submitted queries (not every keystroke) from the log stream.
  2. Normalize: lowercase, trim spaces, collapse repeats.
  3. Count with decay: recent searches count more, so last week's news fades. A common formula: score = Σ count × 0.5^(age / half_life).
  4. 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.
  5. 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.

Put it in order6 steps

Order the offline suggestion pipeline.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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).

TypeScriptdebounce.ts
function debounce<A extends unknown[]>(fn: (...args: A) => void, ms: number) { let timer: ReturnType<typeof setTimeout> | undefined; return (...args: A) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), ms); };} const sent: string[] = [];const suggest = debounce((q: string) => sent.push(q), 150); // Simulated typing: [text so far, ms since the previous key]const keys: [string, number][] = [ ["h", 0], ["ho", 80], ["how", 90], ["how ", 70], ["how t", 400], ["how to", 60], ["how to m", 90], ["how to ma", 300],]; let t = 0;for (const [text, gap] of keys) { t += gap; setTimeout(() => suggest(text), t);}setTimeout(() => { console.log(`keystrokes: ${keys.length}, requests sent: ${sent.length}`); console.log(sent);}, t + 500);
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

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);
Need a nudge? Hints walk you through it.

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 recipe yesterday, so it ranks first for car for you.
  • Location and language: football completes 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 pairs0/5 matched

Match the problem to the technique.

Choose an item, then its match on the other side.

Bottlenecks, failures, and 10x scale

  • Shard hot spots. Sharding by first letter is uneven (far more queries start with s than x). 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.
Key terms
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.