11 minute read

“The user knows what they want. Your job is to tell them before they finish typing.”

TL;DR

Typeahead systems must return suggestions in under 50ms at millions of QPS. A weighted trie with pre-computed top-K candidates at each node makes lookups cost only the prefix walk, avoiding runtime subtree traversal. The architecture combines a static trie built offline from query logs with a dynamic trie for real-time trending topics, all served behind CDN caching and prefix-based sharding. Radix Trees cut memory by merging single-child chains. For the data structure foundations behind this, see the broader ML System Design series, and for how vector search complements keyword retrieval, see Vector Databases.

A massive filing cabinet with cascading drawer labels getting more specific at each level

1. Problem Statement

Typeahead (or Autocomplete) is one of the most heavily used features on the internet.

  • Volume: Every keystroke can trigger a query. If a user types “iphone case”, that’s up to 11 requests.
  • Latency: Must be < 50ms server-side, so the full round trip still feels instant to a human.
  • Freshness: If “Earthquake in Japan” happens, it must appear in suggestions within minutes.

The System Design: Build a backend for a Google-style search bar that suggests top 10 completions based on prefix.


2. Understanding the Requirements

2.1 The Scale (assumed for this design)

  • DAU: 500 Million.
  • Queries: 5 billion searches / day.
  • Keystrokes: ~50 billion typeahead requests / day, about 580K QPS on average.
  • QPS: Peak 1 million QPS. (This requires massive horizontal scaling).

2.2 The Ranking Problem

We don’t just want matching strings.

  • Prefix: “ja”
  • Candidates: “java”, “japan”, “javascript”, “jacket”.
  • We need to return top 5 sorted by Score. Score = Transformation(Frequency, User_History, Location, Freshness)

A common base score is a time-decayed count: each past search of a query contributes exp(-age / tau), so a query searched a million times last year can lose to one searched fifty thousand times this morning. The decay constant tau sets how quickly the system forgets.


3. High-Level Architecture

We need a dedicated Typeahead Service separate from the main Search Service.

[Browser]
      | (GET /suggest?q=sys)
      v
[Load Balancer] --> [CDN (Caches popular: "fa"->"facebook")]
      |
      v
[Typeahead Aggregator]
      |
      +---> [Service Node 1 (A-C)]
      +---> [Service Node 2 (D-F)]
      +---> [Personalization Service (Reranking)]

The aggregator fetches a generous global candidate list (say the top 50) from the trie shard, then the personalization service reranks it with the user’s history and location before the top 10 go back. Global popularity is computed once for everyone; personalization only touches 50 items per request.


4. Component Deep-Dives

4.1 The Data Structure: The Weighted Trie

In RAM, we store a specialized Trie. Each Node contains:

  1. Children Pointers: {'a': Node, 'b': Node}.
  2. Top-K Cache: A pre-sorted list of the top 10 most popular completed queries that pass through this node.

Why Pre-compute Top-K? If we wait until runtime to traverse the whole subtree of “sys” to find “system”, “systolic”… it’s too slow. We aggregate scores offline. At node “s-y-s”, we store ["system", "sysadmin"] directly. Time Complexity: O(L) to walk a prefix of length L, plus O(K) to return the cached list, independent of how many queries the trie holds.

4.2 Data Sharding

The Dictionary is too big for one machine.

  • Option A: Range Partitioning (A-C, D-F)
    • Risk: Hotspots. ‘S’ is popular. ‘X’ is quiet.
  • Option B: Hash Partitioning
    • ShardID = Hash(first 2-3 characters of the prefix) % 100.
    • Catch: A one-character prefix like “s” has no 2-character key. The fix is cheap: the top-K lists for all 1-2 character prefixes are tiny (a few thousand prefixes), so replicate them on every node and cache them at the CDN. Only longer prefixes route to a specific shard.

4.3 Back-of-Envelope Memory Sizing

Assume 100 million distinct queries worth suggesting, averaging 20 characters.

  • Nodes: Shared prefixes collapse a lot of paths, but even a few hundred million nodes is realistic for a naive character trie.
  • Top-K lists: Storing 10 query IDs (4 bytes each) per node is 40 bytes; at 500 million nodes that is about 20GB before counting child maps, scores and the query strings themselves.
  • Levers: Store integer query IDs in the lists and keep strings in one shared table; precompute top-K only for prefixes up to a length cap (say 10 characters) and walk the small remaining subtree at query time; compress single-child chains (Section 11). Together these bring a shard down to a size that fits comfortably in RAM with replicas.

5. Data Flow: The Log Processing Pipeline

How do queries get into the Trie?

  1. Log Collection: Browser emits “User searched: java” -> Kafka.
  2. Aggregation (Spark/MapReduce):
    • Window: Last 7 days.
    • Group By Query. Count Frequency (with time decay).
  3. Filtering: Drop queries below a minimum count, queries containing personal data (emails, phone numbers), and anything on the blocklist (Section 9).
  4. Trie Building (Offline):
    • Worker reads aggregated list.
    • Builds the Weighted Trie.
    • Serializes to file (trie_snapshot_v100.bin).
  5. Deployment:
    • Push file to S3.
    • Typeahead Servers download and hot-swap memory.

6. Scaling Strategies

Offline builds happen weekly. But “Breaking News” needs to appear now. Hybrid Architecture:

  • Result = Merge(Static_Trie, Dynamic_Trie).
  • Dynamic Trie: Size limited (e.g., 200MB). Stores only high-velocity queries from the last 15 mins (via a Storm/Flink stream).

6.2 Sampling

We don’t log every keystroke. We log the final submission. Or we sample 1% of traffic for analytics.

