SkillSprout
Chapter 5 · Lesson 3
Intermediate
25 min read

Design Typeahead (Search Autocomplete)

Overview

When you type how to t into a search box and a list drops down with how to tie a tie, how to train your dragon, you are using typeahead (also called autocomplete). It looks like a tiny feature, but it is one of the harshest latency problems in system design: the suggestions must appear within about 100 ms of every keystroke, for hundreds of millions of users, while the underlying data (what people search for) keeps changing. The key idea is to do the hard work offline, ahead of time, so that the live request is a single in-memory lookup. This lesson walks the full eight-step interview framework and defines every data structure it needs, including the trie.

Detailed Notes

How to use this lesson

Treat this as a 45-minute interview. The numbers are assumptions you state out loud, not facts about any real company. The interviewer will not check that 100 million daily users is realistic; they will check that your estimates drive your design.

Step 1: Clarify Requirements

Turn "design search autocomplete" into a precise scope. A good opening: "Is this for a search engine's query box, and should suggestions come from what other people searched, or from a catalog of items? How many suggestions do we show? Do they need to be personalized?"

Functional requirements

  • As the user types a prefix (the first few characters of a query), return the top 10 suggested queries that start with that prefix.
  • Suggestions are ranked by popularity: how often people searched for that query recently.
  • Suggestions update as the user types more characters.
  • Matching is prefix based (typing tre suggests tree house, not street food). Matching in the middle of a word is out of scope.

Extended requirements

Mention these, then ask whether to include them.

  • Trending: a breaking-news query should appear within minutes, not days.
  • Personalization: boost queries this user searched before.
  • Filtering: never suggest offensive, dangerous or illegal queries.
  • Multi-language and region: suggestions depend on language and country.
  • Spelling tolerance: suggest facebook for facebok. We will not build it.

Non-functional requirements

  • Very low latency: suggestions must show while the user is still typing. Target p99 (99 of 100 requests faster than this) under 100 ms end to end, so the server side should take under 20 ms.
  • High availability: 99.99% (about 52 minutes of downtime per year). If typeahead fails the search box still works, so the system must degrade gracefully instead of blocking the page.
  • Scalability: tens of thousands of suggestion requests per second on average, more than 100,000 at peak.
  • Eventual consistency is fine: suggestions can be minutes or even hours behind real searches. Nobody notices if a count is off by 1%. This single decision makes the whole design cheap.
  • Relevance: the top results should match what users actually want.

Out of scope

The search results page itself, spell correction, semantic (meaning-based) suggestions, voice input, and ads inside the suggestion box.

Interview tip. The most valuable clarifying question is "how fresh must suggestions be?" If the answer is "a day old is fine", you can build everything as an offline batch job. If it is "trending within 5 minutes", you need an extra fast path. Ask before drawing.

Step 2: Estimate Scale

Assumptions to state

  • 100 million daily active users (DAU).
  • Each user performs 10 searches per day.
  • Typing a query triggers about 5 suggestion requests. A query has roughly 20 characters, but we will see in Step 6 that the client does not send a request on every keystroke.
  • The distinct queries worth suggesting number about 100 million. Billions of rare, one-off queries (a typo, a pasted sentence) are never suggested, so we drop them.
  • An average query is 25 characters, about 25 bytes.
  • A day has about 100,000 seconds (the real value is 86,400; the error is small).
  • We show 10 suggestions per request, about 300 bytes of JSON.

Request load

text
Searches per day               = 100M users x 10     = 1 billion
Suggestion requests per day    = 1B x 5              = 5 billion
Average QPS                    = 5B / 100,000 s      = 50,000 per second
Peak QPS (x3 peak factor)      = 50,000 x 3          = 150,000 per second
Typeahead: Estimate the Scale
Estimation

Request load

100Mdaily active users
given
1Bsearches / day
× 10 each
5Brequests / day
× 5 per search
50K/saverage QPS
÷ 100,000 s
150K/speak QPS
× 3 peak factor

Origin load

45K/s

150K peak × 30% not cached by browser or CDN

Cache hard; about 12 servers (4 shards × 3 replicas)

Trie size

~40 GB

