Design Search Autocomplete: Tries, Top-K and Offline Updates
How suggestions appear within milliseconds of each keystroke: a trie with precomputed top results per node, built offline from search logs and served from cache.
Search autocomplete, also called typeahead, suggests complete queries while the user is still typing. After two or three letters the most popular matching searches are already displayed.
A SQL query with LIKE 'prefix%' on a table of past searches gives the right result on a small dataset, but it cannot meet the latency requirement at scale. These notes describe the data structure and the pipeline that make autocomplete fast.
1. Requirements
- Functional: for a typed prefix, return the top 5 suggestions ordered by popularity.
- Non-functional: very low latency. Suggestions must feel instant, so the budget is roughly 100 ms end to end, which leaves only a few milliseconds for the lookup itself.
- Non-functional: high availability. If autocomplete is down, search must still work.
- Freshness: suggestions do not need to reflect searches made a second ago. Updating every few hours is acceptable (ask whether trending queries need faster updates).
- Workload: extremely read-heavy. Every keystroke is a read; the dataset changes slowly.
2. Scale estimation
Assume 10 million daily active users, 10 searches each, and about 10 keystrokes per search that could each trigger a request. That is 1 billion requests per day, or about 10,000 per second on average and 30,000 at peak. The traffic is higher than the search traffic itself, which is why reducing requests on the client and caching aggressively are part of the design.
3. Why a LIKE query is not enough
A prefix query can use a B-tree index, but the database still has to find every row that starts with the prefix and then sort them by popularity. For a short prefix such as 'i' that may be millions of rows. Doing this on every keystroke for thousands of requests per second is far too slow and too expensive.
4. The trie
A trie, or prefix tree, stores strings character by character. The root is empty. Each edge adds one character, so the node reached by following 'i', 'p', 'l' represents the prefix 'ipl'. All queries that share a prefix share the same path. Finding the node for a prefix of length L takes L steps, no matter how many queries are stored.
Reaching the node is fast, but collecting suggestions is not. Under the node for 'i' there may be millions of complete queries. Walking the entire subtree to find the five most popular ones is again too slow.
5. Precomputing the top K at every node
The key optimisation is to store, at each node, the top 5 suggestions for that prefix. The work of ranking is done when the trie is built, not when it is queried. A lookup becomes: walk down L nodes, return the list stored there. That is a few memory accesses.
This uses more memory, since each node carries a small list, and it makes updates more expensive, since changing one query's popularity may affect the lists of all its prefixes. Both costs are acceptable because the system is read-heavy and updates are done in bulk.
class TrieNode {
constructor() {
this.children = new Map(); // char -> TrieNode
this.top = []; // precomputed: [{ query, score }], max 5
}
}
function suggest(root, prefix) {
let node = root;
for (const ch of prefix) {
node = node.children.get(ch);
if (!node) return []; // no query starts with this prefix
}
return node.top; // O(length of prefix), no subtree scan
}6. Where popularity comes from
Popularity is derived from search logs. Every completed search is written to a log stream. Updating the trie on every search would mean a write for every query and constant changes to a structure that is being read at high volume.
Instead, the logs are processed offline. A batch job aggregates the logs every few hours and produces a table of query and frequency, usually with more weight given to recent days so that old trends fade. From that table a new trie is built, and the serving machines switch from the old version to the new one atomically. The serving path never modifies the trie, which keeps it simple and fast.
SERVING PATH (online, read-only)
Browser --debounce--> CDN / edge cache --> Autocomplete service --> In-memory trie
| (replicated, sharded)
+--> Redis: prefix -> top 5 (hot prefixes)
BUILD PATH (offline, every few hours)
Search service --> Search logs (Kafka) --> Aggregation job --> query frequency table
|
v
Trie builder --> trie snapshot (object storage)
|
v
Serving nodes load the new snapshot and swap7. Reducing the number of requests
Sending a request on every keystroke is wasteful, because a user typing quickly does not read suggestions for intermediate prefixes. The client applies debouncing: it waits until the user has paused for a short interval, for example 150 ms, before sending a request. Any request still in flight for an older prefix is cancelled or ignored.
The client also caches results for the session, so deleting a character shows the previous suggestions without a network call.
function debounce(fn, delayMs) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delayMs);
};
}
const fetchSuggestions = debounce(async (prefix) => {
const res = await fetch("/api/v1/suggest?q=" + encodeURIComponent(prefix));
render(await res.json());
}, 150);
input.addEventListener("input", (e) => fetchSuggestions(e.target.value));8. Caching
Autocomplete results are the same for everyone (ignoring personalisation) and change only when the trie is rebuilt. That makes them ideal for caching. Responses for a prefix carry a Cache-Control header so that the browser and the CDN can serve them. Short, popular prefixes receive most of the traffic and are answered at the edge without reaching the service at all.
9. Scaling the trie
The trie is replicated across several servers for availability and read throughput. If it does not fit in the memory of one machine, it is sharded by prefix: for example, queries starting with a to m on one group of servers and n to z on another.
A naive alphabetical split is uneven, because far more queries begin with 's' than with 'x'. The shard boundaries should be chosen from the observed distribution of queries, and a small mapping service records which shard owns which prefix range so that boundaries can be adjusted.
10. Additional considerations
- Trending queries: a separate streaming job can compute a small set of rapidly rising queries and merge them into results, without waiting for the batch rebuild.
- Typos: handled by a separate spelling-correction or fuzzy-matching component; a plain trie matches exact prefixes only.
- Filtering: offensive or unsafe suggestions are removed with a blocklist when the trie is built.
- Personalisation: the user's own recent searches are kept on the client or in a small per-user store and merged in front of the global results.
- Alternative: a search engine with completion suggesters, or precomputed prefix-to-results entries in a key-value store, follow the same principle of precomputation.
Interview summary
- Requirements: top 5 by popularity, very low latency, read-heavy.
- Data structure: a trie with the top 5 precomputed at every node.
- Updates: offline aggregation of search logs, periodic rebuild and atomic swap.
- Traffic reduction: client-side debouncing, browser and CDN caching of popular prefixes.
- Scale: replicate the trie and shard it by prefix according to the real distribution.
Summary
Autocomplete is fast because nothing is computed at query time. A trie finds the prefix in a few steps, each node already holds its top suggestions, popularity is calculated offline from logs, and debouncing and caching keep most requests away from the servers.
Puneet Tiwari
Full Stack Developer
