Case study: Search autocomplete
Overview
Autocomplete (typeahead) suggests completions as the user types. Every keystroke can be a request, so it’s one of the highest-QPS features in a search product, with a tight latency budget. The key idea is to precompute answers so serving is a quick memory lookup.
Try the exercise first: 45 minutes, then compare.
1. Requirements
Functional
- Given a prefix, return the top 10 suggestions ranked mainly by popularity.
- Suggestions update at least daily; trending queries ideally within an hour.
- No offensive or unsafe suggestions.
Non-functional
- Very low latency: under 100 ms end to end, so the server part must take a few milliseconds.
- Very high QPS and high availability; slightly stale suggestions are fine.
2. Estimates
searches : 1B / day
requests : ~5 autocomplete calls per search (after debouncing) → 5B / day ≈ 60,000 / s
peak : ~3× → ~180,000 / s
distinct queries kept: say 100M popular queries × ~30 bytes + top-k lists → tens of GB → shard it3. API
GET /v1/suggest?q=syst&lang=en&limit=10
→ 200 {"suggestions": ["system design", "systemctl", "system of a down", …]}
Cache-Control: public, max-age=3004. Data structure
A trie (prefix tree) stores strings character by character. Finding all completions of a prefix by walking every descendant and sorting would be slow for short prefixes like “s”. Instead, each node stores the top-k completions for its prefix, computed when the trie is built. A request walks down at most a few dozen nodes and returns the stored list.
Memory optimisations: compress chains of single-child nodes (radix tree), store only queries above a popularity threshold, and keep the stored lists short.
5. High-level design
Build path (offline)
- Collect search queries from logs.
- Aggregate counts per normalised query over a time window, with decay so recent popularity matters more.
- Filter: drop rare queries (privacy and noise), spam, offensive and unsafe terms, and personal data.
- Build tries with top-k lists per node, one per shard and language.
- Publish versioned snapshots to object storage; servers load the new version and swap atomically.
Serving path
- Suggest API servers are stateless; trie servers hold the snapshot in memory.
- Shard by prefix (for example by the first one or two characters), balanced by traffic, not by alphabet (“s” gets far more traffic than “x”). Replicate each shard for throughput and availability.
- Cache: responses for common prefixes are identical for everyone, so they’re cached at the CDN and in the browser for minutes.
6. Deep dives
Client-side optimisations
- Debounce: wait ~100–150 ms after the last keystroke before requesting.
- Cancel in-flight requests when a newer prefix is typed.
- Cache responses in the browser; going back from “syste” to “syst” needs no request.
- Optionally prefetch the next likely prefixes.
Freshness and trending
A daily rebuild misses breaking news. Add a streaming job that counts queries over the last hour, detects terms rising sharply, and publishes a small “trending” structure that the API merges with the main suggestions.
Personalisation
Merge the user’s own recent searches (stored per user, or on the device) with global suggestions. Keep the global results cacheable by doing personal merging on the client or as a thin layer in the API.
Safety
Suggestions shape what people search for, so filtering matters: block lists, classifiers for hateful or dangerous completions, and a fast path to remove a suggestion from serving immediately (an override list checked at request time).
7. Trade-offs and bottlenecks
- Precomputing top-k makes reads fast but builds slower and memory larger.
- Prefix sharding can be uneven; split hot prefixes into finer shards.
- Snapshot swaps must be atomic and versioned to roll back bad builds.
8. Follow-up questions
- Typo tolerance? Fuzzy matching against the trie (edit distance) or a spell-correction step.
- Multiple languages? Separate tries per language and locale.
- Ranking beyond popularity? Combine popularity with freshness, location and personalisation scores at build or serve time.
Recap
Autocomplete serves precomputed answers: tries whose nodes store the top-k completions for each prefix, built offline from aggregated and filtered query logs and published as versioned snapshots to in-memory servers sharded by prefix. Edge and browser caching plus client debouncing cut request volume, and a streaming pipeline adds trending queries.
Design it yourself (45 minutes)
Set a 45-minute timer and design search autocomplete for a large search engine: as users type, show the top 10 suggestions for the current prefix, ranked by popularity, within 100 ms. Assume 1 billion searches per day, an average query of 4 words (~20 characters), and suggestions updated at least daily (trending topics within an hour would be nice). Use the framework, then compare.
1. Clarifying questions:
2. Functional requirements:
3. Non-functional requirements:
4. Estimates:
5. API:
6. Data structures:
7. High-level design (serving + building):
8. Deep dives (top-k per node, sharding, freshness, filtering):
9. Trade-offs and bottlenecks:A strong answer covers:
- Estimates: 1B searches/day × ~10 keystroke requests (with debounce maybe ~5) →
~50-100k QPS average, several hundred thousand at peak.
- Data structure: trie of popular queries; each node stores the top-k (e.g. 10)
completions with scores, so a lookup is O(prefix length).
- Build pipeline: query logs → aggregate counts (with time decay) → filter (spam,
offensive, rare queries) → build tries offline → publish versioned snapshots to servers.
- Serving: in-memory trie servers sharded by prefix (e.g. first 1-2 characters, balanced
by traffic) with replicas; cache very hot prefixes at CDN/edge and in the browser.
- Client: debounce (~100-150 ms), cancel stale requests, cache recent responses.
- Freshness: daily full rebuild + streaming job for trending queries merged at serve time.
- Personalisation: merge user's recent searches client-side.Summary
- Precompute: store the top-k completions at every trie node so each request is a short walk with no sorting.
- Build tries offline from aggregated, filtered query logs and publish versioned snapshots.
- Serve from memory on servers sharded by prefix with replicas; cache hot prefixes at the edge and in the browser.
- Reduce request volume on the client with debouncing, cancellation and caching.
- Add freshness with a streaming trending pipeline and filter unsafe suggestions before publishing.