Design typeahead (search autocomplete)
Suggest the most popular completions for a prefix on every keystroke. The work is done offline, by precomputing the top results for each prefix, so serving is a memory lookup.
The problem
A shop adds suggestions to its search box. The first version runs a query on every keystroke: find rows in the search log table where the text starts with what the user typed, order by count, take ten. With a few million rows it answers in 30 ms. A year later the table holds a billion rows, the prefix “s” matches tens of millions of them, and sorting those takes seconds. People type a character every 100 to 200 ms, so a suggestion that arrives a second late describes a prefix the user left behind several keystrokes ago.
Google launched this feature as Google Suggest, a Labs experiment, in 2004, and it has since become something users expect from any search box. The interesting property of the problem is that it is extremely read-heavy and tolerant of staleness: the best completions for “sys” barely change from one hour to the next. That lets almost all the work move offline.
Requirements
Functional
- Given the prefix typed so far, return up to 10 completions, ranked by popularity.
- Suggestions are past search queries, not documents.
- New popular queries appear within a day, and sharply trending ones within minutes.
- Offensive, illegal or private queries are never suggested, and one can be removed within minutes.
Out of scope at first: spelling correction, personalisation (treated as an extension below) and the search results themselves.
Non-functional
- Latency: suggestions visible within about 100 ms of the keystroke. Most of that is the network, so the server gets about 10 ms at p99.
- Availability: 99.99% for serving. If suggestions fail, search must still work.
- Scale: 100 million daily users.
- Freshness: eventual. Suggestions may be hours old.
- Read-only serving: nothing a user does on the suggestion path writes to the index.
Capacity estimates
| Quantity | Working | Result |
|---|---|---|
| Searches | 100M users x 5 searches a day | 500M per day |
| Suggestion requests | 500M x about 6 requests per search after debouncing | 3 billion per day |
| Average rate | 3 billion / 86,400 seconds | about 35,000 per second |
| Peak rate | 3x average | about 100,000 per second |
| Queries kept | assumed, after dropping rare queries | 100 million |
| Prefix entries | 100M x about 5 new prefixes each (short prefixes are shared) | 500 million |
| Index size | 500M x 100 bytes (ten 8-byte query IDs plus overhead), plus 100M query strings x 30 bytes | about 55 GB |
| Query log | 500M x 100 bytes | 50 GB per day |
The numbers of kept queries and prefixes are assumptions, and an interviewer may give different ones. The conclusions hold across a wide range. The index is tens of gigabytes, which fits in the memory of one large machine or a few ordinary ones, so every lookup can be a memory read. The request rate is high but each request is trivial. All the expensive work, counting and ranking 500 million searches a day, can run offline.
API
GET /v1/suggest?q=sys&lang=en&limit=8
200 OK
Cache-Control: public, max-age=600
{ "q": "sys", "suggestions": ["system design interview", "system of a down", "sysadmin"] }
It is a plain GET with everything in the URL, so browsers and CDNs can cache it. The server normalises the prefix before lookup (lower case, trimmed, Unicode normalised) and the client should send it normalised too, so that “Sys” and “sys” share a cache entry. The response echoes q so the client can discard a response for a prefix the user has already moved past.
Data model
Three data sets, each derived from the one before.
| Data | Shape | Where |
|---|---|---|
| Query log | query, time, language, anonymous user hash, whether it came from a suggestion | a log such as Kafka, then object storage |
| Query counts | (query, language, hour) to count and distinct users | a batch-friendly table |
| Serving index | prefix to top 10 of (query, score) | memory of the suggestion servers |
The serving index is the only one on the request path, and it is immutable between builds.
High-level architecture
Serving path. The client waits for a pause in typing, checks its own cache, then sends the request. The CDN answers from its cache if it can. Otherwise the request reaches a suggestion server through the load balancer. The server looks the prefix up in its in-memory index, removes anything on the serving blocklist and returns the list.
Logging path. When a user actually runs a search, the search service writes an event to the query log. Individual keystrokes are not logged as queries, because “sys” is not something anyone wanted to search for.
Build path. Aggregation jobs turn the log into counts per query per hour. The index builder reads the counts, applies filters, computes the top 10 for every prefix and writes a snapshot to object storage. Suggestion servers load the snapshot and switch to it.
Deep dives
The index: a trie with top-k at every node
A trie stores strings by sharing prefixes: one node per character, with each query ending at some node. Finding the node for a prefix of length L takes L steps, which is fast.
The slow part is what comes next. To return the ten most popular queries under “s”, a plain trie has to visit every query that starts with “s”, which is millions of nodes, and rank them. Short prefixes are both the most expensive and the most requested.
The fix is to do that ranking once, at build time, and store the result on the node.
s top: spotify, speed test, system design interview, ...
sy top: system design interview, sydney weather, synonym, ...
sys top: system design interview, system of a down, sysadmin, ...
A lookup now walks to the node and returns its list. The cost depends on the length of the prefix and on k, and not on the size of the subtree.
This costs memory, because every node carries a list. Three things keep it in check: store query IDs in the lists and each string once, cap the prefix length at about 20 characters (beyond that few queries remain and the client can filter what it has), and merge chains of single-child nodes. It also makes in-place updates awkward. A change in one query’s score can alter the list of every one of its prefixes while readers are using them, which is the main reason to rebuild offline and swap.
Splitting the index. At 55 GB I would not shard at first: every suggestion server holds the whole index and any server can answer any request. If one server handles 10,000 requests a second, peak load needs 10, and I would run about 20 across zones. When the index outgrows a machine, split by language or country first, since those tries share nothing, and only then by prefix range. Ranges should be chosen from measured load, because far more queries start with “s” than with “x”.
Building the index from query logs
- Aggregate. Hourly jobs count each query per language and count distinct users.
- Score. Sum the hourly counts with exponential decay, so last week weighs more than last year. The half-life is a tuning choice: short for news, long for a product catalogue.
- Filter. Drop queries with fewer than a minimum number of distinct users. That removes typos and noise, makes it hard for one bot to plant a suggestion, and keeps a private query (someone’s address, a phone number) from being shown to everyone. Then apply the blocklist.
- Build. For each surviving query, emit every prefix with the query and its score. Group by prefix and keep the top 10. This is a standard batch job in Spark or similar.
- Publish. Write a snapshot with a version and a checksum. Validate it: total size and entry count within a few percent of the last one, and a list of well-known prefixes still returning sensible results.
- Swap. Each server downloads the snapshot, builds the new index beside the old one and switches a pointer. Roll out a few servers at a time and keep several old snapshots for rollback.
Trending queries. A daily build cannot show a query that became popular ten minutes ago. Rebuilding everything more often is wasteful, because almost nothing changed. Instead a stream job counts queries over the last few minutes, compares them with their usual rate and publishes a small overlay of rising queries, a few thousand entries. Servers fetch the overlay every minute and merge it with the main index at lookup time.
Serving fast, and caching at the client and edge
In the client.
- Debounce. Send a request only after typing has paused for somewhere around 100 to 200 ms. A shorter wait feels livelier and sends more requests.
- Ignore stale responses. Responses can arrive out of order. Show one only if its
qmatches the current input. - Cache by prefix for the session, so backspacing is instant.
- Filter locally. If the list for “syst” came back shorter than the limit, it is complete, and the answer for “syste” is a filter of it with no request. If it was cut at the limit this is not safe, because a query outside the top 10 for “syst” may be in the top 10 for “syste”.
At the edge. There are 26 one-letter, 676 two-letter and 17,576 three-letter prefixes in the Latin alphabet, about 18,000 in total, and every search passes through them. A CDN holds all of them with ease and answers a large share of requests without touching the origin (see CDN caching). Long prefixes are the long tail: they mostly miss, and they are cheap to serve. The TTL trades origin load against how quickly a new build or a removal becomes visible, so keep it to minutes and use the CDN’s purge API for removals.
At the server. The lookup itself takes microseconds. The time goes on connections and serialisation, so keep connections alive with HTTP/2 or HTTP/3, keep responses under a kilobyte, and serve from the region nearest the user.
Personalisation as an extension. A user’s own recent searches are the most useful suggestions for them. Keep them as a small per-user list, on the device or in a key-value store, and merge them on top of the global list in the client. Fetching the two separately keeps the global response identical for everyone and therefore cacheable.
Bottlenecks and failure modes
- A bad build. An upstream failure produces a tiny or empty index. Validation before the swap, a canary server and kept snapshots mean users see yesterday’s suggestions, which nobody notices.
- Memory during a swap. Holding two indexes needs twice the memory. Either provision for it or take each server out of rotation while it loads.
- Suggestion service down. The client hides the dropdown after a short timeout. Search is unaffected, because the two share nothing on the request path.
- Feedback loops. A suggested query gets clicked, which raises its count, which keeps it suggested. Log whether a search came from a suggestion and discount those.
- Manipulation. People try to plant suggestions by repeating a query. Counting distinct users, and rate limiting search itself, blunt this.
- Urgent removal. The blocklist is pushed to servers in seconds and checked on every response, and the affected prefixes are purged from the CDN. Waiting for the next build is too slow.
Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Ranking | Precomputed top-k per prefix | Rank at query time | Lookup cost is independent of subtree size; costs memory and build time |
| Updates | Offline build, atomic swap | In-place updates | Readers never see a half-updated index; freshness is hours |
| Freshness | Daily build plus trending overlay | Frequent full rebuilds | Small overlay is cheap; two sources to merge |
| Index layout | Whole index on every server | Shard by prefix | No routing and no scatter; limited by one machine’s memory |
| Personalisation | Separate list merged in the client | Per-user server ranking | Global list stays cacheable; simpler ranking |
45-minute interview script
A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.
- 0:00 to 5:00
Requirements 5 min
Agree what is suggested (popular queries, not documents), how many, how fresh, and which languages. Set the latency target against typing speed. Put personalisation and spelling correction out of scope for now.
- 5:00 to 9:00
Capacity estimates 4 min
Requests per second from searches and keystrokes, then the number of prefixes and the size of the index. Conclude that the index fits in memory and that all the heavy work can be done offline.
- 9:00 to 12:00
API 3 min
One cacheable GET. Normalise the prefix, echo it in the response, and set cache headers.
- 12:00 to 16:00
Data model 4 min
The query log, the aggregated counts and the serving index of prefix to top-k list.
- 16:00 to 24:00
High-level design 8 min
Draw the serving path from client through CDN to the suggestion service, then the logging path, then the offline build that produces a snapshot the servers load.
- 24:00 to 31:00
Deep dive: the index 7 min
A trie, why a plain trie is too slow for short prefixes, and storing the top-k at every node. Compare with a flat prefix map. Say how the index is split when it outgrows a machine.
- 31:00 to 37:00
Deep dive: building from logs 6 min
Aggregate, decay, filter, build, validate, swap. Then how trending queries get in within minutes without rebuilding everything.
- 37:00 to 42:00
Deep dive: serving and caching 5 min
Debounce and local cache in the client, edge caching of short prefixes, and the latency budget.
- 42:00 to 44:00
Failure modes and extensions 2 min
A bad build, manipulation of suggestions, urgent removals. Sketch personalisation as a separate, uncached list merged on top.
- 44:00 to 45:00
Wrap-up 1 min
One sentence each for the serving path and the build path, and the main trade-off, which is freshness against simplicity.
Key takeaways
- Typeahead is read-heavy and tolerant of staleness, so compute the answers offline and make serving a lookup.
- A plain trie finds the prefix quickly but must then search a whole subtree. Storing the top-k list at every node makes the lookup cost depend only on the prefix length.
- Build the index from aggregated query logs in a batch job, publish it as a versioned snapshot, validate it and swap it in atomically.
- Short prefixes are few and carry a large share of traffic, so they cache very well at the edge and in the client.
- Handle trending queries with a small, frequently updated overlay instead of rebuilding the main index.
- Only suggest queries that many different users have typed. This removes noise, resists manipulation and protects privacy.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
Why precompute the top-k at each trie node?
So a lookup walks to the prefix node and returns its stored list, with no search of the subtree. The cost depends on prefix length, not on how many queries share the prefix.
What are the steps of the offline build?
Aggregate the query log into counts, apply time decay, filter (minimum distinct users, blocklist), compute the top-k for every prefix, write a versioned snapshot, validate it, and swap it in on the servers.
How do trending queries appear within minutes?
A stream job counts queries over the last few minutes and publishes a small overlay of rising queries. Servers merge the overlay with the main index at lookup time.
What does the client do to cut requests?
Debounce keystrokes, cache results by prefix for the session, drop responses that arrive out of order, and filter a complete cached list locally when the user types another character.
Why do short prefixes cache so well?
There are few of them (about 18,000 of up to three Latin letters) and every search passes through them, so a small edge cache answers a large share of requests.
How is an offensive suggestion removed quickly?
Add it to a blocklist that the suggestion servers check at serving time and that is pushed within seconds, then purge the affected prefixes from the CDN. The next build removes it from the index.