Design Search Autocomplete (Typeahead)
medium 45 minSuggest ten likely searches before a person finishes typing, within 100 ms, for 700,000 requests a second.
See it run
Answer a prefix, read a stored list, rebuild the index, catch a trend and rank.
Operations
Answer a prefix
From key press to list, on a path where every cache misses.
Step 1 of 15
Type and wait
prefix
ho
pause
80 ms
The person types ho. The client waits 50 to 100 ms for a pause. Why: ten key presses become about four requests, by assumption.
Step 1: Type and wait
def suggest(prefix, lang): key = (VERSION, lang, normalise(prefix)) if hit := ranked_cache.get(key): return hit candidates = index.top(key, 100) try: best = ranker.score(candidates, timeout=0.020) except Timeout: best = candidates # stored order best = [c for c in best if not blocked(c)][:10] ranked_cache.set(key, best, ttl=60) return best- Latency
- about 60 ms
- Load
- 700,000/s peak
- Edge answers
- 70% (assumed)
The filter runs after ranking too, so a removal works before the next build.
In the real world
The same search autocomplete doing real jobs. Pick one and step through it.
Traffic grows to three or four times normal.
Step 1 of 4
Normal peak
- Origin
- 210,000/s
700,000 requests a second. The edge takes 70%.
Step 1: Normal peak
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Searching the subtree
criticalOne letter can have millions of queries below it.
Wrongnode = find(prefix)return best(walk(node))Rightreturn find(prefix).top[:10]Writing to the live tree
major58,000 searches a second would change lists that readers use.
Wrongindex.add(query)Rightkafka.send(query) # next snapshotPattern in a Redis delete
majorDEL takes exact key names, so nothing is removed.
Wrongredis.delete("suggest:h*")Rightkey = f"suggest:{VERSION}:{prefix}"Showing every reply
majorThe reply for an older prefix may arrive last.
Wrongshow(reply.items)Rightif reply.number == latest: show(reply.items)Timestamps as trend scores
majorThey show which query was last seen, not how often.
Wrongzadd("trending", {query: now})Rightzincrby(f"trend:{minute}", people, query)
Interview tips
Open with the insight
- Wide prefixes are few and repeated.
- So compute and cache them.
Know the numbers
- 700,000 a second at peak.
- 23 GB index.
- 95.5% answered by caches, assumed.
Two speeds
- Hourly snapshot.
- Overlay in minutes.
- Device history at once.
Fail softly
- Stored order, then stale, then empty.
- Search must not wait.
- Removal in seconds.