InterviewDryRun
Lesson 9 · 22 min video · free

Design Search Autocomplete

Every keystroke in a search box asks for the best ten completions of what you have typed so far, and the answer must come back before the next keystroke. This lesson designs type-ahead suggestions for millions of users: a trie with the top results cached at every node, built offline from query logs, served from memory, and kept fresh for queries that start trending.

What you will learn

  • The latency budget is tens of milliseconds per keystroke, so serve from memory only.
  • Store the top suggestions at every trie node so a lookup is one walk down the prefix.
  • Build the trie offline from aggregated query logs and swap it in atomically.
  • Shard by prefix with care, and replicate heavily: this is a read-only, read-heavy service.
  • Blend a small real-time layer on top for trending queries.
  • Filter offensive and dangerous suggestions before they ever reach the index.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The API
  5. Step 4: The trie, with answers cached
  6. Step 5: Fitting the trie in memory
  7. Step 6: Building it from query logs
  8. Step 7: Serving suggestions
  9. Step 8: One search, keystroke by keystroke
  10. Step 9: When it does not fit on one machine
  11. Step 10: Freshness and trending queries
  12. Step 11: Personalisation and typos
  13. Step 12: Failures and operations
  14. Step 13: The follow-up questions
  15. Recap

Short on time? Read the answer outline for design Search Autocomplete.

Practice this question with Max

The question

Welcome to lesson nine of the InterviewDryRun system design course. Today we design search autocomplete, also called type-ahead: the list of suggestions that appears under a search box as you type, and changes with every letter.

It is a great interview question because it is small enough to finish, but it combines several ideas that come up everywhere: a clever data structure, a strict latency budget, an offline pipeline that builds data and an online service that serves it, and the tension between fresh results and fast results. And everyone has used it, so you can reason from experience about what good looks like.

Max asks

“Design the type-ahead suggestions for a search box used by millions of people.”

That is how Max, our AI interviewer, asks it. Short and open. That means you will need to set the scope yourself: what kind of search, what makes a suggestion good, and how fresh it has to be. Doing that well, early, is half the score on this question.

The plan: requirements and the latency budget, then sizing and the API. Then the core data structure, the trie with cached top suggestions. Then how we build it from query logs, how we serve it, how we shard and replicate it, how we keep it fresh, and how we filter and personalise. Then the follow-up questions.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    Suggest completionsTop 10 for the typed prefix
  2. 02
    Ranked by popularityHow often people searched it, weighted to recent
  3. 03
    Prefix matchStarting letters; typo tolerance as a stretch
  4. 04
    One language firstThen many, each with its own index
  5. 05
    SafeNo offensive or harmful suggestions

Start with questions.

We return the top ten completions for whatever has been typed so far. Ask what top means. The usual answer is popularity: how often people searched for that full query, weighted towards recent searches so that last year's news does not dominate.

Ask whether we match only from the start of the query, or anywhere, and whether we fix typos. A good scope is prefix matching for the core design, with typo tolerance mentioned as an extension. And ask about languages: design for one, and say how many would work, with a separate index per language or region.

And safety. Suggestions are words we put in front of users, unprompted. A suggestion that is offensive, defamatory or dangerous is a real problem for the company, even if many people typed it. So filtering is a requirement, not an extra. Interviewers notice when candidates raise it unprompted.

Non-functional requirements
  1. 01
    Very fastUnder 50 ms server time; users type 5 to 10 keys a second
  2. 02
    Highly availableIf it fails, the search box still works
  3. 03
    ScalableHundreds of thousands of requests a second
  4. 04
    Fresh enoughTrending queries within minutes; the rest daily

The qualities. Speed above everything: people type five to ten characters a second, so a suggestion that takes two hundred milliseconds arrives after the next keystroke and is useless. Aim for under fifty milliseconds on the server, and under a hundred end to end.

Availability is softer here. If autocomplete fails, the user can still type their whole query and press enter. So it should degrade gracefully: if a request is slow, show nothing rather than make the user wait.

And freshness: ask how quickly new queries must appear. A good answer is two speeds. The bulk of suggestions can be rebuilt daily or hourly. But when something suddenly trends, a breaking news event, it should appear within minutes. That two-speed requirement will shape the whole architecture.