300M nodes × 50 B + top-10 lists 24 GB + text 2.5 GB

Keep it in memory and shard it

Search logs

100 GB/day

1B events × 100 bytes; 3 TB for 30 days

Object storage and a batch job; sample if needed
Key point. Read-heavy at extreme QPS with tiny payloads: cache in front, keep the trie in memory, and shard it.

Everything derives from 100 million daily users, 10 searches each and about 5 suggestion requests per search.

So what: this is a read-heavy system with an extreme request rate and a tiny payload. Writes (the search logs we collect) are only 1 billion per day, about 10,000 per second, and they do not have to be real time. We will separate reading from learning.

How much traffic actually reaches our servers?

Typeahead is very cacheable. Many users type the same prefixes (face, how, wea), and a prefix's top 10 changes slowly. If browser caches and a CDN absorb about 70% of requests:

text
Origin peak QPS = 150,000 x 30% = 45,000 per second

So what: caching in front of the servers is not optional; it cuts server load by three quarters. We design the HTTP caching headers in Step 6.

Trie size (the main data structure)

We will define the trie properly in Step 5. For now: a trie is a tree where each node stands for one prefix, so all queries that start with tre live under the node for tre.

text
Distinct queries                 = 100 million
Characters if stored separately  = 100M x 25 = 2.5 billion
Shared prefixes shrink this: assume ~3 new nodes per query
Nodes                            = 100M x 3 = 300 million
Node structure (child pointers, flags) = 300M x 50 bytes = 15 GB
Top-10 list on every node (10 query ids x 8 bytes = 80 bytes)
                                 = 300M x 80 bytes = 24 GB
Query text dictionary            = 100M x 25 bytes = 2.5 GB
Total                            = about 40 GB

So what: 40 GB fits in the RAM of one large server, so the trie can live entirely in memory and answer in microseconds. We still split it into shards (parts, each holding a subset of the data) because one machine cannot serve 45,000 requests per second, cannot be restarted safely, and takes long to reload.

Servers needed

text
One in-memory trie server  = about 10,000 requests/s (network and JSON dominate)
Origin peak                = 45,000 / 10,000 = about 5 servers of capacity
Plan: 4 shards x 3 replicas = 12 servers (~10 GB trie per server)
Capacity                   = 12 x 10,000 = 120,000 requests/s (headroom for peak and failures)

Log storage and bandwidth

text
Search log line                = about 100 bytes (query, time, user, country)
Per day                        = 1B x 100 bytes = 100 GB per day
Keep 30 days                   = 100 GB x 30 = 3 TB
Response bandwidth (peak)      = 150,000/s x 500 bytes = 75 MB/s

So what: 3 TB of logs is trivial for object storage and a batch job. 75 MB/s (about 600 Mbps) of small responses is fine, and the CDN serves most of it.

Interview tip. Say the sizes in the right unit and conclude each time: "the trie is 40 GB, so memory, not disk"; "QPS is 150,000 at peak, so caching must absorb most of it."

Step 3: Define the APIs

An API is the contract between the client and the service. There are two: one to read suggestions (fast, huge volume) and one to record what users searched (so we can learn).

Get suggestions

http
GET /v1/suggestions?q=tre&limit=10&lang=en&country=IN
Accept: application/json

HTTP/1.1 200 OK
Cache-Control: public, max-age=300
Content-Type: application/json
json
{
  "prefix": "tre",
  "suggestions": [
    { "text": "tree house", "score": 9120 },
    { "text": "trending now", "score": 8800 },
    { "text": "treadmill", "score": 7400 }
  ]
}
  • 200 OK with an empty suggestions array if nothing matches (never 404: "no suggestions" is a valid answer).
  • 400 Bad Request if q is empty or longer than 100 characters.
  • 429 Too Many Requests if one client sends far too many requests.
  • 503 Service Unavailable if the service is overloaded. The client then simply shows no dropdown.

Design points:

  • It is a GET with the prefix in the URL, so browsers, CDNs and proxies can cache it. A POST would not be cacheable.
  • Cache-Control: public, max-age=300 lets browsers and the CDN reuse the answer for 5 minutes. This is the lever that removes 70% of the load.
  • The prefix is normalized before use (lowercase, trimmed, Unicode normalized) so Tre, tre and TRE share one cache entry.
  • Personalized requests carry a user token and return Cache-Control: private, so a shared CDN never caches one user's suggestions for someone else.

