Design: search autocomplete (typeahead)

In one sentence

Precompute the top-K completions per prefix offline from query logs, serve them from an in-memory index behind browser and CDN caches, and answer each keystroke well under 100 ms; merge a trending layer for freshness.

The expensive work (counting and top-K) happens offline; each keystroke is a cache hit or one in-memory lookup.

How it works

  • Budget: keystroke to suggestions under ~100 ms, where a UI still feels instantaneous.
  • Precompute offline: aggregate query logs, then store the top 10 completions for every prefix.
  • Serve from RAM: a trie with top-K per node, or a flat prefix → list map.
  • Short prefixes are shared by everyone, so browser, CDN and server caches absorb most traffic.
  • A small streaming layer adds trending queries, merged with the batch index at query time.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your autocomplete p99 is 900 ms for one-letter prefixes and 20 ms for long ones. For each request, the service walks the trie subtree under the prefix and sorts every match by count. What do you change?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: as the user types, show the top ~10 completions for the prefix, ranked by popularity and freshness (optionally locale and personal history); never suggest blocked terms. Non-functional: keystroke to rendered suggestions under ~100 ms, the limit where a UI feels instantaneous (Nielsen); availability over freshness; suggestions may trail trends by minutes.

Scale (assumed): 100M DAU × 10 searches × ~6 requests per search after debouncing ≈ 6B requests/day ≈ 70k QPS average, ~140k at peak.

Questions I'd ask:

  1. Global or personalized suggestions? Personal ones break shared caching.
  2. How fast must a trending query appear: minutes or a day?
  3. Which languages and scripts? Normalization changes per language.

Data model

Offline, a batch job aggregates query logs into (query, score) with time decay, then keeps the top 10 completions for every prefix up to ~20 characters. Serve it from memory as a trie with a top-K list at each node (Tries (Prefix Trees), Heaps and top-K), or as a flat prefix → list map: simpler code, more memory.

Architecture

Client: debounce keystrokes, cancel stale requests, cache responses per prefix. Edge: non-personalized responses are identical for everyone, so a CDN caches popular prefixes with a short TTL (CDNs and edge caching). Suggest service: each replica holds the whole index in RAM and swaps in a new snapshot after each build. Freshness: a streaming job counts recent queries and publishes a small trending list, merged at query time (Stream processing: windows, watermarks, state).

The hard parts

  1. Top-K per prefix in memory, with an O(prefix length) lookup.
  2. Freshness vs precompute: batch builds for quality, a streaming layer for trends.
Code Build top-K per prefix offline, look it up online
pythonBuild top-K per prefix offline, look it up online
import heapq
from collections import defaultdict

K, MAX_PREFIX = 10, 20

def build_index(scores: dict[str, float]) -> dict[str, list[str]]:
    """Offline (a batch job in production): prefix -> top-K completions.
    A trie stores the same top-K list at each node and shares prefix memory."""
    heaps: dict[str, list[tuple[float, str]]] = defaultdict(list)
    for query, score in scores.items():              # score = decayed count
        for i in range(1, min(len(query), MAX_PREFIX) + 1):
            h = heaps[query[:i]]
            if len(h) < K:                           # bounded min-heap of size K
                heapq.heappush(h, (score, query))
            elif score > h[0][0]:                    # beats the weakest kept
                heapq.heapreplace(h, (score, query))
    return {p: [q for _, q in sorted(h, reverse=True)] for p, h in heaps.items()}

def suggest(index, prefix: str, trending: list[str], blocked: set[str]) -> list[str]:
    p = prefix.lower()
    # Online: one dict lookup, O(prefix length); no subtree walk per keystroke
    batch = [q for q in index.get(p[:MAX_PREFIX], []) if q.startswith(p)]
    hot = [q for q in trending if q.startswith(p)][:3]   # streaming layer
    out: list[str] = []
    for q in hot + batch:                             # dedupe, filter, cap at K
        if q not in out and q not in blocked:
            out.append(q)
    return out[:K]
Real example

Facebook's typeahead (2010): when you focus the search box, the browser preloads your friends, pages and groups, so many queries resolve locally. The rest go to a stateless aggregator that queries leaf services in parallel, a global leaf (pages and apps, the same for everyone) and a graph leaf (your social neighborhood), and merges their prefix matches. A memcached query cache fronts the global service. The engineers' rule: spending more than 100 ms to retrieve a result makes typeahead "stutter".

Trade-offs +3 · −3