Step 2: Back-of-the-envelope estimates

Sizing it
Searches a day1 billionfrom about 100 million users
Keystrokes per searchabout 6 requestsafter debouncing on the client
Suggestion requests6 billion / dayabout 70,000 a second
Peakabout 200,000 / sevenings and big news
Distinct queries keptabout 100 millionthe popular head
Index sizetens of GBfits in memory per server

Let us size it.

Say a billion searches a day. Each search is typed a letter at a time, and if the client sends a request for every keystroke, that could be fifteen requests per search. With a small client-side delay, sending only when the user pauses for a few tens of milliseconds, and skipping very short prefixes, it is about six. So six billion suggestion requests a day, seventy thousand a second on average, around two hundred thousand at peak.

How much data do we need to serve? Not every query ever typed: most are typed once and never again. Keep the popular head, say a hundred million distinct queries that were searched more than a few times.

A hundred million queries at around twenty to thirty bytes each, plus the trie structure and cached results, comes to tens of gigabytes. That is the key insight from the numbers: the whole index can fit in the memory of a single large server. So we can serve every request from memory, and scale reads simply by adding replicas.

Notice also how cache-friendly the traffic is. Prefix popularity follows a steep power law: a few thousand short prefixes, like single letters and common two and three letter starts, account for a large share of all requests. Those answers are identical for everyone in a region, so edge caches and browser caches can absorb a big part of the two hundred thousand requests a second before they reach our servers. Say that the server fleet is sized for the long tail of longer, rarer prefixes.

Step 3: The API

API
GET /v1/suggest?q=how%20to%20bo&lang=en&limit=10
→ 200 Cache-Control: max-age=300
  { "q": "how to bo",
    "suggestions": [
      "how to boil eggs",
      "how to boost wifi signal",
      "how to book a train ticket", ... ] }

The API is a single GET: the prefix, the language and a limit. The response is a list of suggestions. Two details matter.

First, the response is cacheable. Many people type the same prefixes, and the answer for a given prefix changes slowly, so set a cache lifetime of a few minutes. Browsers, content delivery network edges and our own servers can all reuse answers. For short, popular prefixes like t, h, or ho, almost every request will be served from a cache before it reaches us.

Second, the client matters as much as the server. It should debounce, waiting until the user pauses briefly before sending. It should cancel requests that are no longer needed when the user types another letter. And it should cache answers locally, so pressing backspace shows the previous suggestions instantly. Clients can even filter locally: if the suggestions for how to b are already on the screen, the suggestions for how to bo are often a subset of them.

Step 4: The trie, with answers cached

A trie with top suggestions at each node
STORE(root)CACHEhtop: how to..., hotels...CACHEhotop: how to..., hotels...CACHEhowtop: how to boil eggs...CACHEhottop: hotels near me...CACHEwtop: weather...

Now the core data structure. A trie, or prefix tree, stores strings by their characters: the root has a child for each first letter, each of those has a child for each second letter, and so on. Every prefix is a node, and every query is a path from the root.

To find completions of a prefix, walk down the tree, one node per character, which takes time proportional to the prefix length, a handful of steps. Then the naive approach is to explore everything below that node, collect all the complete queries, and sort them by popularity.

But below a short prefix like h, there are millions of queries. Exploring and sorting them on every keystroke would be far too slow. So here is the key optimisation, and the thing interviewers want to hear: store the answer at each node. Every node keeps a small list of its top ten completions, already sorted. A request becomes: walk down the prefix, read the list, return it. A few microseconds.

The cost is memory and build time: every node holds ten references, and when popularity changes, the lists of all ancestors may need updating. That is exactly why we build the trie offline, from aggregated data, rather than updating it on every search. Store references to queries, not copies of the strings, to keep memory down.

One more memory trick worth naming: compress chains of nodes with a single child into one node with a longer label. This is called a radix tree, and it can shrink the number of nodes many times over, because long queries share long unbranching tails. If the interviewer asks how to make the trie smaller, this is the first answer.

Is a trie the only option? No. A simpler alternative is a key-value map from every prefix, up to some length, directly to its top ten list. It uses more memory, because every prefix is stored in full, but it can sit in any key-value store and be served by any cache. For an interview, explain the trie, then mention the prefix map as the practical shortcut. Both serve the same answers.

