Skip to content
Commitwise
Menu
System Design

Design search autocomplete (typeahead)

Design search suggestions that appear within 100 ms of each keystroke for millions of users, with an offline pipeline that ranks completions from query logs, an in-memory prefix index with precomputed top suggestions, sharding and edge caching, freshness for trending terms, and a client that debounces, cancels and caches, with code in Swift, Kotlin, Java and TypeScript.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A user types “s”, then “sw”, then “swi”, and after each letter the search box should already suggest “swift concurrency”, “swiftui navigation”, “switch statement”. The suggestions must appear faster than the user types the next letter (about 100 ms), for millions of users, ranked by what people actually search for. The first prototype ran select … where query like 'swi%' order by count desc limit 10 against the main database on every keystroke, and the database team asked politely for it to stop.

“Design typeahead” is a classic interview question because the trick is to do almost no work at query time: precompute the answers, keep them in memory, cache the popular ones at the edge, and make the client smart about what it asks for.

New to some of these? Open what you need, or skip ahead.

Basics:What is a trie?

A trie (prefix tree) stores words character by character, so all words that start with “swi” share the same path. Finding everything below a prefix takes as many steps as the prefix has characters. The Tries lesson builds one. See trieTrieA tree that stores words character by character, so all words with the same prefix share one path.Open in glossary →.

Basics:What is a CDN?

A CDN (content delivery network) keeps copies of responses on servers close to users all over the world. A response cached there is returned in a few milliseconds without reaching your servers. See CDN (content delivery network)CDN (content delivery network)Servers in many cities that keep copies of your files and answer users from nearby, fetching from your origin only on a miss.Open in glossary → and the CDNs lesson.

Part Not started

Step 1: Requirements and estimates

Functional requirements:

  • After each keystroke, show up to 10 suggestions that start with what was typed.
  • Rank them by how often people search for them, with recent searches counting more.
  • Filter out offensive or unwanted suggestions.

Non-functional requirements:

  • Fast: suggestions should appear in under 100 ms, or they’re useless; the user has typed the next letter.
  • Available: if suggestions fail, search must still work; it’s a helpful extra, not a required step.
  • Fresh enough: popular terms can update every few hours; a breaking news term should appear within minutes.

A useful observation: most keystrokes are short prefixes (“s”, “sw”, “swi”), and the suggestions for “sw” are the same for everyone (unless personalized). That makes caching very effective.

Clarify: suggestion count, ranking signals (frequency, recency, click-through, personalization), languages and scripts, spelling tolerance, content policy, and whether suggestions are queries or entities (products, people). Non-functional: p99 under ~100 ms including the network (so the server has tens of milliseconds), very high read QPS, writes only through the aggregation pipeline, eventual consistency in hours for the base index and minutes for trending terms. Typeahead is a read-optimized, precomputed system: the online path should be a hash lookup plus serialization; all ranking happens offline.

Searches:                 1 billion / day, ~4 typeahead requests per search (debounced)
Typeahead requests:       4e9 / 86,400 s ≈ 46,000 / s average, ~150,000 / s peak
Response:                 10 suggestions × ~30 B ≈ 300 B → ~45 MB / s at peak

Index size:
  distinct queries kept:  100 million (after dropping rare ones)
  prefixes (≤ 20 chars):  ~1 billion prefix entries before dedup, far fewer distinct
  top-10 per prefix:      ~10 × 8 B ids + scores → precompute only prefixes with traffic
  → tens of GB: shard across nodes, keep each shard in memory

Cache:                    prefixes of length 1–3 cover a large share of requests → CDN and in-process caches
  • 150,000 requests per second at peak is far too many for a database query each, but easy for in-memory lookups spread over a few servers.
  • The index is tens of gigabytes, so it’s split (sharded) across servers, each keeping its part in memory.
  • Short prefixes are a big share of traffic and identical for all users, so caching them near users removes most of the load.
  • Top 5–10 per prefix, ranked offline by frequency with time decay (and CTR, personalization optional); content filtering.
  • p99 ~100 ms end to end; online path = lookup + serialize; graceful failure (search still works).
  • ~150k req/s peak; index tens of GB, sharded in memory; short prefixes dominate and are cacheable at the edge.
  • Freshness: hours for the base index, minutes for trending via a streaming path.

Check this part

  1. Why must suggestions appear in about 100 ms?

  2. Where does ranking happen in a typeahead system?

Suggestions within about 100 ms end to end, top 5–10 per prefix ranked by popularity with time decay, for billions of keystrokes a day. Freshness of hours is fine for most terms, minutes for trending ones. Most traffic hits short prefixes, which are the same for everyone, so they cache extremely well.

