{}DSA Atlas

Design Search Autocomplete (Typeahead)

Return the top suggestions for a prefix within ~50 ms for millions of keystrokes per second — tries with precomputed top-K per node, the offline aggregation pipeline for query frequencies, sharding the trie, multi-layer caching (browser, CDN, service), freshness for trending queries, personalisation, and filtering.

Intermediate → Advanced5 interview questions

1. Requirements

Functional

  • As the user types, return the top 5–10 suggestions for the current prefix, ranked by popularity (and optionally freshness, personalisation).
  • Filter offensive/blocked terms.

Non-functional

  • p99 < 100 ms end-to-end (perceptibly instant), server < 20 ms.
  • 10B searches/day, ~4 keystroke requests per search (with debounce).
  • Eventual freshness: hours for most, minutes for trending.

2. Estimation

QuantityValue
Suggestion requests10B × 4 / 86,400 ≈ 460k/s avg, ~1M/s peak
Unique popular queries kept~100M after thresholding
Trie size~100M queries × ~30 B + top-K pointers → tens of GB (fits in RAM on large servers; shard if needed)
Cache hit ratevery high for short prefixes (most traffic)

3. Data structure: trie with top-K per node

root "b"best buy, bitcoin, bbc "t"twitter, translate… "be"best buy, bed bath… "bi"bitcoin, bing, bible lookup("bi") = walk 2 nodes → return the stored list (no subtree scan)
Precomputing top-K at every node trades memory for O(prefix length) lookups.
Python
import heapq

class Node:
    __slots__ = ("children", "top")
    def __init__(self):
        self.children, self.top = {}, []          # top: list of (score, query), best first

class Typeahead:
    def __init__(self, k=10):
        self.root, self.k = Node(), k

    def build(self, counts: dict[str, float]):
        """Offline: insert every query, then compute top-K bottom-up."""
        for q in counts:
            node = self.root
            for ch in q:
                node = node.children.setdefault(ch, Node())
            node.top = [(counts[q], q)]                 # terminal: itself

        def fill(node):
            cands = list(node.top)
            for child in node.children.values():
                cands.extend(fill(child))
            node.top = heapq.nlargest(self.k, cands)
            return node.top
        fill(self.root)

    def suggest(self, prefix: str) -> list[str]:
        node = self.root
        for ch in prefix.lower():
            node = node.children.get(ch)
            if node is None:
                return []
        return [q for _, q in node.top]

t = Typeahead(k=3)
t.build({"bitcoin": 900, "bing": 700, "bible": 400, "best buy": 1200, "bbc": 650})
print(t.suggest("bi"))     # ['bitcoin', 'bing', 'bible']
print(t.suggest("b"))      # ['best buy', 'bitcoin', 'bing']

4. High-level design

Query cache architecture: client, web server, query API, memory cache, reverse index service and document service
Caching the results of popular queries in memory in front of the services that compute them. Diagram from The System Design Primer by Donne Martin, licensed CC BY 4.0.
serving path browserdebounce CDN cache suggest servicein-memory trie trending overlay(Redis, 1-min) data path search logs Kafka aggregation(Spark, decay, filter) trie builder(hourly) snapshotstore (S3) streaming top-K(Flink, CMS) load + atomic swap
Serve from memory and caches; rebuild offline; overlay trends from a streaming job.

5. Deep dives

Ranking score

score = Σ count(window) × decay(age) + boosts (freshness, locale, click-through rate of the suggestion) − penalties (low quality). Use exponential decay so last week matters more than last year.

Sharding

shard 1: a – bz shard 2: c 3: d – h 4: i–m 5: n – s 6: t–z ranges sized by traffic, not alphabet; shard map held by the router; each shard replicated
Range-shard by prefix using measured load, with a shard map you can rebalance.

Filtering

Blocklists (hate, adult, legal takedowns) applied at build time and at serve time (so removals take effect instantly without waiting for a rebuild).

Client behaviour

  • Debounce 100–150 ms; cancel stale requests (AbortController); ignore out-of-order responses (only render if response prefix = current input).
  • Cache prefix results in memory for the session; prefetch next likely prefix.

6. Trade-offs

DecisionChoiceAlternative
Structuretrie with top-K per nodeElasticsearch completion suggester
Freshnesshourly rebuild + streaming overlayreal-time trie updates (complex locking)
Scalingreplicate full trie; range-shard when too bighash sharding (loses prefix locality)
Cachingbrowser + CDN + servicenone (would need 10× servers)

Interview questions

0 / 5 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.