Record a search (feeds the learning pipeline)

http
POST /v1/search-events
{ "query": "tree house", "ts": "2026-11-28T10:15:00Z", "country": "IN" }

HTTP/1.1 202 Accepted

202 Accepted means "received, will process later". In practice the search service that serves the results page already sees every submitted query, so it writes this event itself instead of asking the browser to call a second endpoint.

Trade-off thinking. Returning scores helps debugging but lets competitors scrape popularity. Many real systems return only ordered text. Choose based on the product.

Step 4: Define the Data Model

Start from access patterns:

  1. Online: given a prefix, return its top 10 queries. Key lookup, 45,000 per second.
  2. Offline: count how often each query was searched in a time window. Scans over terabytes.
  3. Offline: build a new lookup structure from the counts and publish it.

Two very different workloads, so two stores.

Fields and why each exists

  • query_counts.query, window_start, count: output of the counting job. One row per query per time window (for example per hour). Summing recent windows (with a decay for older ones) gives the ranking score.
  • trie_snapshot: the serialized trie built from the counts. It is a file, not a table, because it is loaded into memory, not queried by SQL.
  • prefix_top_k.prefix and suggestions: the logical content of every trie node: the prefix and its precomputed top 10.
  • blocklist.term: words and phrases that must never be suggested.
  • user_recent.user_id and query: the last 50 queries of a user, for personalization.
The Data Model
Data model
query_countsObject storage (batch)
  • PKqueryvarchar(100)

    normalized text

  • SKwindow_starttimestamp

    one row per hour

  • countbigint

    searches in that window

  • distinct_usersint

    guards against one user spamming

  • countryvarchar(2)

    for regional rankings

Append-only files partitioned by day. Summed with a time decay to produce the score.

prefix_top_kIn-memory trie (snapshot)
  • PKprefixvarchar(100)

    the trie node; shard chosen by prefix range

  • suggestionsarray of query ids x 10

    ordered by score, resolved via the dictionary

  • snapshot_versionvarchar

    which build this came from

Serialized to a file per shard, loaded into RAM, swapped atomically, never edited in place.

blocklistSmall key-value store
  • PKtermvarchar

    word or phrase to never suggest

  • added_attimestamp
  • reasonvarchar

    offensive, legal, privacy

Applied at build time and again at serve time so removals take effect immediately.

user_recentKey-value store
  • PKuser_iduuid
  • recent_querieslist of 50

    newest first, with timestamps

Read at request time to boost personal matches; written by the search service.

  • prefix_top_k.suggestionsquery_counts.query· built from
Key point. The online store is the in-memory trie; everything else supports building it.

Raw data is batch-processed offline. Only the snapshot and a few small tables are touched online.

Which storage?

  • Raw search logs and counts live in object storage plus a batch engine (files partitioned by day). These are append-only and scanned in bulk; a transactional database would be wasteful.
  • The live trie lives in the memory of the suggestion servers. A database lookup per keystroke would cost milliseconds and need a huge cluster for 45,000 requests per second. Snapshots in object storage make rebuild and recovery easy.
  • Per-user history is a small key-value lookup by user_id, so a key-value store or cache works.

Why not a relational database with LIKE 'tre%'? An index on the query column does support prefix search, but it must then sort 100 million candidates by popularity on every keystroke. Even with a composite index it is far slower than reading one precomputed list, and it would melt at 45,000 requests per second.

Step 5: High-Level Design

The golden rule is to separate learning from serving. Learning is slow, bulk and tolerant of delay. Serving must answer in milliseconds.

What is a trie?