Part Not started

Step 2: Building and serving suggestions

Typeahead: offline building, online serving

Query logsAggregation jobhourly / dailyIndex artifactTrending streamminutesTypeahead nodesin-memory, shardedCDN / edge cacheApp / browser

Tap a box to see what it does.

The system has two halves that run at very different speeds:

Offline (every hour or day): a job reads the search logs, counts how often each query was searched (recent searches count more), removes unwanted terms, and for every prefix writes down its top 10 completions. “s” → [swift, spotify, …], “sw” → [swift, swiftui, …]. The result is a file, the index.

Online (every keystroke): typeahead servers load the index into memory. A request for “swi” is a single lookup in a map: the answer was computed in advance. No sorting, no counting, no database.

Two more pieces keep it fast and fresh:

  • Caching: responses for short prefixes are cached at the CDN for a few minutes, so most requests never reach the servers.
  • Trending terms: a separate streaming job counts searches from the last few minutes, so a sudden new term (“swift 7 release”) can appear without waiting for the next daily build.

Offline: aggregate completed queries (not keystrokes) with exponential time decay, normalize (case, whitespace, Unicode), drop low-count and policy-blocked terms, optionally blend click-through on suggestions, then emit per-prefix top-K lists, limited to prefixes up to ~20 characters with meaningful traffic. Emit per-shard, versioned artifacts. Serving: each node memory-maps or loads its shard as a hash map from prefix to top-K (or a trie with top-K cached at nodes, more compact for shared prefixes), swaps versions atomically, and replicates for availability. Sharding by prefix ranges risks hot shards (“s” is huge), so shard by a hash of the first few characters, or replicate the small, hot short-prefix set everywhere. Freshness: a streaming top-K (count-min sketch + heap per window) produces trending candidates that the serving layer merges with a boost. Caching: CDN with short TTLs keyed by prefix and locale, plus in-process LRU; personalization is applied on top (client-side or a small per-user service) so the shared response stays cacheable. Safety: filter at build time and again at serve time with a fast blocklist that can be updated without a rebuild.

class SuggestionIndex(private val topByPrefix: Map<String, List<Suggestion>>)   // loaded from the artifact

class TypeaheadService(
    @Volatile private var index: SuggestionIndex,
    private val trending: TrendingTerms,                     // updated every minute from the stream
    private val blocklist: Blocklist,
) {
    fun suggest(rawPrefix: String, limit: Int = 10): List<Suggestion> {
        val prefix = normalize(rawPrefix)
        if (prefix.isEmpty()) return emptyList()
        val base = index.topByPrefix[prefix].orEmpty()       // one map lookup: precomputed offline
        val fresh = trending.startingWith(prefix)            // a handful of rising terms
        return (fresh + base)
            .distinctBy { it.text }
            .filterNot { blocklist.contains(it.text) }
            .sortedByDescending { it.score }
            .take(limit)
    }

    fun swap(newIndex: SuggestionIndex) { index = newIndex }  // atomic: requests see old or new, never half

    private fun normalize(s: String) = s.trim().lowercase().replace(Regex("\\s+"), " ")
}
final class TypeaheadService {
    private volatile SuggestionIndex index;                  // loaded from the artifact
    private final TrendingTerms trending;                    // updated every minute from the stream
    private final Blocklist blocklist;

    TypeaheadService(SuggestionIndex index, TrendingTerms trending, Blocklist blocklist) {
        this.index = index;
        this.trending = trending;
        this.blocklist = blocklist;
    }

    List<Suggestion> suggest(String rawPrefix, int limit) {
        String prefix = rawPrefix.trim().toLowerCase(Locale.ROOT).replaceAll("\\s+", " ");
        if (prefix.isEmpty()) return List.of();
        List<Suggestion> base = index.topFor(prefix);         // one map lookup: precomputed offline
        List<Suggestion> fresh = trending.startingWith(prefix);
        return Stream.concat(fresh.stream(), base.stream())
            .filter(s -> !blocklist.contains(s.text()))
            .collect(Collectors.toMap(Suggestion::text, s -> s, (a, b) -> a.score() >= b.score() ? a : b))
            .values().stream()
            .sorted(Comparator.comparingDouble(Suggestion::score).reversed())
            .limit(limit)
            .toList();
    }

    void swap(SuggestionIndex newIndex) { this.index = newIndex; }   // atomic: old or new, never half
}
  • topByPrefix[prefix] is the whole trick: the answer for “swi” was computed hours ago and sits in memory.
  • Trending terms are mixed in at request time, but there are only a few of them, so it’s cheap.
  • swap replaces the whole index at once when a new one is built; requests in progress keep using the old one.
  • The blocklist is checked at request time too, so a term can be removed immediately, without waiting for the next build.

