Design Typeahead Search
How to design search-box autocomplete, including precomputed top-five lists per prefix, offline popularity rebuilds, and caching to stay under 100 ms.
On this page
Typeahead search shows a list of suggested queries below a search box and updates the list as the user types each character. For a prefix such as "pi" the service returns the most popular past queries that start with it. The service must answer before the next keystroke, within about 100 ms.
The obvious design is a trie on a server, which is only half of the answer. The hard parts are avoiding a search through a huge subtree on every request, keeping popularity current without slowing the serving path, and using caches to meet the latency target. The steps follow A Framework for Any Design, and the data structure is explained in Tries.
Clarify the problem
Design the autocomplete for a search box.
Do we suggest past queries ranked by popularity, or documents? And how many suggestions do we show?
Past queries ranked by popularity, and we show five.
How fresh does the popularity data have to be, and are the suggestions personal to each user?
A day old is fine, although trending queries within an hour would be nice. The suggestions are not personalised.
How many users do we have, and how fast does it need to be?
There are 50 million daily users who each search about 6 times a day, and it should feel instant.
I will treat instant as under 100 ms from keystroke to list for most users. I will support English and prefix matching only, with no spelling correction, and offensive suggestions must be removable quickly.
- Functional: for a prefix, return the 5 most popular past queries that start with it, weighting recent searches more, and let operators remove a bad suggestion.
- Non-functional: under 100 ms for most users, very high availability with an empty list as the fallback, popularity at most a day old, and trending queries within an hour as a stretch goal.
- Out of scope: personalisation, spelling correction, other languages, and searching documents (see Search Systems).
Estimate the scale
The users run 50 million × 6 = 300 million searches a day. A 20-character query could send 20 suggestion requests, but people pick a suggestion early, the client waits for a short pause in typing before it sends a request (debouncing), and the client's own cache answers repeated prefixes. We assume 6 suggestion requests per search, which is 1.8 billion a day. Dividing by about 86,400 seconds gives about 21,000 a second on average, and a 3 times peak is about 62,500 a second. The query log grows by about 30 GB a day (300 million × 100 bytes).
We keep the 10 million most popular queries. If we store a top-5 list for every prefix of every query, how much memory does the table need at most?
- 10 million queries kept
- Queries average 20 characters
- About 150 bytes per prefix entry (the prefix plus five suggestions)
Show the working
- Each query has up to 20 prefixes, so there are at most 107 × 20 = 2 × 108 prefixes
- 2 × 108 × 150 B = 3 × 1010 B = 30 GB
Estimate 30 GB (anything from 10 GB to 100 GB is a good answer)
Queries share prefixes, so the real number is lower. Even this bound fits in the memory of one server.
Write the suggestion endpoint. What makes its responses cacheable by a CDN?
Compare with a model answer
The endpoint is a plain GET with the prefix in the query string and a Cache-Control header. The response contains nothing personal, and the client normalises the prefix (lowercase, trimmed) so that equal prefixes share one cache entry.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
GET /v1/suggest?q=pi&limit=5
200 OK
Cache-Control: public, max-age=3600
{ "q": "pi", "version": "2026-11-14",
"suggestions": ["pizza near me", "pie crust recipe", "pilates",
"pineapple upside down cake", "piano lessons"] }
q is empty 200 with an empty list
q longer than 50 400 Bad Request
service overloaded 503, and the client shows no list while the user keeps typingThe API decision worth arguing is making the response public and cacheable. The request carries no cookie and no user id, so everyone who types "pi" in the same hour can be served from one cached response at the edge. A user id would make every response unique and defeat the cache. The cost is that the API cannot personalise, so the client merges the user's recent searches itself.
What do the serving side and the offline side each store? Which of them is read 62,500 times a second?
Compare with a model answer
The serving side holds one read-only table that maps a prefix to its five best suggestions, and it is replaced on every build. The offline side holds daily query counts that only the build job reads. The hot path never computes anything.
Model the data
-- serving: read-only, rebuilt each build, held in memory on every server
prefix_top5
prefix VARCHAR(50) PRIMARY KEY -- "pi"
suggestions [ (query, score) x 5 ] -- about 150 bytes a row with the key
version DATE
-- offline: written by the log pipeline, read only by the build
query_counts
query VARCHAR(100)
day DATE
count BIGINT
PRIMARY KEY (query, day)
blocklist -- queries and patterns never to suggest; small, edited by peopleThe serving table is only ever read by a single key, and it does not change between builds. It therefore fits an in-memory hash map that is loaded from a file on every suggest server, with no database on the hot path. If the table ever outgrew memory, the next step would be a key-value store partitioned by prefix. The offline counts are large, append-only and scanned in bulk, so they belong in files in blob storage or in a data warehouse.
Sketch the path of a keystroke and the path of a search that later changes the list. Where do the caches sit?
Compare with a model answer
On the read path, the client's cache comes first, then a CDN edge, then identical suggest servers that hold the table in memory. On the write path, searches are logged, a batch job counts and ranks them, and it writes a versioned table to blob storage, which the servers load and swap in.
High-level design
request and replyasynchronous message
- ms used
- 30
1Mia types "pi" and pauses for 30 ms. Her app normalises the prefix to
piand checks its own cache, which has no entry yet.- ms used
- 40
2The app sends
GET /v1/suggest?q=pito the nearest edge location, which has no cached copy ofpi.- ms used
- 70
3A suggest server finds the five suggestions for
piwith one in-memory lookup.- ms used
- 90
4The answer returns with
max-age=3600, and the edge and the app keep a copy. This double miss fits in 100 ms only because the servers are nearby.- ms used
- 60
5A minute later another user near the same edge types "pi". The edge has the answer, so no suggest server is involved.
- ms used
- 30
6Mia types "z" and deletes it, and her app answers
pifrom its own cache.7She submits the search "pizza near me". The search service runs it and writes the query to a log stream.
8Overnight, the build job adds the day's 300 million searches to the decayed counts and computes the top five for every prefix.
9The job writes a new versioned file,
2026-11-15, and overwrites nothing, so a bad build can be rolled back.10Each suggest server loads the file into spare memory and then switches one pointer, so requests never see a half-loaded table.
11If tomorrow's build fails, the servers keep serving this table. The suggestions become a day staler, but they are still valid.
Deep dives
Finding the top five suggestions for a prefix
A trie stores every past query on a path of letters, so all queries that start with "pi" sit under one node, reached in one step per character. Finding the five best completions below that node is the problem. The subtree under a short prefix such as "p" can hold millions of queries, and short prefixes are the most frequent requests. There are three ways to deal with this.
Plain trie with a search per request. The server walks to the prefix node, visits every query below it and keeps the five with the highest counts. It is small and exact, but the work grows with the subtree, so the common short prefixes are the slowest requests.
Trie with the top five stored on every node. The build calculates the top five once, and each node keeps its own list by merging its own query with the lists of its children, so it never looks deeper than its children. A request walks one node per character and reads the list. The cost is a custom structure to load and shard.
Hash map from prefix to top five. The same build writes every node's list into a map keyed by the prefix string, so a request is one lookup in any key-value store. The cost is memory, because every prefix is stored in full. The estimate shows this is at most 30 GB.
1The trie holds five past queries with their search counts. Each edge is one letter, and each node stands for the prefix that leads to it.
- nodes visited
- 3
2Without stored answers, a request for "ca" walks root, c, ca, which is 3 nodes.
- nodes visited
- 7
3The server then visits every node below "ca" to collect the completions, which is 4 more nodes.
4The node "car" merges its own query (50) with the lists of its children (cart 30, care 25) and keeps car and cart.
5The node "ca" merges the list of car (car 50, cart 30) with the list of cat (cat 40) and keeps car and cat.
- nodes visited
- 3
6A request for "ca" now reads the stored list after 3 nodes however large the subtree is, or after one lookup if the lists are kept in a hash map.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Plain trie, search per request | It is small and exact. | Short prefixes are the slowest requests. | Use it when the vocabulary is small enough that a subtree search is cheap. |
| Trie with the top five on each node | A lookup takes one step per character. | It is a custom structure to load and shard. | Use it when memory is too tight to store every prefix as its own entry. |
| Hash map from prefix to top five Usual default | A lookup is a single read, and it shards by prefix hash. | Every prefix is stored in full. | Use it when the table fits in memory. This is my choice, built from a trie offline. |
Every server holds the whole map. If it stopped fitting, I would shard by a hash of the prefix and not by first letter, because far more queries start with "s" than with "x".
Keeping popularity up to date
There are three ways to feed new searches into the table. Updating counts live means every search increments a counter and re-sorts the lists of up to 20 prefixes, which puts writes and locking on the fastest path and leaves no file to inspect or roll back.
A daily offline rebuild appends searches to a log and builds a new table once a day. A query that starts trending this morning appears tomorrow, which is acceptable here. Every build is a file that can be inspected and rolled back, and the serving path never writes. This is my base design.
A trending overlay adds a stream job that compares each query's count in the last hour with its normal rate and publishes the spiking queries every few minutes. The suggest servers merge them into the daily results. It gives freshness within an hour, but it needs a second system and a tuned merge rule, so I offer it as an extension.
The rebuild also decides the ranking. Weighting each day's count by 0.8 for every day of age lets recent searches win: a query searched 1,000 times a week ago scores 1,000 × 0.87, which is about 210, so a query searched 300 times today ranks above it. The build also drops rare queries, which are mostly typos and private details, and everything on the blocklist.
Meeting the 100 ms budget with caches
For a user near an edge location the budget is about 30 ms of debouncing, 15 to 30 ms to the edge and back, 30 ms from the edge to a suggest server and back on a miss, under 1 ms for the lookup and 10 ms to draw the list. An edge hit therefore takes 55 to 70 ms, and a miss to a nearby region takes 85 to 100 ms. A miss to a distant region goes over budget, so there are three layers of caching and the servers run in several regions.
The client keeps every response for the session, so backspacing never costs a request. It discards replies whose prefix no longer matches the text in the box. If the list for "pi" has fewer than five entries it is complete, so the client can filter it to answer "piz" without a request.
The edge caches the responses because the API is public. There are only 26 + 262 + 263 = 18,278 letter prefixes of up to three characters, and they draw a large share of the requests. We assume the edge answers 60% of all requests, so the 62,500 a second at peak become 25,000 a second at the suggest servers. See CDNs for how edge caching works.
Removing a bad suggestion quickly
Filtering only in the daily build would leave an offensive suggestion visible for up to a day. Instead, each suggest server refreshes a small blocklist every minute and filters results against it at serve time. The edge may still hold the old response for an hour, so the operator also purges that prefix from the CDN. The next build drops the query for good.
Bottlenecks and failures
What breaks first at 10 times the traffic
At 10 times the traffic the peak is 625,000 requests a second. The edge still answers 60%, so 250,000 a second reach the suggest servers. They share nothing, so you add more of them: at about 10,000 requests a second each, limited by the HTTP stack and not the lookup, that is 25 servers plus spares. The build breaks first, because 300 GB of log a day needs a distributed batch job.
A suggest server, a region or an edge location fails
When one suggest server dies, requests to it fail until the health check removes it, and the other identical servers take its share. If a whole region is down, misses go to another region and exceed the budget, so the client gives up on a timeout and shows no list while search keeps working. If an edge location fails, users move to the next nearest one, which has a cold cache and sends more misses to the servers for a while.
The build job or the log stream fails
If the build fails, the servers keep serving yesterday's table, and an alert fires when the table is more than 2 days old. If the log stream loses a few hours of searches, the ranking barely changes.
What a strong answer sounds like
The table below shows how answers differ by level.
| Level | What the answer does |
|---|---|
| Junior | It searches a trie on every request and updates counts on every search. |
| Mid | It stores the top five per node, rebuilds offline, adds a cache and debounces. |
| Senior | It spends a 100 ms budget, makes responses edge-cacheable on purpose, builds versioned tables with decay, and removes bad suggestions at serve time. |
An offensive suggestion is showing for a common prefix. How fast can you remove it?
I can remove it within about a minute. Each suggest server refreshes the blocklist every minute and filters results at serve time. The edge may hold the old response for an hour, so I would also purge that prefix from the CDN. App copies go away with the session, and the next build drops the query for good.
Follow-up questions
How would you personalise the suggestions?
The client stores the user's recent searches and puts the matching ones first. The shared response stays anonymous, so the edge can still cache it.
How would you show trending queries within an hour?
A stream job compares each query's last-hour count with its usual rate and publishes the spiking queries every few minutes. The suggest servers merge them into the daily results, and the edge time to live drops to a few minutes for short prefixes.
Why not use a search engine's prefix queries?
A search engine suits a small catalogue. At 62,500 requests a second, ranking on every request costs far more than a map lookup, and the answers change only once a day.
How do you stop a bad table from reaching users?
The build compares the new table with the previous one, for example the number of prefixes and how many lists changed, and stops with an alert if the difference is far outside the normal range. Servers also load the file into spare memory first, so a corrupt file fails to load while the old table keeps serving.
How would you handle spelling mistakes and other languages?
Prefix matching cannot fix a typo, because a misspelled prefix matches nothing. A separate spelling-correction step can map the typed prefix to likely intended prefixes, using the query log to learn common corrections, and then look those up in the same table. Each language gets its own table, built from its own log.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".