Type sys into a search box and, before you reach the next key, a list appears: system design, systemctl restart, sysco careers. Search autocomplete (typeahead) has to answer a new request on almost every keystroke, for every user, in well under 100 ms end to end. The design is a lesson in doing the expensive work ahead of time: an offline pipeline turns billions of logged searches into a compact trie with the top-k completions precomputed at every node, and the online path becomes a memory lookup served from replicas, CDN edges and the browser itself.
Think of it like
The index tabs of a well-run library
Imagine a card catalog where every drawer tab (s, sy, sys) already has a sticky note listing the five most-borrowed titles inside. A visitor never searches the drawer; they read the note. Overnight, a librarian recounts the checkouts and rewrites the notes. The notes are a little stale by evening, but reading them is instant, and that trade (precompute in the back office, read instantly at the desk) is the whole design.
1. Requirements
Functional
- Return the top 5 to 10 completions for the typed prefix
- Rank by popularity, with a boost for recent (trending) queries
- Support the major languages and Unicode input
- Never suggest offensive, illegal or policy-violating text
- Optional: blend in the user's own recent searches
Non-functional
- Fast: suggestions visible within ~100 ms of a keystroke (server p99 < 10 ms)
- Highly available: a failed suggestion is invisible, but a slow one feels broken
- Scales to tens of thousands of requests per second at peak
- Eventually fresh: new trends appear within minutes to hours, not instantly
- Cheap per request: most traffic should never reach an application server
| In scope | Out of scope |
|---|---|
| Prefix completion of whole queries | Full search results ranking (see Search Systems) |
| Popularity ranking with recency | Spell correction and fuzzy matching (mention as an extension) |
| Data collection and aggregation pipeline | Query understanding and entity linking |
| Filtering and light personalization | Ads in suggestions |
2. Back-of-the-envelope estimation
Assume 50 million daily active users, each running 8 searches a day. An average query is about 20 characters, but debouncing and client caching mean only about 6 suggestion requests reach the network per search. See Back-of-the-Envelope Estimation for the method.
Suggest requests
~28,000 /s
2.4B/day ÷ 86,400 s
Peak
~56,000 /s
2× average
Query log
~40 GB /day
400M searches × ~100 B
Trie in memory
~2.5 GB
10M queries, top-10 per node
3. API and data model
GET /v1/suggest?q=sys&lang=en®ion=us&limit=8 HTTP/1.1
Host: suggest.example.com
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: public, max-age=300
Vary: Accept-Encoding
{
"q": "sys",
"version": "2026-11-06T04:00Z",
"suggestions": [
{ "text": "system design", "type": "query" },
{ "text": "systemctl restart", "type": "query" },
{ "text": "sysco careers", "type": "query" }
]
}- GET with the prefix in the URL makes responses cacheable by browsers and CDNs. Normalize
qfirst (lowercase, trim, collapse spaces, Unicode NFKC) soSysandsysshare one cache entry. - No user id in the URL for the global list: personalized results would make every response uncacheable. Personal history is blended in on the client or by a separate call.
versionidentifies the trie snapshot that served the response, which helps debugging and lets the client discard results from an older build.
| Dataset | Key | Contents | Store and why |
|---|---|---|---|
| Query log | (date, hour) | normalized query, user locale, region, timestamp, clicked? | Kafka, then Parquet in object storage: append-only and huge |
| Daily counts | (query, day, lang) | count, distinct users | Columnar table (data warehouse): scanned in bulk, never point-read |
| Scored queries | (lang, query) | decayed score, flags | Build input, rewritten each run |
| Trie snapshot | (lang, version) | serialized trie, checksum | Object storage (Blob & Object Storage): immutable, versioned, easy rollback |
| Blocklist | pattern | reason, added by, expiry | Small relational table, pushed to every server |
4. High-level architecture
The system splits cleanly into an online serving path (top) that must be fast and an offline pipeline (bottom) that may be slow but must be correct. They meet only at the snapshot store. Press play to follow a request and a rebuild.
5. Deep dive: a trie with top-k at every node
A plain Tries (Prefix Trees) answers "which stored strings start with sys?" by walking to the sys node and exploring its whole subtree. The simulation above shows exactly that walk. For autocomplete the subtree under s holds millions of queries, so collecting and sorting them per keystroke is far too slow. The fix is to store the answer in the node.
(root)
└─ s top: [system design 980, spotify 870, sql join 610]
├─ p top: [spotify 870, spotify web 220]
├─ q top: [sql join 610, sqlite 300]
└─ y top: [system design 980, systemctl restart 400, sysco careers 150]
└─ s top: [system design 980, systemctl restart 400, sysco careers 150]
├─ c ... sysco careers
└─ t ... system design, systemctl restartSearch the subtree per request
- Lookup: walk p characters, then visit every node below: O(p + n), plus a heap for top-k
- n can be millions for 1 to 2 character prefixes
- Small memory footprint
- Fine for tiny dictionaries, hopeless at web scale
Precomputed top-k per node
- Lookup: walk p characters, read a list: O(p), independent of n
- Memory: k ids per node (k = 10 ids × 4 B = 40 B)
- Updates are expensive: one score change can touch every ancestor
- Perfect for a read-only snapshot rebuilt offline
- 1
Sort the input by score, highest first
The builder receives (query, score) pairs from the aggregation job and sorts them once: O(m log m) for m queries.
- 2
Insert in that order
Walk each query's path, creating nodes as needed. At every node on the path, append the query to the node's list only if it holds fewer than k entries. Because higher scores arrive first, the first k arrivals are exactly the top k. No heap, no re-sorting.
- 3
Compress
Merge chains of single-child nodes into one edge labeled with a substring (a radix trie). This roughly halves or better the node count for natural-language queries.
- 4
Cap depth and serialize
Stop storing top-k lists past ~50 characters (nobody needs suggestions for a paragraph) and write the structure to a flat, pointer-free format that loads with a single read (or
mmap).
| Option | Lookup | Memory | Freshness | Best for |
|---|---|---|---|---|
| In-memory trie with top-k | O(p), microseconds | Smallest (shared prefixes) | Snapshot swaps | Dedicated typeahead service |
| Prefix → top-k in Redis or a KV store | One key read | Larger (prefixes repeated) | Per-key updates possible | Teams that want off-the-shelf storage |
| Search engine (Elasticsearch completion suggester, edge n-grams) | Milliseconds | Index plus FSTs | Near real time indexing | Suggestions of documents, products or entities with filters |
6. Deep dive: collecting and aggregating queries
Suggestions are only as good as the counts behind them. The pipeline is a classic batch job (see Batch & Stream Processing): log, aggregate, score, filter, build. The interesting decisions are what to count and how to weigh time.
- Count submitted searches and accepted suggestions, not keystrokes. Weight a clicked suggestion slightly higher: it is a direct signal that the suggestion was useful.
- Count distinct users, not raw events. One bot or one user hitting refresh should not make a query trend. Cap each user's contribution per query per day.
- Normalize before counting: lowercase, trim, collapse whitespace, Unicode normalization, and strip trailing punctuation, so variants merge into one entry.
- Drop the long tail: a query must reach a minimum number of distinct users before it can ever be suggested. This also protects privacy, since a query typed by one person (a name, an address) never surfaces.
-- daily_counts(query, lang, day, users) is produced by the aggregation job.
WITH scored AS (
SELECT query,
lang,
SUM(users * POWER(0.5, DATE_DIFF(CURRENT_DATE, day, DAY) / 7.0)) AS score,
SUM(users) AS total_users
FROM daily_counts
WHERE day >= DATE_SUB(CURRENT_DATE, INTERVAL 90 DAY)
GROUP BY query, lang
)
SELECT s.query, s.lang, s.score
FROM scored s
LEFT JOIN blocklist b ON s.query LIKE b.pattern
WHERE s.total_users >= 50 -- k-anonymity style threshold
AND b.pattern IS NULL -- policy filter at build time
ORDER BY s.lang, s.score DESC;Freshness versus cost
Daily batch rebuild
- Simple, cheap, easy to validate
- Suggestions lag by up to a day
- Good for most product and site search
Hourly rebuild
- Incremental counts plus a fast rebuild of the snapshot
- Lag of about an hour
- 24× the build cost; needs automated validation
Batch base + streaming trending overlay
- A stream job (Flink, Kafka Streams) spots spikes over 5 to 15 minute windows
- A small trending table is merged with the base list at query time
- Minutes of lag where it matters, at a fraction of full-rebuild cost
The overlay is small because only a few thousand queries trend at any moment. The API looks up the base top-k and the trending entries for the same prefix, merges them by score, and caches the result for a shorter time (say 60 seconds) when trending entries are present.
7. Deep dive: sharding and serving
With a 2.5 GB trie, every server can hold a full copy, and capacity is simply the number of replicas behind a load balancer. Sharding becomes necessary when the index outgrows one machine: dozens of languages, per-region tries, or entity suggestions with rich metadata. The natural partition key is the prefix, because a lookup for sys must land on the one shard that owns all queries starting with sys.
s is split in two, so the single-letter prefix s needs a scatter-gather. Pick a flow above to animate a request.| Strategy | How | Pros | Cons |
|---|---|---|---|
| Range by first letters | a–f, g–r, ... | Simple; a prefix maps to one shard | Badly skewed (far more queries start with s than x) |
| Range by balanced split points | Choose cut points from the data (s–sm, sn–z) so each shard holds equal load | Even load, still range-routable | Short prefixes span shards; split points need rebalancing |
| Hash of the full prefix (prefix table) | shard = hash(prefix) mod N in a KV store | Perfectly even; one key per lookup | No shared structure; much more memory |
| By language or region | One trie per (lang, region) | Natural isolation and relevance | Popular languages still need range splits |
8. Deep dive: caching from the browser to the edge
The fastest request is the one never sent. Autocomplete is the rare system where the client does a large share of the scaling work.
- 1
Debounce keystrokes
Wait until the user pauses for ~100 ms before sending a request. Fast typists generate far fewer requests, and results for intermediate prefixes they typed through would never be read anyway.
- 2
Cancel stale requests
Abort the in-flight request when a new keystroke arrives, and drop any response whose prefix no longer matches the input. Otherwise a slow response for
sycan overwrite the newer list forsys. - 3
Cache by prefix in the page
Keep a small in-memory map of prefix to results. Backspacing and retyping are instant, and a list for
syscan be filtered locally forsystwhen it already holds fewer than k items (it cannot contain anything new). - 4
Let the browser and CDN cache
Cache-Control: public, max-age=300lets the browser HTTP cache and the CDN serve repeats. Short prefixes are requested by everyone, so edge hit rates for them are very high. See Content Delivery Networks. - 5
Prefetch the head
Some products ship the top suggestions for 1 to 2 character prefixes with the page, so the first keystroke needs no network at all.
const cache = new Map<string, string[]>();
let timer: ReturnType<typeof setTimeout> | undefined;
let inflight: AbortController | undefined;
export function onInput(raw: string, render: (items: string[]) => void): void {
const q = raw.trim().toLowerCase().replace(/\s+/g, " ");
clearTimeout(timer);
if (q.length === 0) return render([]);
const hit = cache.get(q);
if (hit) return render(hit); // instant on backspace or retype
timer = setTimeout(async () => {
inflight?.abort(); // cancel the request for the old prefix
inflight = new AbortController();
try {
const res = await fetch(`/v1/suggest?q=${encodeURIComponent(q)}&limit=8`, {
signal: inflight.signal,
});
const body: { q: string; suggestions: { text: string }[] } = await res.json();
const items = body.suggestions.map((s) => s.text);
cache.set(body.q, items);
render(items);
} catch (err) {
if ((err as Error).name !== "AbortError") render([]); // fail quietly: the search box still works
}
}, 100);
}9. Personalization and filtering
Personalization
- Blend the user's own recent searches (stored on the device or in a small per-user store) above global suggestions
- Keep global results cacheable: personalize on the client, or with a separate uncached call
- Use coarse context (language, country, city) as part of the cache key instead of the user id
- Rerank with a lightweight model only if the budget allows; it must run in a few milliseconds
Filtering
- Build time: drop blocklisted terms, hate speech, sexual content and personal data before they enter the trie
- Serve time: a hot blocklist pushed to all servers can remove a suggestion within seconds, without a rebuild
- Thresholds protect privacy: rare queries never surface
- Legal removals and sensitive events (tragedies, elections) follow written policies with human review
10. Scaling, bottlenecks and failure handling
- Stateless replicas: each trie server is a read-only copy, so scale out by adding replicas per region and route users to the nearest one. See Load Balancing.
- Edge first: the CDN absorbs most short-prefix traffic; origin capacity is sized for misses plus a safety margin for cache flushes.
- Memory headroom: loading a new snapshot next to the old one needs roughly 2× the trie's memory during the swap.
- Build validation: compare the new snapshot against the live one (size, top queries for canary prefixes, blocklist hits) and refuse to publish if they diverge too much.
- Rate limiting: protect the origin from scrapers enumerating every prefix. See Rate Limiting.
| Failure | Impact | Mitigation |
|---|---|---|
| Trie server crashes | Requests to it fail | Load balancer health checks remove it; replicas absorb the load |
| Bad build (empty, poisoned or offensive) | Wrong suggestions everywhere | Validation gates, staged rollout to a few servers, instant rollback to the previous version |
| Pipeline is late or broken | Suggestions get stale | Keep serving the last good snapshot; alert on snapshot age |
| Suggest API is slow or down | Empty dropdown | Clients time out quickly and fail silently; the search box still works |
| CDN flush or cold start | Origin traffic spikes | Autoscale origin, pre-warm hot prefixes, prefetch the head on the client |
Implementation
Built offline from (query, score) pairs. Inserting in descending score order means each node simply keeps the first k queries that pass through it.
from dataclasses import dataclass, field
@dataclass
class _Node:
children: dict[str, "_Node"] = field(default_factory=dict)
top: list[str] = field(default_factory=list) # best first
class AutocompleteTrie:
def __init__(self, entries: list[tuple[str, float]], k: int = 10) -> None:
self.k = k
self.root = _Node()
for query, _score in sorted(entries, key=lambda e: e[1], reverse=True):
self._insert(query)
def _insert(self, query: str) -> None:
node = self.root
for ch in query:
node = node.children.setdefault(ch, _Node())
if len(node.top) < self.k: # higher scores were inserted first
node.top.append(query)
def suggest(self, prefix: str) -> list[str]:
node = self.root
for ch in prefix:
node = node.children.get(ch)
if node is None:
return []
return list(node.top)
trie = AutocompleteTrie([("system design", 980), ("systemctl restart", 400), ("sysco careers", 150)], k=2)
print(trie.suggest("sys")) # ['system design', 'systemctl restart']Key takeaways
- Precompute the answer: store the top-k completions in every trie node so a lookup is O(prefix length), independent of how many queries exist.
- Build the trie offline from submitted searches with time-decayed, distinct-user scores, and serve it as an immutable, versioned snapshot.
- A filtered query set usually fits in RAM, so replicate first; shard by prefix (with balanced split points) only when it does not.
- Most of the latency budget is network, so debounce, cache by prefix in the browser, and let the CDN serve hot short prefixes.
- Add freshness with a small streaming trending overlay merged at query time instead of rebuilding the whole trie constantly.
- Filtering is a product and legal requirement: block at build time, and keep a serve-time blocklist for instant removals.
Common pitfalls
- Exploring the whole subtree on every keystroke, which is fast in a demo and hopeless for one-letter prefixes at scale.
- Logging every keystroke as a query, which fills the counts with partial words like
sysd. - Putting the user id in the suggest URL, making every response uncacheable.
- Updating a live trie in place, which needs locks and lets replicas drift apart; swap immutable snapshots instead.
- Letting out-of-order responses overwrite newer results in the dropdown.
Interview tips
- Do the estimation and point out that the filtered query set fits in memory: it changes the design from "shard a database" to "replicate a snapshot".
- Explain why top-k per node beats searching the subtree, then name its cost (memory and expensive updates) and why offline rebuilds make that cost acceptable.
- Volunteer the freshness trade-off: daily batch, hourly batch, or batch plus a streaming trending overlay.
- Mention client-side work (debounce, abort, prefix cache): interviewers like candidates who remember the browser is part of the system.
Real-world applications
- Google Search autocomplete predictions are generated from real searches and are subject to published removal policies for violent, hateful, sexual and other violating predictions.
- Facebook described its typeahead in 2010 ("The Life of a Typeahead Query"): the browser prefetches a user's most likely results (friends, pages) so many keystrokes are answered locally, with a server-side index for the rest.
- LinkedIn open-sourced Cleo, a typeahead library built around in-memory prefix indexes and Bloom filters.
- Elasticsearch offers a completion suggester backed by in-memory finite state transducers, a common choice for product search typeahead.
- Twitter released typeahead.js, a client library built around prefetching, local caching and debounced remote calls.
Test yourself
What does storing a top-k list in every trie node buy you?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.