A trie (pronounced "try", from retrieval, also called a prefix tree) is a tree where every node represents a prefix and each edge adds one character. Walking from the root along the characters of a prefix lands on the node for that prefix, and everything below that node starts with it. Let us build one for three queries: tea (searched 30 times), tree (20) and toy (10).

  1. Start with an empty root. The root represents the empty prefix.
  2. Insert tea. Add edges t, then e, then a. Mark the last node as a complete query with count 30.
  3. Insert tree. Follow the existing t edge (it is shared, nothing new), then add r, e, e. Mark the last node with count 20.
  4. Insert toy. Follow t, add o, then y. Mark it with count 10.
  5. Look up the prefix t. Walk one edge, arrive at node t. Everything below it (tea, tree, toy) is a candidate.
A Trie Holding tea (30), tree (20) and toy (10)
Architecture
roottop: tea, tree, toyttop: tea, tree, toytetop: teatrtop: treetotop: toyteaquery, count 30tre + e = treequery, count 20toyquery, count 10teroae, ey
Key point. Looking up a prefix of L characters takes L steps, then one list read.

Each node is one prefix. The top-3 list stored on a node is the answer to that prefix. A real system stores 10.

Because queries share beginnings, the trie stores t once instead of three times. Looking up a prefix of length L takes L steps regardless of how many queries exist. That is the property we want.

The picture above also shows the key optimization: each node stores its top-k list (the k most popular complete queries below it, here k = 10). Without that list, finding the best suggestions for t means visiting every node below it, possibly millions. With it, the answer is already waiting at the node.

Serving a Prefix: Walk the Subtree or Precompute Top-k
Comparison

Walk the subtree

search at request time

  1. 1

    Walk to the prefix node

    L steps

  2. 2

    Visit every node below

    millions for short prefixes

  3. 3

    Collect complete queries

    with their counts

  4. 4

    Sort and keep the top 10

    on every keystroke

  • Least memory
  • Counts can be updated in place
  • Latency grows with subtree size
  • Too slow at 45,000 requests/s

Fine for tiny data sets only

Precomputed top-k

store the answer on each node

  1. 1

    Offline: score every query

    from aggregated logs

  2. 2

    Offline: merge child lists upward

    bottom-up, keep 10

  3. 3

    Online: walk to the prefix node

    L steps

  4. 4

    Online: return the stored list

    one read, no sorting

  • Microsecond lookups
  • Cost does not depend on subtree size
  • Read-only, so no locks
  • About 24 GB extra memory
  • Changes appear only after the next build

The right choice for a read-heavy, eventually consistent product

Key point. Spend memory and offline time once so that each of 5 billion daily requests is cheap.

Both return the same answer. Only one finishes in microseconds for a short prefix like t.

The architecture

The Read Path and the Learning Path
Architecture
Read pathLearningBrowserdebounce + cacheCDN edgecaches prefixesSuggestion svc~45K req/sTrie shardsin memory, 3 copiesSearch servicelogs each queryLog queuedurable bufferOffline buildercount + buildGET /suggeston misslookupsubmitlogsnapshot
Key point. Live traffic never changes the trie. It changes the logs, and the logs change the next snapshot.

Suggestions are served from an in-memory snapshot. Searches only feed the offline builder.

Components and why each exists

  • Browser and CDN caches: answer repeated prefixes without touching our servers (about 70% of traffic).
  • Load balancer and suggestion service: a stateless service that normalizes the prefix, finds the right trie shard, merges in personalization and filters. A load balancer spreads requests across identical servers and skips unhealthy ones.
  • Trie shards: servers that hold an in-memory trie for a range of prefixes and answer with the node's precomputed top 10.
  • Search service and log queue: every submitted query is appended to a message queue (a durable buffer where producers append messages and consumers read them later at their own pace). The queue decouples searching from learning.
  • Offline builder: a batch pipeline that turns logs into counts and counts into a new trie snapshot. Covered in Step 6.
One Suggestion Request After the Cache Misses
Request flow
BrowserCDNSuggestion svcTrie shard1GET /suggest?q=treafter 120 ms debounce, local miss2forward on miss3get top 10 for trenormalize prefix, pick shard410 query idswalk 3 nodes, read one list5filter + personalize6200 + max-age=3007JSON, cached at edge

A browser cache hit ends before step 1; a CDN hit ends at step 2.

Request flow