Predict the output

The typeahead index is sharded by the first letter of the prefix (a–z → 26 shards). Traffic per shard is measured. What do you expect?

Ranking and quality

  • Score: Σ count × decay^(age) per query, plus click-through on suggestions and a penalty for queries that led to zero results.
  • Diversity: avoid ten variants of the same query (“swift”, “swift ”, “swift lang”) by normalizing and grouping.
  • Spelling tolerance: fuzzy matching is expensive online; precompute common misspellings to canonical prefixes offline, or serve a separate “did you mean” path.
  • Evaluation: offline metrics (mean reciprocal rank of the clicked suggestion) and online A/B tests (keystrokes saved, suggestion CTR, search success).
  • Offline: completed queries → normalized, decayed counts → filter → per-prefix top-K (prefixes ≤ ~20 chars with traffic) → versioned per-shard artifacts.
  • Online: in-memory prefix map or trie with top-K per node; atomic swaps; replicas.
  • Shard by hash of a longer prefix; replicate hot short prefixes everywhere; avoid first-letter range shards.
  • Trending via streaming top-K (count-min sketch + heap) merged at serve time; blocklist at build and serve time.
  • CDN + in-process cache keyed by prefix and locale; personalization layered on top to keep shared responses cacheable.

Check this part

  1. What happens on the typeahead server when the user types "swi"?

  2. How do brand-new trending terms appear before the next daily build?

  3. Why not shard typeahead by the first letter?

  4. How do you keep shared responses cacheable when adding personalization?

An offline pipeline aggregates query logs with time decay, filters unwanted terms, and builds for each prefix its top suggestions. Serving nodes load that artifact into memory (a prefix map or a trie with top-k per node), sharded by prefix and replicated, and swap it atomically on each build. Short prefixes are cached at the CDN and in process. A streaming path merges trending terms within minutes.

Part Not started

Step 3: A client that keeps it fast

The app or browser decides how many requests the backend gets, so a good client matters as much as a good server:

  • Debounce: wait about 120 ms after the last keystroke before asking. Fast typists send one request instead of five.
  • Cancel outdated requests: if the user types “swi” while the request for “sw” is still in flight, cancel it. Otherwise a slow “sw” response can arrive after the “swi” one and replace the newer suggestions with older ones.
  • Cache locally: remember responses per prefix. Deleting a letter shows the previous suggestions instantly.
  • Fail quietly: if suggestions fail, show none. The user can still press search.

Client behavior multiplies server load: debounce (100–150 ms), a minimum prefix length (often 1–2 characters), cancellation of in-flight requests on each new keystroke (structured concurrency or switchMap), a per-prefix LRU cache with a short TTL, and local narrowing: when the response for “sw” contains fewer than the limit, results for “swi” can be filtered locally without a request. Send the locale and an app version for cache keys; keep payloads tiny (text plus an id, no rich objects). On mobile, render suggestions without layout work per keystroke, and treat the feature as optional under poor connectivity (skip requests on 2G, rely on recent searches).

@Observable @MainActor
final class SearchModel {
    var query = ""
    private(set) var suggestions: [String] = []
    private var cache: [String: [String]] = [:]
    private let api: TypeaheadAPI

    init(api: TypeaheadAPI) { self.api = api }

    // Called from .task(id: query): SwiftUI cancels the previous run on every keystroke
    func updateSuggestions() async {
        let prefix = query.trimmingCharacters(in: .whitespaces).lowercased()
        guard !prefix.isEmpty else { suggestions = []; return }
        if let cached = cache[prefix] { suggestions = cached; return }
        do {
            try await Task.sleep(for: .milliseconds(120))          // debounce
            let result = try await api.suggestions(for: prefix)     // cancelled if the user types on
            cache[prefix] = result
            suggestions = result
        } catch {
            // cancelled or failed: keep what's shown; suggestions are optional
        }
    }
}
class SearchViewModel(private val api: TypeaheadApi) : ViewModel() {
    private val query = MutableStateFlow("")
    private val cache = LruCache<String, List<String>>(100)

    @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)
    val suggestions: StateFlow<List<String>> = query
        .map { it.trim().lowercase() }
        .debounce(120)                                             // wait for a pause in typing
        .distinctUntilChanged()
        .mapLatest { prefix ->                                     // cancels the previous request
            if (prefix.isEmpty()) return@mapLatest emptyList()
            cache.get(prefix) ?: runCatching { api.suggestions(prefix) }
                .onSuccess { cache.put(prefix, it) }
                .getOrDefault(emptyList())                         // suggestions are optional
        }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    fun onQueryChange(text: String) { query.value = text }
}
// Debounce + cancel with AbortController
let timer: ReturnType<typeof setTimeout> | undefined;
let inFlight: AbortController | undefined;
const cache = new Map<string, string[]>();

