"Design search autocomplete" is the question behind the dropdown that appears as you type. Each keystroke sends a request, and a fraction of a second later the five most likely completions appear. Everything about the design is set by that fraction of a second.
Interviewers use it because it looks like a search problem and is not. A search engine finds documents that match words. Autocomplete finds the best completions of a few characters, using no documents at all, only a history of what people have searched. The search systems lesson covers inverted indexes, and you will not need one here. What you need is a different structure, a clear latency budget and a plan for keeping it fresh.
The interviewer is listening for three things: why you precompute the answer for each prefix, how you shard and cache the result, and how new trending queries and takedowns reach the box in minutes rather than days.
Clarify the requirements
Functional requirements:
- As the user types, return the top 5 suggested completions for the current prefix.
- Suggestions are ranked by popularity, with newer interest weighted more.
- Suggestions reflect new trending queries within minutes.
- Offensive, illegal or legally removed queries never appear.
Out of scope, said aloud: typo correction ("did you mean"), personalized suggestions from a user's history, multi-language tokenization, and the search results page itself.
Non-functional requirements:
- Fast: the dropdown must appear before the user types the next character, so the end-to-end response is under 100 ms and the server's share is about 20 ms at p99.
- Highly available, but degradable: if suggestions fail, the search box still works.
- Read-heavy: almost every request is a read and writes are an offline pipeline.
- Eventually fresh: minutes of lag are acceptable, hours are not.
Estimate the scale
Assume 10 million daily active users, 10 searches each a day, and about 6 autocomplete requests per search once the client waits for a short pause in typing.
Requests: 10M × 10 × 6 = 600 million a day ÷ 86,400 s ≈ 7,000 per second on average, about 21,000 per second at peak.
Search log events: 10M × 10 = 100 million a day ≈ 1,160 per second into the analytics pipeline. At about 200 bytes each, one year is 100M × 200 B × 365 ≈ 7.3 TB.
The suggestion table: assume the queries seen often enough to suggest (above a minimum frequency) give about 300 million distinct prefixes up to 20 characters. Each entry holds the prefix (about 12 bytes), five suggestion ids (5 × 8 B = 40 B) and about 50 bytes of overhead, roughly 100 bytes. 300M × 100 B = 30 GB, which fits in memory on a few machines and replicates easily.
Cache effect: short prefixes ("a", "ap", "app") are asked by a huge share of users. Assume a cache layer absorbs 70% of requests. The origin then sees 21,000 × 0.3 = 6,300 per second at peak.
"7,000 requests per second is small, and 30 GB of table fits in RAM, so capacity is easy. The constraint is latency per keystroke, which means no search at query time: the answer for every prefix must already exist, ready to read by key. The design is a precomputation pipeline plus a very fast lookup."
You can see the request rates in the capacity estimator, where writes are search log events.
API and data model
GET /v1/suggest?q=how+to+b&limit=5 -> { prefix, suggestions: [{ text, score }] }suggestions key: normalized prefix -> [ {text, score} x 5 ] (the serving table)
query_counts (query, window_start) -> count (the offline input)
blocklist normalized query or pattern (applied at build and at serve)The serving table is keyed by the prefix itself, so one request is one key lookup and nothing else. All the ranking work has already happened by the time a user types.
High-level design
The slice to simulate is the serving path: a CDN in front of a suggest API, a prefix cache and a suggestion index behind it.
- The CDN answers popular short prefixes without reaching the origin.
- The suggest API checks a prefix cache in Redis, and on a miss reads the suggestion index.
- The index holds the precomputed suggestions for each prefix.
Describe this diagram
Components
- typists (Client)
- edge (Content delivery network)
- suggest api (Service)
- prefix cache (Redis)
- suggestion index (Search cluster (Elasticsearch))
Connections
- typists sends to edge
- edge sends to suggest api
- suggest api sends to prefix cache
- suggest api sends to suggestion index
Run it, then try shortening the cache TTL or the CDN TTL, or raising the load, and watch the origin's share of requests. The cache absorbs most of a read-heavy workload.
The read path: the browser waits for a short pause (about 100 ms) after the last keystroke, cancels any request still in flight, and sends the prefix. The CDN may answer. If not, the API looks in the prefix cache, and on a miss reads the suggestion index and fills the cache.
The build path: an offline pipeline reads search logs, counts queries over a recent window with a decay for older ones, filters blocked terms, and writes the top 5 for every qualifying prefix into the index. It runs on a schedule, with a small streaming layer for trending queries (below).
The interesting problem: answering a prefix instantly
Given the prefix app, return the five best completions in a few milliseconds.
Approach A: query the database
SELECT query FROM queries WHERE query LIKE 'app%' ORDER BY count DESC LIMIT 5.
Good: trivial, and fine for a prototype with a thousand queries.
Bad: with 100 million queries, even an index on the query text must walk every match of app%, including thousands of rare ones, before it can sort by count. A short prefix like a matches millions of rows. Latency is unpredictable and grows with data.
Approach B: a trie, with top-K computed at query time
Store queries in a trie: one node per character, so app is three hops. To suggest, walk to the prefix's node and then explore the subtree for the five best completions.
Good: finding the prefix node is fast, and a trie shares storage between queries that start alike.
Bad: the subtree under a short prefix is enormous. Finding the best five means visiting a large part of it, and that is the slow case on exactly the most common requests. Memory use is also high, with a pointer per character.
Approach C: precompute the top-K for every prefix
Walk the trie once, offline, and store at every node (every prefix) its five best completions. A query is then a single lookup: go to the prefix's node, return its stored list.
Good: a request costs one key lookup regardless of how many queries start with the prefix. Latency is flat and tiny, and the table can be a plain hash map keyed by prefix, which is easy to cache, shard and replicate.
Bad: more storage (each node carries its top 5, the 30 GB above), and the lists go stale until the next build.
Diagram, as text
- Search logs leads to Count and decay
- Count and decay leads to Build prefix to top 5
- Build prefix to top 5 leads to Suggestion index
- Suggestion index leads to Serve by key
The recommended answer is C. The sentence to say: "I move the work from query time to build time, because the build has hours and the query has twenty milliseconds." Then handle the cost: store only prefixes above a frequency threshold and cap length at 20 characters.
The second decision: staying fresh
A table rebuilt nightly is wrong the moment something happens in the world. A hurricane name, a product launch or a breaking story can go from nothing to the top query in minutes.
Batch for the base, a stream for the new. Rebuild the full table on a schedule (hourly or daily) from a long window with decayed counts, which gives stable, well-ranked suggestions. Run a streaming job beside it that counts queries over the last few minutes. A query whose recent rate jumps far above its baseline is written to a small trending overlay.
Merge at read time. The API reads the base list for the prefix and the overlay list, and merges them by score. The overlay is tiny, so it fits in memory on every API node, and a trending query appears within a minute or two. The same idea, windowed counting over a stream, is covered in stream processing and developed in the top-K trending page.
Rank by more than count. Raw frequency favors old, long-standing queries. Blend popularity, a decay on old counts (halve the weight every week), and a small boost for recency. Do not personalize in the first design.
Blocklist at both ends. A removed query must be filtered from the build, and also at serve time, because a build can be hours old. Check each suggestion against the blocklist before returning it, and purge caches when an entry is added.
Bottlenecks and failures
Hot prefixes. One or two-letter prefixes are requested constantly. Cache them at the CDN with a TTL of a few minutes, and keep them in an in-process cache on every API node, so they almost never reach the index. Since a one-letter prefix has only 26 or so values, it can be fully precomputed and pinned.
Request storms from typing. A user typing a ten-letter query could cause ten requests. The client waits 100 to 150 ms after the last keystroke (debounce), cancels the previous request when a new key arrives, and skips the request when the prefix is already in its local cache. That cuts the request volume severalfold, and is usually the cheapest optimization.
Index node failure. Replicate each shard on at least two nodes. If the index is down, the API serves the CDN or cache content it has and returns an empty list otherwise. The search box must keep working without suggestions.
A bad build. A pipeline bug can produce a table of empty or garbage lists. Build into a new versioned table, run sanity checks (size, a sample of known prefixes, no blocked terms) and switch the alias only if they pass. Keep the last good version for fast rollback.
Abuse and manipulation. Scripts can search a phrase millions of times to push it into suggestions. Count each user (or IP) at most a few times per query per day, and filter low-diversity spikes.
Cache staleness. A blocklisted query can still be in a CDN copy for its TTL. Keep CDN TTLs short for sensitive prefixes, and send a purge when you block something.
Trade-offs to name aloud
- Precomputing every prefix: about 30 GB of storage, in exchange for a flat, single-lookup latency.
- Batch plus overlay: two systems, in exchange for stable rankings and a fresh trending layer.
- A frequency threshold: rare queries are never suggested, in exchange for a table a tenth of the size.
- Caching at the CDN: staleness of a few minutes, in exchange for taking most traffic off the origin.
- No personalization at first: less relevant for returning users, in exchange for a cacheable, shared answer.
What interviewers listen for
- A working answer: a trie or prefix index, ranked by query frequency, behind an API with a cache.
- A strong answer: precomputes top-K per prefix and says why querying the subtree is too slow, builds from logs offline and uses client debouncing and caching.
- A standout answer: also shards by hashed prefix and explains the skew trap, merges a streaming trending overlay with the batch table, blocklists at build and serve time and has a versioned, verifiable rollout of each build.
Check your understanding
Common mistakes
Treating it as a search problem. Autocomplete does not search documents. Reaching for Elasticsearch and an inverted index as the main idea misses that the answer can be precomputed by prefix.
Computing top-K at query time. It works in a demo and fails on the short prefixes that dominate traffic.
Sharding by first letter. It is the intuitive choice and it creates hot shards. Hash the prefix.
Ignoring freshness. A nightly batch alone misses everything that happened today. Name the streaming overlay.
Forgetting the client. Debounce, cancellation and local caching often do more for load than any server change, and they are free.
Forgetting takedowns. Autocomplete can surface things that cause real harm. A blocklist checked at build and serve time, plus cache purges, is part of the design, not an afterthought.
Practice
A major news event begins, and within five minutes a new query is among the most searched terms, but your table is rebuilt hourly. How do you get it into suggestions within about two minutes?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
You do not need to rebuild everything. Only a few queries are changing.
Show a strong answer
Detect the spike. A streaming job counts each query over one-minute windows and compares it with the query's usual rate. A term with a rate 50 times above its baseline is flagged as trending.
Write it to a small overlay. Store the trending queries and their prefixes (a few thousand entries) in memory or a small fast store, updated every minute. For each prefix of the trending term, record the term and its current score.
Merge at read time. The API reads the base list and the overlay for the prefix, merges by score and returns the top five. The overlay costs one extra in-memory lookup.
Guard against abuse and mistakes. Require a minimum number of distinct users (not only a high count) before a query can enter the overlay, and apply the blocklist, since fast paths bypass review.
Let the batch absorb it later. The next hourly rebuild includes the term in the base table, and the overlay entry expires.
The pattern worth keeping: keep a slow, thorough path for the bulk and a small fast path for what changed.
Legal requires that a specific phrase disappear from all suggestions within five minutes, worldwide. How do you do it?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
List every place the phrase can be stored or cached.
Show a strong answer
List the copies. The phrase exists in the current index version, in the Redis prefix cache, in CDN edge caches, in each API node's in-process cache and in the next build's input.
Add it to the blocklist first. The blocklist is read by the API at serve time (refreshed every few seconds), so every suggestion is filtered against it before being returned. That alone removes the phrase from responses within seconds, whatever cached copies hold.
Purge the caches. Send a purge for the affected prefixes to the CDN, and delete the keys in Redis. A short CDN TTL on sensitive prefixes limits how long a stale copy can survive if a purge fails.
Fix the source. Exclude the phrase from the build so the next index version does not bring it back, and delete or flag it in the query counts.
Verify and record. Run a check across regions that the phrase no longer appears, and keep an audit record of when it was added and when it vanished.
The pattern worth keeping: enforce removals at the last step before the user, and treat every cache and every rebuild as a way for the data to come back.
Key takeaways
- Autocomplete is a lookup by prefix, not a search. Do the ranking before the request.
- Precompute the top five for every prefix and serve it with one key lookup.
- Hash the whole prefix to shard evenly, since first-letter sharding makes hot shards.
- A batch table plus a streaming overlay gives stable ranking and fresh trends.
- The client matters: debounce, cancel and cache before adding servers.
- Enforce blocklists at serve time and purge every cache.
Further reading
- C. Manning, P. Raghavan and H. Schütze, "Introduction to Information Retrieval" (Cambridge University Press, 2008): prefix and wildcard indexing, tries and query processing.
- Elasticsearch Reference, "Suggesters": the completion suggester and its in-memory data structure.
- Redis documentation, "Sorted sets": a common structure for ranked lists of suggestions.