Case Study 13 โ Search Autocomplete (Typeahead)
Design a search autocomplete / typeahead system like Google Search suggestions or Amazon product search โ as the user types, return relevant completions in milliseconds.
1. Problem
On each keystroke (or every few characters), the client sends a prefix query like "sys" and expects top-K suggestions ("system design", "system of a down", โฆ) ranked by popularity and relevance, with latency low enough that the UI feels instant.
2. Requirements
Functional (MVP)
- Return top K suggestions (e.g., 10) for a query prefix
- Rank by popularity (search frequency) and basic relevance
- Support personalization optionally (user's recent searches) โ phase 2
- Handle prefixes of 1โ50 characters
- Update suggestions as new trending queries emerge (near real-time or daily)
- Multi-language / locale-aware results
Out of scope (initially)
- Full web search results page
- Spell correction across entire index ("did you mean") โ can add fuzzy layer later
- Rich snippets (images, prices) in dropdown
- Voice input processing
Non-functional
- Ultra-low latency: p99 < 50 ms (often < 20 ms)
- High read QPS: every keystroke = 1 request (with debouncing on client)
- High availability โ autocomplete is on critical search path
- Eventually consistent with trending updates (minutes delay OK)
- Cost-efficient at billions of unique queries stored
3. Back-of-the-envelope estimates
These numbers are rough order-of-magnitude math โ not a capacity plan. In interviews, the goal is to show you know what to count and which resource breaks first. A useful shortcut: 1 QPS sustained โ 86,400 requests/day. Autocomplete breaks that rule because every keystroke can fire a request โ client debounce is essential to cut volume.
Why we estimate
Autocomplete sits on the critical search path with a p99 < 50 ms target. Estimates tell us:
- Why you cannot run
LIKE 'prefix%'on a database at request time - How client debounce changes QPS by 2โ3ร
- Whether the index must live in memory (yes, at this scale)
Assumptions
| Assumption | Value | Why it matters |
|---|---|---|
| Daily active search users | 500M | Base traffic volume |
| Keystrokes per search interaction | 8 (before debounce) | Upper bound on raw calls |
| Client debounce | 150 ms | Collapses redundant requests |
| Effective API calls per search | ~3 | After debounce + min prefix length |
| Unique query strings in index | ~500M | Long tail storage |
| Top-K suggestions returned | 10 | Fixed response size |
Step A โ Traffic (QPS) with labeled arithmetic
Daily autocomplete requests:
Searches per day = 500,000,000
Calls per search = 3 (after debounce)
Daily requests = 500M ร 3 = 1,500,000,000 requests/day
Average QPS:
Average QPS = 1,500,000,000 รท 86,400
โ 17,361 requests/second
โ 17,000/s (round for interview)
Peak QPS (5ร average, regional spikes higher):
Peak QPS โ 17,000 ร 5 โ 85,000/s
Without debounce (why debounce matters):
Raw calls = 500M searches ร 8 keystrokes = 4B requests/day
Raw QPS = 4B รท 86,400 โ 46,000/s โ 2.7ร worse than debounced
Index update traffic (async, off hot path):
Search log ingest: high volume, but batched every 1โ5 minutes
Write QPS to live trie: effectively 0 at request time โ full snapshot rebuild + swap
Step B โ Storage
Unique query strings (raw text):
Queries = 500 million
Avg term length โ 30 bytes
Raw term text = 500M ร 30 B โ 15 GB
In-memory trie with top-K at each node:
15 GB raw terms + trie structure overhead + top-10 heaps per node
Total in memory โ 50โ100 GB (sharded across nodes)
Top 1M prefixes serve ~80% of traffic โ fits easily in Redis + local LRU
Snapshot files (for rolling reload):
Serialized trie snapshot โ 50โ100 GB per locale โ stored in S3, loaded at pod start
Step C โ Bandwidth
Response size per suggest call:
10 suggestions ร ~40 B JSON each โ 400 B payload + overhead โ 1 KB/response
Peak egress โ 85,000/s ร 1 KB โ 85 MB/s (modest โ latency, not bandwidth, is the constraint)
Search log ingest (write side):
500M searches/day ร ~100 B log line โ 50 GB/day of raw logs โ Kafka, not the suggest API
Step D โ Read:write ratio table
| Operation | Type | QPS | Notes |
|---|---|---|---|
GET /suggest | Read | ~17k avg; ~85k peak | Must be < 50 ms p99 |
| Trie lookup | Read | Same | O(prefix length) walk |
| L1/L2 cache hit | Read | ~80% of prefix traffic | Hot prefixes |
| Search log append | Write | ~5,800/s avg | Separate pipeline |
| Index rebuild | Write | Batch every 1โ5 min | Zero-downtime pointer swap |
Ratio: millions : 1 read-to-write on the hot suggest path โ classic read-heavy, precompute pattern.
What the numbers tell us
- 17kโ85k read QPS with < 50 ms p99 โ precomputed trie + top-K per node, not database queries
- Client debounce cuts QPS ~3ร โ mention it proactively in interviews
- 50โ100 GB in memory โ shard tries by first character or hash prefix across servers
- 80% traffic on top 1M prefixes โ Redis + in-process LRU cache is high ROI
- Index updates are async โ batch rebuild from search logs; swap snapshot without downtime
- Long tail (500M queries) is fine offline; hot path only walks a trie
Common mistake for this problem
Proposing Elasticsearch or SELECT ... LIKE 'prefix%' on every keystroke. At 85k QPS and 500M rows, that cannot hit p99 < 50 ms. The correct pattern is offline precomputation + in-memory serve + cache. Another mistake: forgetting debounce and overstating QPS by 2โ3ร.
4. High-Level Design (HLD)
Components
| Component | Role |
|---|---|
| Autocomplete Service | Stateless API; lookup prefix โ top-K |
| Prefix Index | Trie or sorted array + binary search per shard |
| Popularity Counter | Count query frequencies from search logs (Flink/Spark) |
| Index Builder | Merges counts, builds new index snapshot periodically |
| Snapshot Store | Versioned index files for rolling reload |
| Cache | Hot prefix results (Redis + in-process LRU) |
| Log pipeline | Ingest raw searches โ aggregate top queries |
Flows
Query path (read)
- User types
"sys"โ client debounces โGET /suggest?q=sys&limit=10 - Autocomplete Service normalizes query (lowercase, trim)
- Check local LRU cache โ Redis โ in-memory trie shard
- Return JSON list in ~5โ20 ms
Index update path (write, async)
- Search logs stream to Kafka
- Counter job aggregates
(query, count)windows - Every N minutes, Builder merges with historical totals
- Builds new trie snapshot โ uploads to S3
- Autocomplete pods reload snapshot with zero-downtime swap
Trade-offs
| Approach | Pros | Cons |
|---|---|---|
| Trie in memory | Fast prefix walk O(prefix len) | Memory heavy; rebuild complexity |
| Elasticsearch completion suggester | Less custom code | Harder to hit <10ms p99 at huge scale |
DB LIKE 'prefix%' | Simple | Too slow at billions of rows |
| Client debounce 150โ300 ms | Cuts QPS 3โ5ร | Slightly less "live" feel |
| Global vs per-locale index | Better relevance | More shards to maintain |
Interview answer: Precomputed trie + top-K heap per node, sharded by first character or hash prefix.
5. Low-Level Design (LLD)
APIs
GET /api/v1/suggest?q=system&limit=10&locale=en-US
โ 200 {
"query": "system",
"suggestions": [
{ "text": "system design interview", "score": 98234 },
{ "text": "system of a down", "score": 45100 },
...
],
"latencyMs": 4
}
GET /api/v1/suggest/health
โ 200 { "indexVersion": "20260720-1430", "shardStatus": "OK" }
Optional: POST /internal/index/reload for controlled rollout.
Schema (metadata & analytics โ not the hot path)
query_stats (
query_text TEXT,
locale VARCHAR(10),
daily_count BIGINT,
total_count BIGINT,
last_seen TIMESTAMPTZ,
PRIMARY KEY (locale, query_text)
)
index_snapshots (
version VARCHAR(30) PRIMARY KEY,
locale VARCHAR(10),
blob_path TEXT,
record_count BIGINT,
created_at TIMESTAMPTZ,
is_active BOOLEAN
)
-- Personalization (phase 2)
user_recent_searches (
user_id UUID,
query_text TEXT,
searched_at TIMESTAMPTZ,
PRIMARY KEY (user_id, query_text)
)
The hot index lives in memory (trie files), not queried from Postgres per request.
Modules
SuggestController / SuggestService
PrefixIndex / TrieNode / TopKHeap
IndexLoader / SnapshotManager
QueryNormalizer / LocaleRouter
PopularityAggregator / IndexBuilderJob
SuggestCache (L1 LRU + L2 Redis)
Data structure โ trie with top-K at each node
Each trie node stores:
children: map char โ nodetopK: fixed-size max-heap or sorted array of{ phrase, score }for full queries passing through this prefix
class TrieNode:
children: Map<char, TrieNode>
topK: List<Suggestion> # size โค K, sorted by score desc
function insert(phrase, score):
node = root
for ch in phrase:
node = node.child(ch)
node.topK.addOrUpdate(phrase, score) # keep only best K
Query "sys" โ walk s โ y โ s โ return node.topK.
Key algorithm โ suggest
function suggest(rawQuery, limit, locale):
q = normalize(rawQuery, locale) # lowercase, NFC unicode, trim
if len(q) == 0: return trending(locale) # optional: show trending when empty
if len(q) > MAX_PREFIX: q = q[0:MAX_PREFIX]
cached = cache.get(locale, q)
if cached: return cached
shard = shardFor(q, locale) # e.g., first char 's' โ shard 18
node = shardIndex[shard].walk(q)
if node is null: return []
results = node.topK.take(limit)
cache.set(locale, q, results, ttl=60s)
return results
Key algorithm โ build index from logs
function buildIndexSnapshot(locale, windowHours=24):
counts = aggregateSearchLogs(locale, windowHours)
# Merge with historical decay: score = 0.7*today + 0.3*yesterday
merged = mergeWithDecay(counts, historicalStats)
trie = new Trie()
for (phrase, score) in merged.sortedByScore():
if isBlocked(phrase): continue # profanity, spam
trie.insert(phrase, score)
snapshot = serialize(trie)
uploadToS3(version, locale, snapshot)
markSnapshotReady(version)
Key algorithm โ zero-downtime reload
function reloadIndex():
meta = snapshotStore.latestActive(locale)
newTrie = deserialize(download(meta.blob_path))
atomicSwap(shardIndexes[locale], newTrie) # pointer swap in memory
localCache.clear()
Use double-buffering: readers always hold ref to current trie; writers build new trie then swap pointer atomically.
Client-side optimizations (mention in interview)
# Debounce: wait 150ms after last keystroke before API call
# AbortController: cancel in-flight request when user types next char
# Minimum prefix length 2 before calling API
# Cache recent prefixes client-side (sessionStorage)
Concurrency & correctness
| Concern | Approach |
|---|---|
| Stale suggestions after reload | Version header in response; client can ignore stale |
| Thundering herd on deploy | Pre-warm cache; gradual pod rollout |
| Unicode normalization | NFC + locale-specific lowercasing (Turkish I/i) |
| Spam queries polluting index | Min count threshold; blocklist; rate limit writes to stats |
Shard imbalance (a* hotter than z*) | Shard by hash prefix, not only first char |
Fuzzy matching (bonus): For typo tolerance, maintain separate n-gram index or use Levenshtein on top-1000 popular queries only โ full fuzzy on billions is too slow for p99.
6. Scale evolution
| Stage | Change |
|---|---|
| MVP | Single trie in memory, nightly batch rebuild, one region |
| 10k QPS | Redis cache, horizontal API replicas, debounced clients |
| 100k QPS | Sharded tries by prefix hash; edge CDN caching for top prefixes |
| Global | Per-locale indexes; geo-routed replicas |
| Personalization | Blend global top-K with user's recent searches (weighted merge) |
7. Recap
- Autocomplete is precomputation + cache, not ad-hoc DB search at request time
- Store top-K at each trie node for O(prefix length) lookups
- Cut QPS with client debounce and request cancellation
- Update index async from search logs; swap snapshots without downtime
Practice: Explain trie vs Elasticsearch for this use case. Write suggest() pseudocode including cache and shard routing.