Step 5: Fitting the trie in memory

Memory, roughly
Queries kept100 millionaverage 25 characters
Query stringsabout 2.5 GBstored once, referenced by id
Trie nodesa few hundred millionfewer with a radix tree
Top lists10 ids per node4 bytes each
Totaltens of GBone large server's memory

Interviewers often ask whether the trie really fits in memory, so be ready to estimate it.

A hundred million queries of about twenty-five characters is about two and a half gigabytes of text. Store each string exactly once, in one big array, and refer to queries by a four-byte number everywhere else.

The trie has a few hundred million nodes before compression, far fewer as a radix tree. Each node stores its children and a top list of ten query numbers, forty bytes. Multiply out and you land at tens of gigabytes. It fits in one large server, and it is worth saying that it is the top lists, not the strings, that dominate the memory.

Lay the whole structure out as flat arrays rather than millions of small objects, so it can be written to a file and memory-mapped by the servers directly. Loading a new version is then just mapping a new file, which takes seconds instead of minutes of parsing. That small engineering decision is what makes frequent snapshot swaps practical.

Step 6: Building it from query logs

Offline build pipeline
publishSERVICESearch servicelogs every queryQUEUEQuery logstream of eventsWORKERAggregation jobcounts per query, decayedWORKERFilterssafety, spam, PIIWORKERTrie buildertop 10 per nodeSTOREIndex snapshotsversioned files

Where do the popularity numbers come from? From what people actually search. Every completed search is logged as an event: the query text, the time, the language and region, but never anything that identifies the user in the aggregated data.

A batch job runs regularly, say every hour, and aggregates the logs into a count per query. Not a plain count, though: a decayed count, where each day's searches are worth a little less than the day after. That way, a query that was huge last year but nobody searches now slowly fades, while new popular queries rise.

Next, filters. Drop queries searched by too few distinct people, which removes typos and also anything private someone typed, like a phone number or an address. Drop or demote queries that match blocklists of offensive, hateful or dangerous terms. And remove spam: people try to manipulate autocomplete by searching for their product thousands of times, so count distinct users, not raw searches, and detect bursts from a few sources.

Finally, the trie builder takes the cleaned list of queries and scores, builds the trie, computes the top ten at every node, bottom up, and writes it out as a compact, versioned snapshot file. Building bottom up is efficient: each node's top ten is just the best ten among its own query and its children's top tens.

Separating the build from serving like this is a pattern worth naming: an offline pipeline builds an immutable artifact, and stateless servers load it. It makes serving simple and fast, and it makes mistakes reversible: if a new snapshot is bad, servers just load the previous version.

Step 7: Serving suggestions

The serving path
missloadblendCLIENTSearch boxdebouncedEDGECDN edgecaches popular prefixesSERVICESuggest serverstrie in memorySTOREIndex snapshotsCACHETrending layerlast hour

Now serving. The search box sends its debounced request, which first hits the content delivery network edge. Popular prefixes are answered right there, close to the user, in a few milliseconds.

Misses reach the suggest servers. Each one holds the entire trie in memory, for its language, and answers by walking the prefix and returning the stored list. No database, no network call in the hot path.

Servers load new snapshots as they are published. Each server downloads the new file in the background, builds or maps it into memory next to the old one, and then switches over with a single pointer swap. Requests in flight finish on the old version, new ones use the new. No downtime, no half-loaded state. Then the old version is freed.

And a small trending layer, which we will look at in a moment, is blended in for freshness. Because every suggest server holds the full index and has no state of its own, scaling to two hundred thousand requests a second is just a matter of adding replicas behind a load balancer, in every region.

And keep the servers boring on purpose. A suggest server does one thing: walk a structure in memory and return a list. It has no database connections to exhaust, no locks, no writes. That is why a single server can answer tens of thousands of requests a second, and why, when something does go wrong, the problem is almost always in the data it was given rather than in the server itself.

Step 8: One search, keystroke by keystroke

Typing how to boil
TypedWhat happensServed from
htoo short, client waitsnothing sent
horequest after a 50 ms pauseCDN edge, cached
how trequestCDN edge, cached
how to brequestsuggest server
how to boclient filters its last list firstbrowser, then server
entersearch runs, query is loggedsearch service

