Skip to content

How to design search autocomplete

The first sections are free. The deep dives, level expectations and quiz are part of Pro.

On this page
Asked at
Practice this question

The problem

Search autocomplete watches a search box and, on each keystroke, shows the five queries searched most often that begin with the letters typed so far. The answer turns on two things. On the read side, a keystroke is a request, so the prefix tree lives in memory and each node already holds its five best completions, which makes a lookup a short pointer chase instead of a walk and a sort. On the data side, search logs are counted offline and a whole new tree is built and swapped in, so nothing on the request path writes.

Clarifying questions

AskWhy it mattersA typical answer

How many people search, how often, and does each keystroke go to the server?

The request rate is set by characters typed, not searches run. If the interviewer confirms a request per keystroke, the service is sized about twenty times larger than the search count suggests.

10 million daily users, 10 searches each of about 20 characters, and a request on each keystroke: about 24,000 requests per second on average and 48,000 at peak.

How fresh do suggestions have to be? Is a query from this morning expected to show up today?

Freshness decides whether the suggestion data is rebuilt weekly, each half hour, or fed by a stream. It is the single biggest fork in the data pipeline.

Keep suggestions current as new queries come in, but trending queries in real time are out of scope. A scheduled rebuild is acceptable; say how you would shorten the interval for a news site.

Is the ranking by popularity, or do spelling, personalization or location play a part?

Popularity on its own means one count per query and a prefix match. Spell correction or personalization would change the data structure and the request path.

Popularity, matching the start of a query. Spell check, personalization and other languages are out of scope.

How many suggestions, and how fast must they appear?

Five fixed slots let each node of the tree store its best completions ahead of time. The latency budget tells you how much of the lookup can afford to leave memory.

The top 5, within 100 ms, so the lookup comes from memory.

Do we need to remove an offensive suggestion quickly, and who decides?

A removal that waits for the next rebuild can leave a harmful suggestion visible for a week. If removal must be immediate, you need a filter on the request path, not just a cleaner dataset.

Yes. There is a POST /blocked-suggestions call, and a blocked query should stop appearing in new responses at once; copies already cached in browsers can linger until they expire.

What characters can a query contain?

A small lowercase alphabet keeps each node of the tree small and makes sharding by prefix range simple to reason about.

English, lowercase letters, no special characters. Normalize input at the API before the lookup.

The requirements menu

RequirementScopeWhy

Return the top 5 suggestions for the prefix typed so far

Core

The product. A fixed count of five is what lets each node of the tree carry its answers ahead of time.

Rank suggestions by how often each query was searched

Core

Popularity is the ranking signal, so the pipeline's job is counting searches per query, nothing fancier.

Match only the start of a query; no spell check

Core

Prefix matching is what a trie does well. Matching inside a query or correcting typos would need a different index, such as an inverted index or a fuzzy matcher.

Keep suggestions current as new queries come in

Core

New searches must reach the suggestions, which is why there is a pipeline from the logs to a rebuilt tree, and a question of how often it runs.

Never suggest offensive or unwanted queries

Core

Popular is not the same as acceptable. A removal has to take effect faster than a rebuild cycle, which forces a filter on the request path.

Debounce keystrokes in the browser so fast typists send fewer requests

Optional

Worth a sentence: it cuts requests at the source and costs nothing on the server. Leave the detail for a frontend round; here it is a lever on the request rate, not a design element.

Sample the search logs instead of writing each line

Optional

Take it if the interviewer presses on log volume: counting one line in N still ranks popular queries well. Leave it if freshness for rare, rising queries matters, because sampling hides them longest.

A separate suggestion set per country

Optional

Take it when the popular searches are different in each country, as they are on a global site. It also makes each tree smaller and lets you serve it near its users. Leave it for a single-country product.

Match words in the middle of a query, not only its start

Out of scope

A real feature on product search, but a tree keyed on whole queries does not answer it on its own. Name it, say it would need a different index, an inverted index for example, and move on.

Spell check and autocorrect

Out of scope

A typo-tolerant match is a different matcher with its own index. Say so and leave it.

Trending queries in real time

Out of scope

Out of the base design, but the interviewer's curveball. Have a two-sentence answer ready about a streaming count that favors recent searches.

Other languages

Out of scope

The base design assumes lowercase English. Other languages mean Unicode in the nodes and, in practice, a tree per language.

Personalised suggestions

Out of scope

Per-user ranking usually means a per-person signal, precomputed or looked up, and far more data. Keep the ranking global for this round.

Non-functional requirements

RequirementWhat it forces

Suggestions show within 100 ms

A short memory lookup per keystroke, with the blocklist check beside it, and no heavy work on the request path: the tree sits in memory with its five best completions stored at each node, so there is no subtree walk, no sort and no write. Prefix length is capped so the pointer chase has a bound.

10 million daily users, 24,000 requests a second on average

Size for keystrokes, not searches: about twenty requests per search. Stateless query servers behind a load balancer, each able to answer from memory, and a browser cache lifetime on responses so repeated prefixes are answered without a request.

Highly available

The tree is replicated on many query servers, so one failing takes no data with it. A new snapshot is loaded beside the old one and swapped in; a rebuild that fails leaves the old snapshot serving. The pipeline is off the request path, so a pipeline outage makes suggestions stale rather than absent.

