Search autocomplete (often called typeahead) is one of the most noticeable features of modern applications. Whether you are searching on Google, shopping on Amazon, or looking for a movie on Netflix, the search bar predicts what you are typing in real-time.
While it seems simple on the surface, designing a system that can return highly relevant suggestions in under 50 milliseconds, while handling hundreds of thousands of queries per second, is a classic and challenging system design interview question. In this article, we will break down how to design a search autocomplete system from scratch.
Requirements (functional and non-functional)
Before jumping into the architecture, we must clarify the scope with the interviewer.
Functional requirements
- Prefix matching: Given a partial search query (a prefix), the system should return a list of complete search queries that start with that prefix.
- Top $k$ suggestions: The system should return a limited number of suggestions (e.g., $k = 5$).
- Popularity ranking: The suggestions must be ranked by historical search frequency or popularity.
- Spell check / Typo tolerance (Stretch goal): The system should handle minor typos.
Non-functional requirements
- Ultra-low latency: This is the most critical requirement. Suggestions must appear instantly as the user types. The system's response time should be under 50ms.
- High availability: If the autocomplete service goes down, it should not break the core search functionality, but the service itself should be highly available.
- High throughput: The system must handle a massive volume of read requests, as every keystroke potentially triggers an API call.
- Eventual consistency: It is acceptable if a newly trending search term takes a few minutes or hours to appear in the autocomplete suggestions.
Capacity estimates
Let's establish some concrete numbers to understand the scale of our system. We will assume we are building this for a large-scale platform like Google or Amazon.
- Daily Active Users (DAU): 100 million.
- Searches per user: Assume each user performs 10 searches per day. That gives us 1 billion searches per day.
- Keystrokes per search: Assume an average search query is 20 characters long.
- Read QPS (Queries Per Second): If a client sends a request for every keystroke, we have 1 billion searches * 20 keystrokes = 20 billion requests per day.
- Average QPS = 20 billion / 86,400 seconds ≈ 230,000 QPS.
- Peak QPS = Average QPS * 2 ≈ 460,000 QPS.
- Storage estimates: We only need to store unique search queries and their frequencies. Out of 1 billion daily searches, let's assume 20% (200 million) are unique. If the average query is 20 bytes (20 characters), the raw string data is 200 million * 20 bytes = 4 GB. Even with the overhead of a data structure (like a Trie), the entire dataset can easily fit into the RAM of a single modern server (which often has 128GB to 256GB of memory).
API design
We need a simple, read-heavy API for the clients to fetch suggestions.
GET /v1/autocomplete?q={prefix}&limit={k}
Parameters:
q(string): The prefix the user has typed so far (e.g., "sys").limit(integer): The maximum number of suggestions to return (e.g., 5).
Response:
{
"prefix": "sys",
"suggestions": [
"system design",
"systemctl",
"system preferences",
"system of a down",
"system administrator"
]
}Data model
We need two distinct data models: one for durable storage (the source of truth for query frequencies) and one for fast in-memory retrieval.
1. Durable Storage (Frequency Database)
We need to store the historical frequency of every search query. A simple NoSQL database (like Cassandra or DynamoDB) or even a relational database (like PostgreSQL) works well here because the schema is incredibly simple.
| Column Name | Data Type | Description |
|---|---|---|
query | VARCHAR | The complete search query (Primary Key) |
frequency | BIGINT | The number of times this query was searched |
updated_at | TIMESTAMP | Last time this record was updated |
2. In-Memory Storage (The Trie)
Relational databases use B-Trees, which are great for exact matches but too slow for prefix matching across millions of rows at 460,000 QPS. To achieve sub-50ms latency, we must store the data in memory using a Trie (Prefix Tree).
High-level architecture
The architecture is split into two distinct paths: the Read Path (fetching suggestions instantly) and the Write Path (gathering analytics and building the Trie offline).
The Read Path
- The user types a character, and the client sends a request to the Load Balancer.
- The API Gateway routes the request to the Autocomplete Service.
- The Autocomplete Service queries its local in-memory Trie (or a distributed cache like Redis) to find the top 5 suggestions for the prefix.
- The suggestions are returned to the client.
The Write Path
- When a user actually hits "Enter" or clicks a search button, the full search query is logged.
- These logs are streamed into a message broker like Kafka. (See message queues for more details).
- A stream processing framework (like Apache Spark or Flink) aggregates the frequencies of these queries over time.
- The aggregated frequencies are saved to the Frequency DB.
- A background worker (Trie Builder) periodically reads the DB, constructs a new Trie, and saves a serialized snapshot to an Object Store (like AWS S3).
- The Autocomplete Service periodically pulls the latest Trie snapshot into memory.
Deep dives
Let's explore the most complex parts of this system.
1. Optimizing the Trie Data Structure
A standard Trie stores characters in nodes. To find the top 5 suggestions for a prefix, you would have to:
- Traverse the Trie to find the node representing the prefix (Time: $O(p)$, where $p$ is prefix length).
- Perform a Depth-First Search (DFS) from that node to find all valid leaf nodes (complete queries) (Time: $O(c)$, where $c$ is the number of nodes in the subtree).
- Sort the retrieved queries by frequency and return the top 5 (Time: $O(n \log n)$, where $n$ is the number of valid queries).
This is too slow for a read-heavy system. To optimize this, we trade space for time. We cache the top $k$ queries at every single node in the Trie.
With this optimization, finding the top 5 suggestions takes $O(p)$ time. We simply traverse to the prefix node and immediately return its cached list.
Here is how you would implement the optimized Trie node:
class TrieNode:
def __init__(self):
self.children = {} # char -> TrieNode
# Caches up to k (e.g., 5) tuples of (frequency, query)
self.top_queries = []2. Building and Updating the Trie
Since we cannot update the Trie in real-time, we rebuild it offline.
- Batch Processing: Every hour (or day), the Trie Builder worker fetches the latest frequencies from the database.
- Construction: It builds a brand new Trie in memory. As it inserts words, it updates the
top_querieslist at each node. - Serialization: Once built, the Trie is serialized into a binary format or a mapped file and uploaded to S3.
- Deployment: The Autocomplete Service servers download the new file. To avoid downtime, they load the new Trie into memory alongside the old one, atomically swap the pointer to the new Trie, and then garbage collect the old one.
3. Scaling and Sharding the Trie
While we estimated our Trie would take ~10GB and fit on one machine, what if we expand globally and support multiple languages, pushing the Trie size to 100GB+? We need to shard the data across multiple servers.
Approach A: Shard by Prefix (Range Based) We could put all queries starting with 'a' through 'm' on Server 1, and 'n' through 'z' on Server 2.
- Pros: Simple routing. We know exactly which server to query.
- Cons: Severe data imbalance and hot spots. The letter 's' starts vastly more words than the letter 'x'. Server 's' will crash under the load.
Approach B: Shard by Hash of the Query We hash the complete query and distribute it evenly across servers.
- Pros: Perfectly even data distribution.
- Cons: To find suggestions for the prefix "sys", we don't know which server holds the completions. We would have to query all servers, get the top 5 from each, and merge them at the API Gateway (Scatter-Gather pattern). This increases latency.
The Optimal Solution: Hybrid Sharding with a Mapping Service We shard by prefix, but we dynamically allocate shards based on data size. We use a configuration manager (like Zookeeper) to maintain a mapping table. For example, if 's' is too large, we split it: 'sa' to 'sm' goes to Server 1, 'sn' to 'sz' goes to Server 2. The API Gateway caches this mapping table and routes requests directly to the correct shard.
Bottlenecks and trade-offs
Client-side optimizations
Sending a network request for every single keystroke is incredibly wasteful. We must implement client-side optimizations:
- Debouncing: The client should wait for the user to pause typing for a short duration (e.g., 50ms) before sending a request. If the user types "s-y-s" rapidly, only one request for "sys" is sent.
- Local Caching: The browser/app should cache previous results. If the user types "sys", deletes the 's', and types 's' again, the client should use the cached result instead of hitting the backend.
- Connection Keep-Alive: Establishing a new TCP/TLS connection for every keystroke adds massive latency. The client must use HTTP Keep-Alive or WebSockets to reuse the same connection.
Data Staleness vs. Compute Cost
Our offline pipeline means trending searches (e.g., a sudden news event) won't appear in autocomplete for an hour. If real-time trending is a strict requirement, we must introduce a secondary, smaller "Trending Trie" that is updated in near real-time (using a stream processor like Flink) and merge its results with the main Trie at read time. This trades compute cost (merging lists on the fly) for data freshness.
Questions an interviewer will ask next
1. How would you handle typos? Answer: We can implement typo tolerance by traversing the Trie using algorithms that allow for a certain Levenshtein distance (edit distance). Alternatively, we can use phonetic hashing algorithms (like Soundex) to map misspelled words to their correct phonetic equivalents before querying the Trie.
2. How do you personalize suggestions for different users? Answer: We can maintain a small, user-specific Trie or database on the client-side or in a fast cache (like Redis) containing the user's past searches. When a query is made, the API Gateway fetches the global top 5 and the user's personal top 5, merging them and giving higher weight to the personal history.
3. How do you prevent offensive words from showing up? Answer: We introduce a filtering step in the Write Path. Before the Trie Builder worker constructs the Trie, it checks every query against a blocklist of offensive terms. If a match is found, that query is simply excluded from the Trie entirely.