Let us put all of this together by following one user typing how to boil, keystroke by keystroke. Walking through a concrete example like this is one of the best ways to show an interviewer that the parts fit.

The user types h. Single letters are so ambiguous that many products do not even ask the server; the client waits. Then o: the user pauses for a fraction of a second, so the client sends a request for ho. Millions of people type ho every day, so the content delivery network edge has the answer cached and returns it in a few milliseconds.

Then how space t, and how to b. The shorter prefixes are still edge hits, but as the prefix gets longer and more specific, the edge is less likely to have it, and the request reaches a suggest server, which walks its in-memory trie and replies in about a millisecond, plus network time.

As the user types o, the client immediately filters the list it already has for how to b, showing only those that start with how to bo, so the screen updates instantly while the real request is in flight. When the user picks how to boil eggs and presses enter, the search runs, and the search service logs the query. That log entry will feed tonight's build, closing the loop. Every piece we designed played its part in under a second.

Step 9: When it does not fit on one machine

Sharding options
Split byGoodProblem
Language or regionnatural, independentstill big for the largest language
First lettersimpleuneven: far more queries start with s than x
Prefix ranges by loadevenneeds a routing map
Hash of the prefixevenevery prefix length goes elsewhere: fine for prefix maps

We estimated tens of gigabytes, which fits in memory. But suppose the interviewer says: add many more languages, long-tail queries and more metadata, and now it does not fit. How do we split it? The first split is natural: one index per language or region, served by separate server groups.

If one language is still too big, split by prefix. Splitting by first letter is the obvious idea, but it is very uneven: far more queries start with s or c than with x or z. So the interviewer will push back.

A better approach is to split by prefix ranges sized by actual traffic and data: a to c on one shard, d to f on another, maybe several shards just for s. A small routing map, built along with the index, tells the front end which shard owns which range. Each shard is replicated many times for throughput.

If we use the simpler prefix map instead of a trie, we can just hash the prefix to choose a shard, because each prefix is an independent key. That is one of the practical advantages of the prefix map. Either way, say that reads vastly outnumber everything else, so replicas are the main scaling tool and shards are only for size.

Step 10: Freshness and trending queries

Two speeds
  1. 01
    Batch indexRebuilt hourly or daily; stable, filtered, big
  2. 02
    Trending layerStreaming counts over the last hour
  3. 03
    BlendMerge trending candidates into the top 10 by score
  4. 04
    Guard railsTrending items need stricter filters and a minimum of users

Batch builds give us stable, filtered suggestions, but hourly at best. When a major event happens, people expect to see it in suggestions within minutes. So we add a second, faster path.

A streaming job reads the same query log and keeps counts over a sliding window, say the last hour, for queries that are growing fast compared with their usual level. It keeps only a small set of trending queries, thousands rather than millions, with their prefixes, in a small in-memory store.

At serving time, the suggest server takes the batch top ten for the prefix, looks up trending candidates for the same prefix, and merges them by score, so a sudden surge can push a new query into the list. Because the trending set is small, this adds almost no latency.

And be careful: the fast path is where manipulation and embarrassing mistakes happen, because there is less time for review. So trending items need stricter filters, a higher minimum number of distinct users, and a quick way for a human to remove a suggestion everywhere within minutes. Say that you would build that kill switch on day one.

Step 11: Personalisation and typos

Making suggestions better
  1. 01
    Your own historyRecent searches first, stored on the device or per user
  2. 02
    LocationIndex per region for local results
  3. 03
    Typo toleranceTry close prefixes when results are thin
  4. 04
    Re-rankingCombine popularity with personal signals

Personalisation is a common extension. The simplest and most effective version is the user's own recent searches: show the ones that match the prefix first. They can be stored on the device, or in a small per-user store, and merged with the global list at serving time.

Location helps a lot too: someone in one city typing pizza wants local places. Rather than personalising per user, keep indexes per region, so suggestions reflect what people nearby search for.

Typos: if the prefix has few or no results, try nearby prefixes, ones that differ by a single character, and merge their suggestions. A full fuzzy search on every keystroke is expensive, so only fall back to it when the exact prefix is thin. Mention it as an extension; it is rarely the focus.