Read path.

  1. The user types tre. After a pause (debounce, Step 6.7) the browser checks its local cache.
  2. On a miss it sends GET /v1/suggestions?q=tre. The CDN answers if it has the prefix cached.
  3. On a CDN miss the request reaches a suggestion service instance, which normalizes the prefix and picks the shard.
  4. The trie shard walks 3 nodes and returns the stored top 10.
  5. The service filters, optionally personalizes, and returns JSON with Cache-Control. Each cache layer on the way back keeps a copy.

Write (learning) path.

  1. The user submits the search. The search service logs the query to the queue.
  2. Offline jobs count queries, build a new trie, and roll it out (Step 6.2). The live trie is never modified by live traffic.

Step 6: Deep Dive

Interviewers pick the hardest part. For typeahead the best material is the top-k precomputation, the offline pipeline, and the layers of caching and sharding.

There are two ways to serve a prefix.

  • Walk the subtree at query time. Find the prefix node, then traverse everything below, collect all completed queries, and pick the 10 highest. For a short prefix like t this touches millions of nodes: far too slow.
  • Precompute top-k on each node. During the offline build, compute each node's best 10 once, and store them on the node. A request is then: walk L nodes, read one list.

We pay with extra memory (24 GB in Step 2) and a slower build, and we gain a lookup that takes microseconds. Because reads are 5 billion per day and builds happen a few times a day, trading memory and offline time for fast reads is the right deal.

How the build computes top-k: process nodes bottom-up. A leaf's list is its own query. A parent merges its children's lists (and its own query if it is complete) and keeps the 10 highest scores. Each node does a small merge of at most (children x 10) items, so the whole build is linear in the number of nodes.

Memory trimming: store query ids (8 bytes) in each list, not strings, and keep the strings once in the dictionary. Nodes deep in the tree with a single descendant do not need their own list, since the parent's list or the dictionary already answers them.

6.2 The offline aggregation pipeline

The Offline Aggregation Pipeline
Architecture
OfflinePublishQuery logs100 GB / dayCount jobsgroup by queryScore + filterdecay, blocklistTrending joblast 15 minutesTrie buildertop-k bottom-upSnapshot storeone file per shardCanary rolloutvalidate, then swapTrie shardspointer swapmerge
Key point. A daily full build gives stability; a small 15-minute trending job gives freshness at low cost.

Logs become counts, counts become a trie, and the trie reaches servers as an immutable snapshot.

  1. Collect logs. The search service writes each query event to the queue. A consumer lands them in object storage, partitioned by hour. About 100 GB per day.
  2. Aggregate counts. A batch job (MapReduce-style: group by query, count) turns raw events into (query, window, count) rows. This is the batch processing idea from the batch-vs-stream lesson: process large data in bulk and optimize for throughput, not per-event latency.
  3. Score. Combine windows: score = sum of count x decay^(age), so recent searches weigh more. Drop queries below a minimum count (for example, searched fewer than 10 times in 30 days) and anything on the blocklist. This is what shrinks billions of distinct queries to 100 million.
  4. Build the trie. Insert the surviving queries, compute top-k bottom-up, serialize to a snapshot file (a complete, immutable copy of the structure) in object storage, one file per shard.
  5. Roll out. Servers download the new snapshot, load it into memory beside the old one, and then atomically swap a pointer from old to new. Requests in flight keep using the old trie until they finish. A bad snapshot is rolled back by swapping the pointer back.

Snapshots are never edited in place: a trie being modified while thousands of threads read it needs locks, which cost latency. A read-only trie replaced wholesale needs none.

Freshness versus cost. A full rebuild of 100 million queries costs real compute, so we choose cadence deliberately:

  • Full rebuild once a day (or weekly) from 30 days of data: cheap and stable.
  • Trending layer every 5 to 15 minutes: a small stream job counts queries over the last 15 minutes and finds the ones whose rate jumped sharply compared to their normal rate. A few thousand results go into a tiny extra trie that the suggestion service merges with the main one at read time.

Running the whole pipeline every 5 minutes would cost about 100x more compute for almost no extra value, because the top 10 for a stable prefix like wea barely changes. Pay for freshness only where it matters.

6.3 Sampling