+ You gain

  • Query time is one memory lookup, O(prefix length), whatever the corpus size.
  • Non-personalized responses are identical for everyone, so caches absorb most traffic.
  • Offline builds are testable and reversible: validate a snapshot, then swap it in.

− You pay

  • Batch indexes lag: without a streaming layer, a breaking-news query is missing until the next build.
  • Top-K per prefix multiplies memory by the number of prefixes per query.
  • Personalization fights shared caching; it needs its own per-user layer.

Use it when

Completion over a large vocabulary ranked by popularity: search boxes, product, place and people pickers, command palettes.

Avoid it when

Small lists (a few thousand items): ship them to the client and filter locally. Typo-tolerant or semantic matching needs a search engine, not prefix lookup.

Numbers to know 4
  • Traffic: 100M DAU × 10 searches × ~6 requests (assumed) = 6B/day ≈ 70k QPS, ~140k at peak.
  • Budget: ~100 ms keystroke-to-render feels instantaneous (Nielsen, 1993); the network uses most of it.
  • Memory: ~100M prefixes × top 10 × 4-byte IDs ≈ 4 GB plus keys (assumed): replicate, don't shard.
  • Facebook (2010): more than 100 ms to retrieve a result makes typeahead "stutter".
Common pitfalls 4
  • Walking the subtree at query time: fine for zebr, hopeless for a. Precompute top-K per node.
  • No request cancellation: a slow response for ne lands after new and overwrites newer suggestions.
  • Blocklist only at build time: an offensive suggestion stays live until the next build.
  • Putting the user ID in the CDN cache key: every request misses and the edge cache is useless.
Interview questions 3

Answer out loud first, then reveal.

How do you make a trending query show up within minutes?Show answer

I don't rebuild the main index faster; I add a small streaming layer. A stream job counts queries in 5-minute windows, compares each with its baseline, and keeps the fast risers using a count-min sketch plus a heap. Every minute it publishes a small trending list per locale, and the suggest service merges matching entries ahead of batch results. I require many distinct users before anything trends and apply the blocklist, so a bot can't plant suggestions.

Why not just run `LIKE 'prefix%'` on the database?Show answer

A B-tree index makes the prefix match cheap, but not the ranking: I need the top 10 by popularity, so every keystroke would read and sort all matches, millions for a, at ~70k QPS. Precomputing top-K per prefix moves that work offline and leaves an O(prefix length) lookup in RAM. For a few thousand rows at low QPS, the database query is fine.

How do you add personalization without killing the cache?Show answer

I keep the global suggestions cacheable and add a per-user layer beside them. The client fetches the user's recent and frequent searches once per session, or in a parallel call, and merges them above global results locally. The CDN cache key never includes the user, so hit rates stay high. If ranking must be personal, I re-rank the cached global top 10 with a few user features, not a per-user index.

Deep dive 3

Trie vs prefix map, and memory

Walking a trie subtree and sorting at query time is fine for zebr and hopeless for a, which has millions of completions. So precompute: each trie node keeps its top-K list, and a lookup walks at most ~20 characters, then reads the list. A flat prefix → top-K hash map gives the same O(prefix length) lookup with less code and more memory, since prefixes aren't shared. Sizing (assumed): ~100M prefixes × 10 IDs × 4 B ≈ 4 GB plus keys, so the index fits in RAM: replicate it, don't shard it. Off the shelf, Elasticsearch's completion suggester keeps in-memory structures that are fast to query but costly to build.

Ranking and freshness

Score = decayed count (yesterday weighs less than today) plus locale and quality signals; drop queries seen from too few distinct users, so nobody can plant a suggestion. Rebuild the batch index daily or hourly, validate it (size, blocked terms, top prefixes), then swap snapshots. For trends, a streaming job counts queries in short windows, flags the ones rising fast against their baseline, and publishes a small trending list merged ahead of batch results; a count-min sketch keeps those counts in fixed memory (Probabilistic data structures). Apply the blocklist at build time and again at serve time, so a takedown is instant.

Latency budget and caching

Of ~100 ms, the in-memory lookup takes microseconds; network round trips and rendering take the rest, so serve from regions or edge locations near users. The client debounces typing to cut requests, cancels in-flight requests when a new key arrives, and caches responses per prefix. Non-personalized responses are identical for every user, so Cache-Control: max-age lets browsers and the CDN absorb repeats. Personalization (recent searches) comes from a separate per-user list merged on the client, so it never enters the shared cache key.