For deeper personalisation, take the top fifty from the index and re-rank them with personal signals, like topics the user often searches for. It is the same two-stage idea as feed ranking: gather candidates cheaply, then score a small number carefully.

Step 12: Failures and operations

What can go wrong
  1. 01
    Bad snapshotValidate before publishing; roll back by version
  2. 02
    Server slowClient times out and shows nothing
  3. 03
    Pipeline stallsKeep serving the last good snapshot
  4. 04
    Offensive suggestionGlobal block list checked at serving time

What can go wrong? A bad snapshot, say the build job read only half the logs, would serve strange suggestions everywhere at once. So validate snapshots before publishing: compare size, top results for common prefixes and overall scores with the previous version, and refuse to publish if they differ wildly. Roll out new snapshots to a few servers first.

If a suggest server is slow, the client has a strict timeout and simply shows no suggestions. The user keeps typing. This is one of the rare systems where showing nothing is a perfectly fine failure mode, and you should say so.

If the pipeline stalls, servers keep serving the last good snapshot, which might be a day old. That is acceptable for a while, and an alert tells us the snapshot age is growing.

And a suggestion that should never have appeared needs to disappear in minutes, not at the next build. So servers also check a small, frequently updated block list at serving time, and the trending layer can be switched off instantly. These are the operational controls that matter most for this particular product.

Step 13: The follow-up questions

Max asks

“Why not just query the search database with a LIKE prefix query?”

Because it is far too slow and expensive at this rate. A prefix query over a hundred million rows, sorted by popularity, two hundred thousand times a second, would need a huge database cluster and still miss the latency budget. Precomputing the top ten per prefix turns every request into a memory lookup. It is the core trade-off of the design: spend work and memory offline, so the online path does almost nothing.

Max asks

“How would you count how often each suggestion is clicked, and use it?”

Log suggestion impressions and clicks, with the prefix, as events through the same pipeline. The aggregation job can then compute a click-through rate per prefix and suggestion, and the score can blend search popularity with click-through. A suggestion that is often shown but never clicked gets demoted. That closes the loop between what users see and what they choose.

Max asks

“How big should the top list at each node be?”

A little larger than what we display, say twenty to fifty instead of ten. That gives room to filter out blocked items at serving time, to merge in personal and trending candidates, and to re-rank, while still always having ten good answers to show. The memory cost is modest, and it keeps the serving logic flexible.

Max asks

“How would you support suggestions that match a word in the middle of the query?”

Index each query under every word position, not just the start: the query best pizza near me is also inserted under pizza near me and near me, pointing back to the full query. The index gets several times bigger, so only do it for the popular head of queries. It is a classic example of trading memory for a richer, still instant, lookup.

Max asks

“How would you add autocomplete for a new language with very little search history?”

Start from other sources: titles of popular pages in that language, product names, place names, and translated versions of popular queries from similar markets. Build a first index from those with conservative filters, then let real query logs take over as they accumulate, blending the two by how much data we have. Until the language has enough distinct users per query, keep the privacy threshold high, because with few users, a rare query is more likely to be personal.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsTop 10 by prefix, popularity, safe; under 50 ms
  2. 02
    5 to 10: estimates and API200,000 a second; tens of GB; cacheable GET
  3. 03
    10 to 20: the trieTop results cached at every node
  4. 04
    20 to 35: build and serveOffline pipeline, filters, snapshots, replicas, shards
  5. 05
    35 to 45: fresh and safeTrending layer, personalisation, kill switch

On the clock: five minutes on requirements, including what top means and the safety requirement. Five minutes on the numbers, which show the index fits in memory, and on a cacheable API with a smart client.

Ten minutes on the trie with the top results cached at every node, and the prefix map as the practical alternative.

Fifteen minutes on the offline pipeline, from query logs through filters to versioned snapshots, and the stateless, replicated servers that load them. And the final ten minutes on freshness with a trending layer, personalisation, and the operational controls that keep bad suggestions off the screen. Offline work, online simplicity: that is the story to tell.

The trie is easy to draw. Explaining how it is built, kept fresh and kept safe, in order, under time pressure, takes practice. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson ten.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.