You type "iph" into a search box and, before you finish, a list drops down: "iphone 15", "iphone case", "iphone charger". That is typeahead (also called autocomplete). When you press Enter, the system runs a search and returns ranked results. The two features look alike, but they are different systems. Typeahead answers one question very fast: "what are the best completions for this prefix?". Search answers a harder one: "which documents best match these words?". This lesson designs both, with most of the depth on typeahead. The inverted index, text analysis and BM25 ranking were covered in the specialized indexes lesson, so here we focus on the full query path and the data pipeline around it.
1. Requirements and Scope
Typeahead
- For each keystroke, return the top 5 to 10 suggestions that start with the typed prefix.
- Suggestions are ranked by popularity and recent trends.
- Very fast: the box must feel instant, so p99 under 50 ms on the server and about 100 ms in the browser.
- Offensive, illegal and blocked terms never appear.
- Optional: personalization and typo tolerance.
Search
- Return ranked results for a query, page by page, with p99 under 300 ms.
- New documents become searchable within minutes.
Non-functional: high availability (suggestions are a nice-to-have, so the search box must still work without them), and the data can be slightly stale. Out of scope: crawling documents (see the web crawler lesson), machine learning ranking internals, images and voice.
2. Estimation
Per day first. Assume 500 million searches per day.
Searches: 500,000,000 / 86,400 = about 5,800/s average, 23,000/s peak (4x)
Typeahead requests: a user sends about 6 requests per search
(after waiting 150 ms between keystrokes and starting at 2 characters)
500,000,000 x 6 = 3 billion/day = 34,700/s average, about 139,000/s peak
Query log: 500,000,000 x 50 bytes = 25 GB/day, about 9 TB/year
Suggestion data:
keep the 10 million most popular queries (they cover most traffic)
about 100 million distinct prefixes (queries share prefixes)
each prefix stores 10 suggestions x about 30 bytes = 300 bytes
100,000,000 x 300 bytes = 30 GB total
Server count: 139,000 / 20,000 per node = 7 nodes, so about 12 with headroom
What this tells us:
- Typeahead traffic is 6 times the search traffic, and each request is tiny. It must be served from memory.
- 30 GB fits in memory on one machine. We replicate for throughput and availability, not because the data is too large to hold.
- Most requests are for short prefixes ("a", "ip", "how"). There are few of them, and each one is requested millions of times, so caching removes most of the load.
3. API
GET /v1/suggest?q=iph&limit=8&lang=en
200 OK Cache-Control: public, max-age=120
{ "prefix": "iph", "suggestions": ["iphone 15", "iphone case", "iphone charger"] }
GET /v1/search?q=iphone+case&limit=10&cursor=eyJzY29yZSI6...
200 OK
{ "results": [ { "id": "d91", "title": "...", "snippet": "..." } ], "nextCursor": "..." }
- The suggest response is the same for everyone with the same prefix and language, so it is cacheable at the edge. Personalized parts are added separately.
- Search uses a cursor, not
page=500. Deep offsets force every shard to collect and throw away thousands of results.
4. Data Model
- Search log (event stream):
{query, timestamp, userId?, region, clickedResult?}, written to Kafka. - Aggregated counts:
(query, hour) → countin a table or warehouse. A query's score combines recent counts with an exponential decay, so old popularity fades. - Suggestion snapshot: the prefix → top-K structure, built offline and stored as a versioned file in object storage.
- Blocklist: terms and patterns that must never be suggested.
- Search index: documents split into shards, each holding an inverted index (the specialized indexes lesson).
5. High-Level Design
flowchart LR
U[Browser: debounce and cache] --> E[CDN / edge cache]
E --> S[Suggest service: in-memory prefix index]
U --> Q[Search service]
Q --> QU[Query understanding]
QU --> SH[Index shards: scatter and gather]
SH --> R[Ranker]
Q --> LOG[(Kafka: search log)]
LOG --> AGG[Aggregation: batch and streaming]
AGG --> B[Snapshot builder]
B --> OS[(Object storage: versioned snapshots)]
OS --> S
AGG --> T[Trending store]
T --> S
DOC[(Documents)] --> IDX[Indexer] --> SH
Online path (typeahead): the browser waits a short time after the last keystroke (debounce), then asks for the prefix. The CDN answers common prefixes. A miss reaches a suggest node, which looks up the prefix in memory, merges in a few trending items and removes any term on the blocklist.
Offline path: every search is logged. A pipeline counts queries, filters blocked terms, and builds a new snapshot (for example hourly). A streaming job tracks the last 15 minutes to catch sudden trends. The snapshot reaches the suggest nodes in four steps:
- Build: the job writes the finished structure as one versioned file in object storage, such as
snapshots/en/2026-11-04T10/index.bin, with a checksum. - Publish: only after the file is complete, it updates a small pointer file (
LATEST) to name the new version. Nodes never see a half-written snapshot. - Load: each node checks the pointer now and then, downloads the new file, verifies the checksum, loads it into memory and swaps it in. A new node does the same at start-up.
- Roll back: if a snapshot is bad, point
LATESTback to the older version. Old files are kept for a few days for this.
What is inside the snapshot file: three parts. A header with the version, language, K, build time and checksum. A query table that stores each distinct query text once, with a number (0 = "iphone 15", 1 = "iphone case", 2 = "iphone charger"). A prefix table that lists each prefix in sorted order with its top-K as query numbers, for example "iph" → [0, 1, 2]. A lookup finds the prefix, reads the numbers and turns them into text. Numbers instead of full text in every list save memory, so the 30 GB estimate above is an upper bound. The format can be a custom binary layout, Protocol Buffers or FlatBuffers. Plain JSON works but is larger and slower to load.
Why a file and not a database or cache? Nodes answer from memory, and object storage only hands the data over: it is cheap, durable and shared by all nodes and regions. Writing 100 million prefix rows into a database every hour would be slow, could not be switched in one step, and would add a network call to every keystroke. A cache is used only for the small, fast-changing trending data.
6. Deep Dive: The Prefix Index
The naive way is SELECT query FROM queries WHERE query LIKE 'iph%' ORDER BY count DESC LIMIT 10. It scans every query that starts with "iph" and sorts them, on every keystroke. Far too slow. The fix is to precompute the top-K for every prefix.
| Structure | How it works | Trade-off |
|---|---|---|
| Trie with top-K at each node | Letters form a tree. Each node stores the top 10 queries below it. | Lookup is O(length of prefix). Shared prefixes save memory. Needs a rebuild to change counts. |
| Hash map: prefix → top-K | Every prefix is a key. The value is the ready list. | Simplest, O(1) lookup, but repeats data for every prefix, so more memory. |
| Redis sorted set per prefix | One sorted set per prefix, read with ZREVRANGE. |
Easy to update live. Highest memory, and many keys. |
| Search engine suggester (compressed automaton) | Elasticsearch completion suggester or Lucene FST in memory. | Compact and fast with built-in features. Less control over ranking and blocking. |
For the interview, draw the trie and say "top-K stored at every node". Build it offline with a simple idea: process queries from highest score to lowest, and add each query to the list of every prefix it has, until that list holds K entries. Because the best queries come first, each list ends up holding exactly the top K.
public class PrefixIndex {
private final Map<String, List<String>> top = new HashMap<>();
public static PrefixIndex build(Map<String, Long> scores, int k, int maxPrefixLength) {
PrefixIndex index = new PrefixIndex();
scores.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed()) // best first
.forEach(e -> {
String query = e.getKey();
int limit = Math.min(query.length(), maxPrefixLength);
for (int i = 1; i <= limit; i++) {
List<String> list = index.top.computeIfAbsent(query.substring(0, i), p -> new ArrayList<>(k));
if (list.size() < k) list.add(query);
}
});
return index;
}
public List<String> suggest(String prefix) {
String key = prefix.trim().toLowerCase();
return top.getOrDefault(key, List.of());
}
}
public class SuggestService {
private final AtomicReference<PrefixIndex> current = new AtomicReference<>(new PrefixIndex());
public List<String> suggest(String prefix) { return current.get().suggest(prefix); }
// called when a new snapshot file has been downloaded and loaded into memory
public void swap(PrefixIndex fresh) { current.set(fresh); }
}
- Immutable snapshot plus atomic swap. Reads never take a lock, and a new snapshot replaces the old one in one step. No half-updated state, and rollback is just swapping the old one back.
- Limit prefix length (for example 20 characters). Long prefixes are specific enough that a normal search is fine, and this cuts memory sharply.
- Normalize input (lower case, trim, collapse spaces) the same way at build time and at query time.
- Store query IDs or compact strings instead of full text in each list to save memory.
7. Deep Dive: Ranking and Freshness
- Score = recent popularity. Weight recent counts more than old ones (exponential decay), so last year's hit fades.
- Trending. A snapshot built hourly misses a breaking event. A streaming job counts queries in the last 15 minutes. At request time, the suggest node merges the snapshot's top-K with the trending list for that prefix and re-sorts a handful of items.
- Personalization. Blend the user's own recent searches (kept on the device or in a small per-user store) with the global list. Keep the global part cacheable, and add the personal part after the cache.
- Locale and language. A separate index per language or region. "football" means different things in different countries.
- Safety. Remove blocked terms at build time, and check again at serve time so a new block takes effect without waiting for the next snapshot.
- Typo tolerance. Optional. It needs edit-distance matching, which is slower. Many systems do spelling correction on the full search, not on each keystroke.
8. Worked Example: A Product Launch
The hourly snapshot has these counts for queries that start with "ip":
| Query | Hourly snapshot score | Last 15 minutes |
|---|---|---|
| iphone 15 | 900 | 40 |
| iphone case | 700 | 45 |
| iphone charger | 400 | 20 |
| ipad pro | 300 | 15 |
| iphone 17 launch | 10 | 600 |
- The user types "iph". The snapshot's top 3 for "iph" are iphone 15, iphone case, iphone charger.
- The streaming trending list for "iph" has "iphone 17 launch" with a very high recent count.
- The suggest node merges the two lists. Each item gets a blended score: the snapshot score scaled for age, plus a weighted recent-window count. "iphone 17 launch" jumps into the top 3, and "iphone charger" drops out.
- The response is cached at the edge for a short TTL (1 to 2 minutes). The trend appears within a couple of minutes, not after the next hourly build.
The same flow shows why short prefixes matter: "ip" is typed by a huge number of users, so it is served from the edge cache almost every time. Only the less common prefixes reach the suggest nodes.
9. Deep Dive: The Search Path
When the user presses Enter, the search service runs these steps:
- Query understanding: normalize, correct spelling ("iphne" → "iphone"), expand synonyms, detect language.
- Scatter: the index is split into shards by document. Every shard holds a part of the documents, so the query goes to all shards (or one replica of each). Each shard finds its own top N matches with the inverted index and a cheap score (BM25).
- Gather: the search service merges the shard results into one top list.
- Re-rank: a slower, smarter model (clicks, freshness, quality) re-orders only the top 100 or so.
- Build the page: fetch titles and snippets for the final 10.
- Tail latency. A query is as slow as its slowest shard. Set a timeout and return partial results from the shards that answered. Send a backup request to another replica of a slow shard (hedged request).
- Result cache. Popular queries repeat. Cache the final result for a short time. A small share of queries usually produces a large share of traffic.
- Freshness. New or changed documents flow from the source through Kafka to an indexer. Search engines such as Lucene make new documents searchable after a refresh of about a second, and merge segments in the background.
- Pagination. Use a cursor made of the last result's sort values, so each shard can continue from there without collecting all earlier pages.
- Replicas serve reads and survive node loss. The database stays the source of truth, and the index can be rebuilt from it.
10. Client Tricks That Save Load
- Debounce about 150 ms, and start at 2 characters. This cut our estimate to 6 requests per search.
- Cancel the previous request when a new key arrives, and ignore responses that arrive late for an older prefix.
- Cache in the browser: if "iph" was fetched, a backspace to "ip" can reuse the stored answer. Also, if "iph" returned fewer than K results, the answer for "ipho" is already inside it and needs no request.
- Use a keep-alive connection (HTTP/2) so each keystroke does not pay for a new connection.
11. Failures, Scaling and Operations
| Failure | Behavior |
|---|---|
| Suggest service down | The browser hides the dropdown. Search still works. Typeahead is a nice-to-have. |
| Snapshot build fails | Nodes keep serving the old snapshot. Alert when it is older than a limit. |
| Streaming job down | Serve the snapshot only. Suggestions are slightly less fresh. |
| Bad snapshot (wrong data) | Roll back with one pointer swap. Canary a new snapshot on a few nodes first. |
| Index shard or node lost | Another replica answers. If none, return partial results with a flag. |
- Scaling the suggest tier: stateless nodes that load the snapshot at start-up. Add nodes for traffic. At 30 GB each node holds everything. If data grows beyond one machine, shard by the first characters of the prefix, and spread hot letters over more nodes.
- Multi-region: each region has its own suggest nodes and a copy of the snapshot, so the lookup stays close to the user.
- Privacy: do not suggest queries that could reveal one person's data. Only include a query in the shared index after enough different users have searched it.
12. Common Pitfalls
- Using a
LIKE 'prefix%'database query on every keystroke. - Walking the whole subtree of a trie to find the top 10, instead of storing the top 10 at each node.
- Updating the live structure in place with locks, instead of building a snapshot and swapping it.
- No debounce or cancellation, so the system gets hit on every key and shows stale responses.
- Ranking only by all-time counts, so trends never appear.
- Skipping the blocklist or applying it only at build time.
- Not caching short prefixes at the edge.
- Deep offset pagination in search, which gets slower with every page.
- Making typeahead a hard dependency of the search page.
13. Interview Questions and Answers
1. How do you build typeahead that responds in under 50 ms?
Precompute the top 10 suggestions for every prefix, keep them in memory on stateless nodes, and look up by prefix in O(1) or O(length). Put a CDN in front for common short prefixes, and debounce on the client. Build the data offline and swap it in as an immutable snapshot.
2. Why store top-K at each trie node?
Without it, every lookup must walk all queries below the prefix and sort them. With the top K stored at each node, a lookup walks only as many nodes as the prefix length and returns the stored list. We pay with more memory and a rebuild when counts change.
3. How do you rank suggestions and keep them fresh?
Rank by recent popularity with time decay, then adjust for language, region and optionally the user's own history. Remove blocked terms. An hourly batch snapshot gives the stable ranking, and a streaming job counts the last 15 minutes. At request time, merge the two lists for the prefix, so a trend shows up within minutes while the big structure is rebuilt only occasionally. Rank globally first and personalize after the cache.
4. Why ship the prefix index as a file instead of storing it in a database or cache?
Rebuilding means rewriting about 100 million prefixes. A file is one upload, it is switched in one step with a pointer, and rollback is the same pointer change. Nodes then answer from local memory, so there is no network call per keystroke and no shared dependency. A live store such as Redis is used only for the small trending data that changes every minute.
5. How does search scale across many documents?
Split the index into shards by document, each with an inverted index and replicas. A query is sent to all shards, each returns its top N, and the search service merges and re-ranks. Use timeouts, hedged requests for slow shards, and a result cache for popular queries.
6. How do new documents become searchable?
Changes go through a queue to an indexer that writes into the shards. The engine makes them visible after a short refresh (about a second in Lucene-based engines) and merges segments in the background. The primary database stays the source of truth, so the index can be rebuilt.
7. What happens if typeahead is down?
Nothing critical. The client hides the dropdown and the user can still type the full query and search. That is why typeahead and search are separate services, with typeahead as an optional feature.