function onInput(raw: string, render: (s: string[]) => void): void {
  const prefix = raw.trim().toLowerCase();
  clearTimeout(timer);
  inFlight?.abort();                                     // a newer keystroke makes the old request useless
  if (!prefix) return render([]);
  const cached = cache.get(prefix);
  if (cached) return render(cached);
  timer = setTimeout(async () => {
    inFlight = new AbortController();
    try {
      const res = await fetch(`/typeahead?q=${encodeURIComponent(prefix)}`, { signal: inFlight.signal });
      const suggestions: string[] = await res.json();
      cache.set(prefix, suggestions);
      render(suggestions);
    } catch {
      // aborted or failed: keep what's shown
    }
  }, 120);
}
  • Swift: .task(id: query) cancels the previous run on each keystroke; the Task.sleep is the debounce, and a cancelled sleep stops the request before it starts.
  • Kotlin: debounce(120) waits for a pause, and mapLatest cancels the previous request when a new prefix arrives.
  • TypeScript: clearTimeout is the debounce, and AbortController cancels the request that’s no longer needed.
  • All three cache by prefix and ignore errors, because suggestions are optional.
Spot the bugSuggestions for what you typed a second ago

Tap the line with the bug.

fun onQueryChange(text: String) {
    viewModelScope.launch {
        val result = api.suggestions(text.trim().lowercase())
        _suggestions.value = result
    }
}
input.addEventListener("input", async () => {
  const prefix = input.value.trim().toLowerCase();
  const res = await fetch("/typeahead?q=" + encodeURIComponent(prefix));
  renderSuggestions(await res.json());
});

Production puzzles

Predict the output

The CDN caches typeahead responses for 10 minutes, keyed by the full URL. A marketing app sends ?q=sw&session=8f2c… with a unique session id on every request for analytics. What does the CDN hit rate look like?

Exercisehard

Add personalization

Product wants suggestions to include the user’s own recent searches and favorite topics, ranked above global ones. Design it without destroying cacheability or latency.

›

Which part of the response is personal, and does it have to come from the same request?

SolutionTry it yourself first
  • Keep the global response shared and cacheable at the CDN (prefix + locale).
  • Recent searches live on the device (last ~50 queries); the client filters them by prefix locally and shows matches first, instantly, with no request.
  • Server-side personal signals (favorite topics from account history) come from a small, per-user endpoint fetched once per session, returning a compact list of boosted terms or categories; the client re-ranks the global suggestions with it.
  • Privacy: recent searches can be cleared, aren’t sent to the typeahead service, and sensitive categories aren’t used for boosting.
  • Measure: A/B test suggestion CTR and search success; watch that personalization doesn’t hide globally popular, useful completions.

Predict the output

A client caches the response for 'sw': [swift, swiftui, switch, swim] (only 4 results, fewer than the limit of 10). The user types 'swi'. Does the client need a new request?

  • Debounce 100–150 ms, minimum prefix length, cancel in flight (switchMap/mapLatest, .task(id:), AbortController) so stale responses never win.
  • Per-prefix LRU with short TTL; narrow locally when a shorter prefix returned fewer than the limit.
  • Cache keys: prefix + locale only; no session or user params in shared responses.
  • Fail silently; skip on poor networks; personalize on the client or via a separate per-session call.

Check this part

  1. Why cancel the previous suggestions request on each keystroke?

  2. What does debouncing do?

  3. A session id in the typeahead URL does what to CDN caching?

The client decides most of the load: debounce keystrokes (~100–150 ms), cancel outdated requests so stale responses never overwrite newer ones, cache responses per prefix, filter cached results for longer prefixes locally, and fail quietly. On mobile, keep requests small and avoid doing work on every keystroke on the main thread.

Key takeaways

  • Typeahead is fast because the answers are computed in advance, not at query time.
  • An offline job ranks completions for every prefix; servers keep them in memory.
  • Short prefixes are the same for everyone, so cache them close to users.
  • The client debounces, cancels outdated requests, caches, and fails quietly.
  • Separate the offline ranking pipeline from a lookup-only online path.
  • Shard to avoid hot prefixes; replicate the hot head; swap versioned artifacts atomically.
  • Add freshness with a streaming top-K path and safety with serve-time blocklists.
  • Protect cacheability: clean cache keys, personalization layered on top.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.