Building a Type-Ahead Suggestion Service for a Large Search Box
System DesignModel answerLast updated
Design a low-latency type-ahead service that returns ranked, personalized, typo-tolerant, multilingual query suggestions while filtering abusive content and protecting user privacy.
Problem
You are asked to design the type-ahead feature of a large consumer search product. As a user types into the search box, the system should show a short list of likely full queries.
Requirements
- The round trip for each keystroke must stay under 100 ms.
- Suggestions should be personalized to the user and should surface currently trending queries.
- The system must tolerate misspellings and work across multiple languages and scripts.
- It must prevent abuse (spam, offensive or harmful completions) and respect user privacy.
What to cover
- Overall architecture: how query data is collected, how the index is built, and how requests are served.
- The ranking approach, including how global, trending, and personal signals are combined.
- Caching at each layer.
- How you would measure quality, both offline and online.
State your assumptions about scale, and call out the trade-offs you make.
Hints
Hint 1
Work backwards from the latency budget: after network and rendering time, only a small slice remains for the server, which pushes you toward in-memory lookups with precomputed results per prefix.
Hint 2
Separate the slow-moving part (a large immutable index rebuilt in batch) from the fast-moving part (a small streaming overlay for trending queries), and merge them at request time.
Hint 3
Treat safety and privacy as pipeline stages rather than afterthoughts: require a minimum number of distinct users per query before it can be suggested, and filter both when building the index and when serving.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
Functional: return the top 5-10 completions for a prefix; blend global popularity, trending, and personal history; handle typos and many scripts; never show spam, offensive, or personally identifying queries.
Non-functional: p99 under 100 ms end to end; highly available but allowed to degrade (showing nothing is better than blocking search); eventual consistency is fine.
Rough numbers (assumptions): 500M daily users x 10 searches x ~6 suggest calls per search (after client debouncing) is about 30B requests/day, roughly 350K QPS average and ~1M QPS at peak. If there are ~100M distinct filtered queries per language at ~25 bytes each, a trie or FST with top-k lists fits in 10-30 GB per language/region shard, so it lives in RAM. With 40-60 ms lost to network and rendering, the server gets roughly 20 ms p99. That rules out disk on the hot path.
2. API and client behavior
GET /suggest?q=...&lang=...&locale=... returns a list of {text, type, highlight} plus a TTL.
Client tricks matter as much as the backend: debounce (~50 ms), cancel in-flight requests when the user types more, cache results per prefix locally, filter cached results when the user extends a prefix, and prefetch on focus.
3. Architecture
Data collection. Clients emit search and suggestion-selection events to a log (Kafka). A normalization step lowercases, applies Unicode NFKC, collapses whitespace, and tags language.
Offline index build (hourly to daily).
- Aggregate query counts with exponential time decay.
- Apply a k-anonymity threshold: keep a query only if at least K distinct users issued it (e.g. K=50). Optionally add differential-privacy noise to counts.
- Run toxicity classifiers, blocklists, and PII detectors (phone numbers, emails, name-plus-address patterns).
- Compute static scores and build a per-shard FST or trie in which every node stores its top-k (k about 20-50) completions.
- Publish immutable snapshots to blob storage; serving nodes hot-swap them. Rollback is just pointing at the previous snapshot.
Streaming trending (minutes). A stream processor keeps sliding-window counts (e.g. 5 min, 1 h) and flags queries whose rate spikes versus baseline. Flagged queries pass the same safety and k-anonymity checks (stricter for brand-new entities) and are loaded into a small in-memory delta index on each serving node.
Serving path. Edge cache, then a stateless suggest service sharded by language/region. In parallel it does: base-index lookup, delta-index lookup, personal-history fetch (Redis or similar, ~5 ms budget, skipped on timeout), and fuzzy lookup if needed. Then candidate merge, light re-ranker, final safety filter, response.
4. Deep dives
Prefix index. Storing top-k at each node makes lookup O(prefix length) with no subtree scan. FSTs share prefixes and suffixes, so they compress well. The cost is that updates need a rebuild, which is exactly why the delta index exists. One- and two-character prefixes are few and extremely hot; cache them aggressively everywhere.
Typo tolerance. Use bounded edit distance (1 for short inputs, 2 for longer) via a Levenshtein automaton intersected with the FST, or a SymSpell-style deletion index. Add keyboard-adjacency weights and phonetic keys. Run fuzzy matching only when exact-prefix results are sparse or low-confidence, to protect latency, and penalize candidates by edit distance so exact matches win.
Multilingual. Shard by language and detect it from locale, keyboard, and script. Normalize with NFKC and fold diacritics (cafe matches café). CJK needs IME-aware handling (suggest on composed text, support pinyin/romaji transliteration indexes). Handle right-to-left rendering on the client. For bilingual users, query two shards and merge.
Ranking (two stages).
- Candidate generation: about 50 candidates from the global top-k, trending delta, personal-history prefix matches, and fuzzy matches.
- Re-ranking: a small gradient-boosted tree or tiny MLP under ~2 ms. Features: log decayed popularity, trending z-score, personal recency/frequency, locale match, edit distance, historical CTR at this prefix length, query length, freshness, and a diversity penalty for near-duplicates.
- Train on logged selections with position-bias correction (inverse propensity weighting or randomized interleaving). Boost personal history strongly but cap it at 2-3 slots so discovery survives.
Abuse prevention. Layer defenses: offline toxicity/hate/sexual/violence classifiers, curated blocklists, and a stricter policy for queries about named people. The distinct-user threshold blunts single-actor injection; rate limiting and bot detection on log ingestion stop coordinated boosting; anomaly detection flags spikes from few IPs or devices. Keep a real-time kill-switch denylist that reaches serving in seconds. Filter at build time and again at serve time.
Privacy. Global suggestions come only from k-anonymous queries. Strip PII and use noisy counts where needed. Personal history is stored per user with a TTL, shown only to that authenticated user, and deletable on request. Log retention is limited and identifiers are anonymized in analytics pipelines.
5. Caching
- Client: per-prefix cache plus local filtering.
- Edge/CDN: short TTL (tens of seconds to minutes) for non-personalized responses on popular prefixes.
- Service: the index itself is in memory; hot short prefixes are memoized.
- Personal data: Redis with a tight timeout; on a miss or timeout, return non-personalized results rather than waiting.
Personalized responses should not be cached at shared layers.
6. Reliability
Replicate shards across zones, hot-swap snapshots, shed load by dropping fuzzy and personalization stages first, and keep the base index serving even if streaming or Redis is down. Degrade gracefully instead of failing.
7. Evaluation
Offline: MRR and success@k of the finally issued query given each typed prefix, replayed from logs; coverage; typo-recovery rate.
Online (A/B): keystrokes saved per search, suggestion CTR, search success/abandon rate, p50/p99 latency, and downstream engagement.
Guardrails: share of suggestions flagged by safety review, user reports, diversity, and freshness lag for trending queries.
Common mistakes
- Walking a trie subtree at query time instead of precomputing top-k.
- Running fuzzy search on every keystroke.
- Letting personal history crowd out everything else.
- Skipping position-bias correction when training on click logs.
- Treating safety and privacy as a post-filter only, with no build-time thresholds or kill switch.
- Caching personalized results at shared layers.