English, lowercase, no special characters

A small alphabet: each node has at most one child per letter, which keeps nodes compact. Input is lowercased at the API before the lookup. Other languages would need Unicode in the nodes and a tree per language.

Estimates

QuantityWorkingResultWhat it sizes

Suggestion requests a second

10 million users × 10 searches × 20 characters = 2 billion keystroke requests a day; 2 billion ÷ 86,400 seconds ≈ 23,150, rounded to 24,000; peak taken as twice the average = 48,000

About 24,000 requests per second on average, 48,000 at peak

The query service fleet and the load balancer in front of it; the figure the design must answer within 100 ms.

Searches a second, the number that misleads

100 million searches a day ÷ 86,400 seconds ≈ 1,160, about 1,200; 24,000 ÷ 1,200 = 20 requests per search

About 1,200 searches per second, one twentieth of the request rate

What a candidate sizes for when they count searches instead of keystrokes: a service twenty times too small.

New query data

100 million searches a day × 20% new × 20 bytes = 400 MB a day; 400 MB × 365 days ≈ 146 GB a year

400 MB a day, about 146 GB a year of raw query strings before the tree's own overhead

How long a tree that keeps each query fits in one server's memory, and when pruning rare queries or sharding becomes necessary.

Browser cache lifetime in seconds

An hour = 60 minutes × 60 seconds = 3,600 seconds, the value in max-age=3600

3,600 seconds

How long a person can keep seeing a suggestion that has since been blocked or overtaken, since their browser answers from its own copy for that long.

Rebuilds a day and worst-case staleness

Each 30 minutes: 24 hours × 60 ÷ 30 = 48 builds a day; weekly: 7 days × 24 hours = 168 hours between a search and its earliest appearance in the worst case

48 builds a day for a news site, against a worst case of 168 hours for a weekly build

The work the build pipeline must finish inside its interval, and how stale a weekly build can leave the suggestions.

Core entities

EntityWhat it holds

Trie node

One node per prefix in the tree, holding its children and the five best completions beneath it, so a lookup ends at this node.

Query count

The aggregated row the pipeline produces: how many times a query was searched in one period.

Blocked suggestion

A query that must not be shown, written by POST /blocked-suggestions and read by the filter layer on each request.

Search log line

One line per search run, the raw input the aggregators count; it is not read on the request path.

The API

EndpointNotes

GET /autocomplete?q={prefix} → top 5 suggestions

Called on each keystroke. The service lowercases the prefix, cuts it at fifty characters, finds the node and returns its stored list after the filter drops blocked queries. The response carries Cache-Control: private, max-age=3600 so the browser reuses it for an hour; private keeps shared caches out. Fewer than five completions is a shorter list, not an error.

Search log line { query, timestamp } written for every search

Written by the search page when a search actually runs, not on keystrokes, so it carries about 1,200 lines a second rather than 24,000. Appended to a log, not read by the query service; aggregators read it later. Sampling one line in N is an option if volume becomes a cost.

POST /blocked-suggestions { query }

Inserts the query into the blocklist the filter layer reads, so it disappears from new responses at once; the next build drops it from the tree. Browsers that cached a response holding it may still show it until their copy expires.

The high-level design

prefixreadBrowserQuery serviceTrie in memory

Step 1 of 3

A query service reading a tree in memory

Start with the read path, because it carries the load. The browser sends GET /autocomplete?q=be on each keystroke to a query service, which follows the letters down a prefix tree held in memory and returns the five best completions stored at the node it reaches. Holding the tree in memory, and storing the answers at the nodes rather than computing them per request, is what makes 100 ms reachable at 24,000 requests per second. What is missing: nothing yet puts counts into the tree.

prefixreadcheckmisscountssnapshotrecentBrowser cacheLoad balancerQuery serviceFilter layerTrie in memoryBlocklistTrie storeSearch logsAggregatorsQuery countsTrie buildersStream job
The whole design

What breaks first

The deep dives

Answering a prefix fast. Someone types b, then e. How do five suggestions come back within 100 ms, what does that cost in space, and what does the service have to be sized for?

A concept that helps here: Tries and prefix searchA concept that helps here: Cache invalidation and TTLsA concept that helps here: Debounce and request cancellation

Building and updating the trie. A query nobody searched yesterday is searched all day today. How does it travel from the search log into the suggestions, how often, and what happens when a rebuild fails or a suggestion has to go at once?

A concept that helps here: Lambda and Kappa architecturesA concept that helps here: Stream processing and windowsA concept that helps here: Queues and logs

Sharding the trie. The suggestion data no longer fits in one server's memory. How do you split it so each part carries a fair share of the requests, and how does a request find its part?

A concept that helps here: Sharding and partition keysA concept that helps here: Hot keys and hot partitionsA concept that helps here: Replication and read replicas

Concepts this guide uses

Sources

  1. Alex Xu, System Design Interview, chapter fourteen: Design a search autocomplete system (book notes at books.dwf.dev)
  2. Google Search blog: How Google autocomplete works in Search
  3. Google Search blog: How Google autocomplete predictions are generated
  4. MDN Web Docs glossary: Debounce
Sign in to report a mistake