6.3 Client-Side Load Shedding

The cheapest request is the one the browser never sends.

  • Debounce: Wait a short pause (tens of milliseconds) after a keystroke before sending, so fast typists don’t fire a request per character.
  • Cancel stale requests: When “jav” is typed, abort the in-flight request for “ja”.
  • Reuse results: Cache each prefix’s suggestions so backspacing doesn’t refetch. If “ja” returned fewer than K results, every completion of “jav” is already in that list and can be filtered locally.

7. Implementation: A Basic Typeahead Class

class TrieNode:
    def __init__(self):
        self.children = {}
        self.top_candidates = [] # Stores top 5 tuples (score, text)

    def insert(self, word, score):
        # Keep one entry per word (scores get updated), then the 5 highest.
        # A word that falls out of the list can't come back if other scores
        # later drop, which is one reason production systems rebuild offline.
        self.top_candidates = [(s, w) for s, w in self.top_candidates if w != word]
        self.top_candidates.append((score, word))
        self.top_candidates.sort(key=lambda x: -x[0])
        self.top_candidates = self.top_candidates[:5]

class TypeaheadSystem:
    def __init__(self):
        self.root = TrieNode()
        
    def add_query(self, query, score):
        node = self.root
        for char in query:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
            # Crucial: Update the pre-computed top-k at every step
            node.insert(query, score)
            
    def suggest(self, prefix):
        node = self.root
        for char in prefix:
            if char not in node.children:
                return []
            node = node.children[char]
        return [text for score, text in node.top_candidates]

# Usage
ta = TypeaheadSystem()
ta.add_query("amazon", 100)
ta.add_query("amazing", 50)
ta.add_query("am", 10)

print(ta.suggest("am")) 
# Returns ['amazon', 'amazing', 'am'] sorted by score (because we sorted on insert)

8. Monitoring & Metrics

  1. Zero Results Rate: % of prefixes that yield no suggestions.
  2. Keystroke Latency: p99 latency (must be < 50ms).
  3. Selection Rate: How often users click suggestion #3 vs completing the typing.
    • High click rate on #1 = Good Ranking.
  4. Keystrokes Saved: Average characters typed before a suggestion is accepted. This is the metric the product actually cares about.

9. Failure Modes

  1. The “Dirty Words” Problem: The algorithm has no judgment. If users search for hate speech, the Trie suggests it.
    • Mitigation: Strict blocklist filter applied during the Offline Build phase, plus a serve-time filter on the dynamic trie, since trending queries never went through the offline build.
  2. Harmful Trending Completions: During breaking news, a rumor or defamatory phrase about a real person can trend within minutes.
    • Mitigation: Classifier-based filtering on the dynamic trie, a delay or review queue for completions that mention people, and a kill switch to suppress a prefix quickly.
  3. Shard Failure: If ‘S’ shard goes down, nobody can search ‘System’.
    • Mitigation: Replica sets (3 replicas per shard).

Facebook’s search, including typeahead, ran on a system called Unicorn (described in a VLDB 2013 paper). It’s a graph-based search engine. When you type “John”, it doesn’t just look for string “John”. It looks for: Friends named John > Friends of Friends > Celebrities. They use Social Graph Context as a ranking signal, not just global frequency.


11. Cost Analysis

Storing 1 Billion queries in a naive Trie is RAM heavy. Optimization: Ternary Search Trees (TST) or Radix Trees. These compress the storage.

  • Nodes with single child are merged (sys -> tem).
  • Removes most intermediate nodes and their pointers; how much RAM this saves depends on how many long single-child chains the query set has.

Typo tolerance costs extra: matching “javscript” to “javascript” needs fuzzy lookup (Levenshtein automata, as in Lucene’s fuzzy queries, or precomputed deletion variants as in SymSpell). Apply it only when the exact-prefix lookup returns too few results.


12. Key Takeaways

  1. Pre-computation: Never sort at query time. Sort at write time.
  2. Prefix Sharding: Hashing is messy for ranges. Use prefix-based sharding with careful heat-balancing, and replicate the short prefixes everywhere.
  3. Browser Caching: The fastest query is the one served from localStorage.
  4. Privacy: Typeahead leaks intent. Encrypt the channel (HTTPS), anonymize the logs, and filter personal data out before it can become a suggestion.
  5. Safety is a Serving Concern Too: Offline filters miss trending queries, so the real-time path needs its own guardrails.

FAQ

How does a typeahead system return results so fast?

Instead of traversing the entire subtree at query time, each trie node stores a pre-sorted list of the top-K most popular completions that pass through it. This means looking up suggestions for any prefix is just a pointer chase to the right node followed by returning the cached list, so the cost depends on prefix length, not on the total dictionary size.

How do you handle trending searches in a typeahead system?

A hybrid architecture merges a static trie built from weekly offline aggregation with a small dynamic trie (limited to around 200MB) that ingests high-velocity queries from the last 15 minutes via a stream processor like Flink or Storm. The final result is a merge of both sources, ensuring breaking news appears within minutes.

What data structure optimizations reduce trie memory usage?

Ternary Search Trees and Radix Trees compress nodes with single children by merging path segments like “sys” and “tem” into a single node. This eliminates intermediate pointer overhead, and combined with storing integer query IDs instead of strings, makes it feasible to keep very large query sets in memory.

How is a typeahead system sharded across multiple servers?

Prefix-based sharding assigns query ranges to different servers (e.g., A-C on Node 1, D-F on Node 2), though careful heat-balancing is needed since prefixes like “S” see far more traffic than “X”. Hash partitioning on the first 2-3 characters is an alternative that distributes load more evenly but complicates range queries.