Counting every one of 1 billion events per day is possible, but you do not need exact counts to rank queries. Sampling means processing a random fraction. If we keep 1 in 10 events (10%), a query's sampled count times 10 is a good estimate of its real count when the query is popular, which is exactly where accuracy matters. Rare queries become noisy, but rare queries are dropped anyway. Sampling cuts log processing and storage by 10x (about 10 GB per day instead of 100 GB). Do not sample the trending layer too aggressively, or a genuinely new topic may not reach the threshold for a while.

6.4 Caching prefixes at the browser and CDN

Layers from closest to the user:

  • Browser memory cache: the client keeps a map of prefix to results. When the user types tre then tr then tre again (backspace), no request is sent. Also, if tre returned fewer than 10 results, then tree can be answered from that same list by filtering locally.
  • HTTP cache and CDN: Cache-Control: public, max-age=300. The CDN (a network of edge servers close to users) answers for everyone in the region. Short prefixes (1 to 3 characters) have a tiny key space (26^3 = about 17,500 for lowercase letters alone) and high hit rate, so most typeahead traffic is for prefixes that a CDN can hold.
  • Server-side cache: optional Redis-style cache keyed by prefix in front of the trie. Usually unnecessary because the trie is already in memory, but useful for the personalized merge.

The cost of caching is staleness: after a new snapshot, caches serve old answers for up to the TTL. Five minutes is acceptable here. Use a version in the URL (&v=2026112810) or a shorter TTL when a fresh snapshot goes live if you need faster turnover.

6.5 Sharding the trie by prefix

One 40 GB trie does not fit our availability and throughput needs, so we shard it. The idea is the same partitioning concept from the partitioning lesson, but the choice of key is unusual.

  • Shard by first character(s) of the prefix: shard 1 holds a-f, shard 2 g-m and so on. A request goes to exactly one shard, which keeps the lookup simple. The problem is skew: far more queries begin with s or t than with x or q, so some shards are much hotter and bigger.
  • Shard by hash of the prefix (first 2 characters): spreads load evenly, but a request still needs exactly one shard because we hash the first two characters only and every longer prefix shares them.
  • Balanced ranges from data: the offline builder already knows the counts. It chooses split points so each shard receives about equal traffic (not equal alphabet width), for example a-co, cp-m, n-s, sa-z. A small routing table maps prefix ranges to shards and is updated with each snapshot.

We combine the last two: the routing table is generated by the builder and each shard has 3 replicas across availability zones. A replica is a copy of the same shard on another machine, which gives both fault tolerance and more read throughput.

Very short prefixes (a, s) are the hottest requests but the easiest to cache, since only 26 of them exist. So the CDN absorbs them and the shards see the long tail of longer prefixes.

6.6 Personalization and filtering

Personalization. The global top 10 for ma is the same for everyone, so it is cacheable. A personalized list is not. Do it cheaply:

  • Fetch the global top 10 from the trie (cacheable).
  • Fetch the user's recent queries (the user_recent store) and keep those that start with the prefix.
  • Merge: boost matching recent queries to the top, then fill with global results. Return with Cache-Control: private.

Doing the merge at read time keeps the expensive shared trie global and the per-user part tiny. A fully per-user trie would multiply memory by 100 million.

Filtering offensive suggestions. A suggestion box is a very public product, so a bad suggestion is a brand problem. Use two layers:

  • At build time: remove blocklisted terms, and queries flagged by an automated classifier or human review, before they enter the trie.
  • At serve time: a small in-memory blocklist applied to the final list. It acts instantly (no waiting for the next snapshot), so a PR emergency is fixed in seconds by pushing a new blocklist.

Also remove queries containing personal data such as phone numbers or emails, and require a minimum number of distinct users per query so a single user cannot push a suggestion into the list by searching it repeatedly.

6.7 Debouncing on the client

If the user types tree house at 5 characters per second, sending a request per keystroke makes 10 requests for one search. Debouncing means waiting until the user pauses typing (for example 100 to 150 ms) before sending. Together with:

  • skipping requests for prefixes shorter than 2 characters (or serving them from a bundled local list),
  • cancelling the previous in-flight request when a new keystroke arrives, and
  • ignoring responses that arrive out of order (a response for tr arriving after tre must not replace the newer list),

debouncing explains why we estimated about 5 requests per search instead of 20. Fewer requests is cheaper than any server optimization.

Trade-off thinking. Every freshness knob has a cost. A shorter cache TTL, a faster rebuild, and more sampling accuracy each make suggestions fresher but multiply compute, load and cost. The right setting is the cheapest one that users cannot tell apart from the freshest.

Step 7: Bottlenecks and Failure Handling

Bottlenecks

  • Hot shards. Cause: uneven prefix popularity. Mitigation: traffic-balanced ranges, more replicas for hot shards, CDN for short prefixes.
  • Build time. Cause: a growing log volume. Mitigation: sampling, incremental counts (reuse yesterday's counts and add today's), parallel builds per shard.
  • Memory growth. Cause: more queries and more languages. Mitigation: raise the minimum count, cap top-k at 10, store ids not strings, add shards.
  • Cache stampede after a snapshot swap. Cause: many entries expire at the same moment. Mitigation: add random jitter to TTLs and let the CDN collapse concurrent misses for one prefix into one origin request.
  • Log pipeline lag. Cause: a queue backlog. Mitigation: scale consumers by queue depth. Serving is not affected, only freshness.

Failures

  • A trie server dies. The load balancer health check removes it; the other replicas of that shard answer.
  • A whole shard is unavailable. The service returns an empty list or a stale cached answer for those prefixes. Typeahead is a convenience, so fail open: the search box keeps working.
  • A bad snapshot (corrupt, or a build bug removed half the queries). Validate before rollout: compare size and a sample of known prefixes with the previous snapshot, roll out to one replica first (a canary), and keep the previous snapshot for instant rollback.
  • Pipeline fails. The old snapshot keeps serving. Suggestions get stale but the product works. Alert if the snapshot is older than 36 hours.
  • Queue or log consumer fails. Events stay in the durable queue, and are processed when it recovers.
  • Thundering requests from a buggy client. Rate limit per client at the gateway and return 429.

Interview tip. Name what you would monitor: suggestion p99 latency, CDN and browser hit rate, snapshot age, shard QPS skew, empty-result rate (a sudden jump means a bad build), and blocklist hits.

Step 8: Final Design Walkthrough

Final Design
Architecture
Read pathLearningBrowserdebounce + cacheCDN edgeprefix cacheSuggestion svcmerge + filterTrie shards4 shards x 3 copiesUser historykey-value storeBlocklistbuild + serve timeSearch servicelogs queriesLog queueBatch +trendingcounts, scoresTrie buildersnapshotson missboostfiltersnapshot

Solid arrows are synchronous requests. Dashed arrows are asynchronous, cached or fallback paths.

Request flow

Suggest: the browser debounces, checks its cache, then calls the CDN. On a miss the suggestion service normalizes the prefix, routes to the right trie shard, reads the precomputed top 10, merges personal history, filters with the blocklist and returns a cacheable response. Search: the search service serves results and logs the query to the queue.

Data flow

Raw query events flow search service, queue, object storage. Counts flow from batch jobs into the builder. The trie snapshot flows from object storage into the memory of trie shards. Per-user history is read from a small key-value store.

Background processing

Hourly log landing, daily full aggregation and trie build, a 15-minute trending job, snapshot validation and canary rollout, and blocklist refresh.

Critical design decisions

  1. Precomputed top-k on every trie node, so each request is a lookup of a few nodes instead of a subtree search.
  2. Offline build plus atomic snapshot swap, so serving is lock-free and the live trie is never edited.
  3. Multi-layer caching (browser, CDN) justified by the 150,000 peak QPS and slow-changing results.
  4. Traffic-balanced sharding by prefix with 3 replicas, because 40 GB and 45,000 QPS need several machines.
  5. A small trending layer instead of fast full rebuilds, to buy freshness cheaply.
  6. Fail open, because suggestions are an enhancement and never block search.

If time remains, discuss multi-region deployment (a trie copy per region, with country-specific rankings) and typo tolerance using edit-distance lookups on top of the trie.

Common Interview Questions

Finished this lesson?

0 of 44 lessons done · 0% of the course