Build a Real-Time Query Suggestion Platform
System DesignModel answerLast updated
Design a scalable service that returns ranked autocomplete suggestions as users type search queries, handling billions of requests per day with sub-100ms latency.
You're tasked with building a query suggestion platform that powers autocomplete for a high-traffic search application. When users type into the search box, your system must return relevant completions instantly.
Design a solution that addresses:
-
Requirements and scope: What core features must the system support? Consider completion matching, how results should be ordered, whether suggestions should adapt to individual users, and how quickly new popular queries should appear.
-
API contracts: What endpoints would you expose? Consider both the user-facing query interface and any administrative or ingestion APIs needed.
-
Data architecture: How would you organize and persist the suggestion corpus? What about auxiliary data like user activity or popularity metrics?
-
Lookup performance: How do you achieve millisecond-scale prefix matching across millions of possible completions? What data structures and indexing strategies work at this scale?
-
Result ordering: How would you incorporate signals like query frequency, current trends, geographic relevance, and personal search history into a scoring function?
-
Operations at scale: How does the system handle continuous updates from user activity, maintain fresh indexes, invalidate stale cache entries, and serve hundreds of thousands of queries per second?
-
Design trade-offs: What compromises would you make between response speed, memory footprint, result freshness, and engineering complexity?
Walk through your design choices, justify architectural decisions with concrete numbers, and discuss failure modes and mitigation strategies.
Hints
Hint 1
Think about immutable index snapshots vs. streaming updates—which signals need real-time processing?
Hint 2
Consider the memory footprint of storing precomputed results per prefix vs. computing them on demand.
Hint 3
Edge caching works well for short prefixes that generate most traffic but contain least user-specific signal.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-Time Query Suggestion Platform
1. Requirements Clarification
Functional Requirements
Completion matching: Return 5-10 suggestions for any typed prefix. Input normalization includes lowercase conversion, whitespace trimming, and Unicode normalization (NFKC). For simplicity, exclude fuzzy matching unless prefix length exceeds 3-4 characters.
Result ordering: Blend multiple signals—historical query frequency, real-time trending activity, geographic/language context, and individual user search patterns.
Personalization: Authenticated users see their recent searches surfaced when relevant. Anonymous sessions receive globally popular results.
Freshness expectations: Viral or breaking-news queries should appear in suggestions within 5-10 minutes. The bulk corpus can refresh hourly. Safety-related removals (harmful content, PII) must propagate in seconds.
Non-Functional Requirements
Latency: Target p99 backend latency of 20ms, allowing ~100ms end-to-end with network overhead and client rendering.
Availability: Staleness is acceptable; outright failures are not. Design for 99.9%+ uptime.
Scale estimation (state assumptions clearly):
- 100M daily active users × 10 searches/day × 5 suggestion requests per search = 5B daily requests
- Average: ~60K QPS, peak: ~200K QPS
- Suggestion corpus: ~100M unique queries after frequency filtering, ~25 bytes each = 2.5GB text
- Prefix mappings: Assuming prefixes up to 20 chars and pruning rare ones yields ~500M-1B prefix entries. At ~120 bytes per entry (10 suggestion IDs + scores + metadata), total storage is 60-120GB—easily fit in distributed memory.
2. API Design
User-facing query endpoint:
GET /suggest?q={prefix}&lang=en®ion=US&limit=10&uid={session_id}
Response:
{
"results": [
{"text": "weather tomorrow", "source": "trending", "confidence": 0.95},
{"text": "weather radar", "source": "popular", "confidence": 0.88}
],
"version": "20240601-1430"
}
Optional authentication token identifies users for personalization. Set Cache-Control: max-age=120 for anonymous short-prefix requests.
Administrative APIs (internal):
POST /admin/corpus/add {"text": "...", "lang": "en", "boost": 1.5}
DELETE /admin/corpus/remove/{id}
POST /admin/blocklist {"pattern": "...", "expiry": "..."}
Organic popularity comes from streaming logs, not direct API writes.
Client behavior: Debounce keystrokes (100-150ms), cancel in-flight requests when new characters arrive, cache responses locally to avoid redundant fetching when typing forward (e.g., "weat" → "weath" can filter client-side).
3. Data Modeling
Suggestion repository (durable store—PostgreSQL, DynamoDB):
- Schema:
{id, text, normalized_text, language, region, base_score, created_ts, manual_boost, status}
Prefix lookup index (in-memory serving layer):
- Structure:
(lang, prefix) → [(suggestion_id, composite_score)]top-10 per prefix - Store suggestion IDs rather than full strings; resolve via shard-local dictionary to save memory
User activity store (Redis, Memcached):
- Schema:
user_id → [{query, timestamp, frequency}]last 100-200 queries with 90-day TTL
Trending aggregates (stream processor output):
- Rolling window counts:
(lang, query, time_bucket) → event_count
4. Architecture Overview
Request flow:
- Client sends debounced request
- CDN/Edge cache serves anonymous 1-3 character prefixes (small keyspace, high hit rate)
- API gateway routes to suggestion service
- Suggestion service (stateless) orchestrates:
- Parallel fanout to: prefix index shard, trending service, user history store
- Merge candidates (~50 items)
- Apply scoring model
- Filter against real-time blocklist
- Return top-K
- Prefix index cluster: In-memory shards with replication for throughput and fault tolerance
Data pipeline:
Batch pipeline (hourly/daily via Spark):
- Consume search logs from Kafka/data lake
- Aggregate query frequencies with time decay (exponential: score × e^(-days/30))
- Filter spam, PII, low-frequency outliers
- Generate immutable index snapshots → object storage
- Serving nodes perform atomic swap from old to new snapshot
Stream pipeline (Flink/Kafka Streams for trending):
- Compute sliding 10-minute windows of query rates
- Compare to baseline rates to detect velocity spikes
- Write trending deltas to small, frequently-refreshed index
- Query-time merger combines global + trending results
5. Prefix Lookup at Scale
Data structure choices:
Hash table approach (prefix → top-K list):
- Simplest implementation: O(1) lookup per prefix
- Memory overhead: no shared structure, but acceptable at 60-120GB distributed
- Best for mutable systems
Trie with cached top-K at nodes:
- Walk trie O(|prefix|), retrieve precomputed top-K at terminal node
- Without caching, would need full subtree traversal—too slow
Finite State Transducer (FST):
- Shares common prefix/suffix structure, achieves 5-10× compression vs. flat hash
- Immutable by design—perfect for snapshot-based rebuilds
- Libraries: Apache Lucene FST
Sharding strategy:
- Avoid alphabetic range sharding (letters like 's', 'a', 'c' become hotspots)
- Use consistent hashing on
hash(lang + prefix)to distribute uniformly - Each prefix lookup hits exactly one shard (self-contained top-K)
- Replicate shards 3-5× for read capacity and availability
- Hot prefixes further cached in local LRU (in-process) and edge layers
Boundary conditions:
- Cap indexed prefix length at 20 chars; longer queries fall back to backend search or return empty
- Prune prefixes where top completion falls below frequency threshold
6. Ranking Model
Two-phase approach:
Phase 1: Candidate retrieval (~50 items):
- Top-10 from primary language index
- Fallback to broader language group, then global if sparse
- Top-10 from trending delta index
- User's personal history matches (if authenticated)
Phase 2: Scoring and reranking:
Start with linear combination, evolve to gradient-boosted decision tree trained on click-through logs:
score = α·log(decayed_frequency)
+ β·trend_velocity
+ γ·geo_match
+ δ·user_affinity
+ ε·editorial_boost
- penalties
Popularity signal: Time-decayed frequency with 14-30 day half-life prevents stale queries from persisting indefinitely.
Trending signal: Current window rate divided by historical baseline (not absolute count, which favors evergreen queries). Detect acceleration, not just volume.
Geographic/language matching: Build separate indexes per locale; prioritize exact locale matches over language-level fallbacks.
Personalization: Boost user's own queries by recency and repetition count. Cap personal results (e.g., max 2 of 8) to maintain diversity. Apply only at merge time so global indexes remain fully cacheable.
Deduplication: Collapse near-duplicates (whitespace variants, singular/plural) before final ranking.
Safety filter: Apply blocklist check as final gate—always enforced at query time for immediate effect.
7. Handling Updates and Scale
Cache strategy:
- Edge/CDN: 60-120s TTL for anonymous short prefixes (1-3 chars)
- Application-level LRU: Hot prefixes with 10-30s TTL
- Stale cache is acceptable; cache misses trigger backend load shedding via circuit breakers
Index updates:
- Batch updates: Build full snapshot, deploy to canary nodes, monitor latency/error rates, roll out
- No in-place mutations—immutable snapshots prevent partial/corrupted state
- Keep two versions loaded briefly during transition for zero-downtime swap
Trending updates:
- Write delta index every 5-10 minutes
- Merge at query time (fast—only ~100 trending items)
- Short TTL (60s) since this data changes frequently
Removal propagation:
- Urgent removals (blocklist) bypass index rebuild—filtered at query time via in-memory bloom filter or small hash set, replicated across all nodes with <5s propagation
Load management:
- Request coalescing: Dedupe identical concurrent requests
- Rate limiting per user/IP to prevent abuse
- Graceful degradation: Return cached or partial results under load rather than errors
Monitoring:
- Latency percentiles (p50/p95/p99) per prefix length
- Cache hit rates by layer
- Index build duration and lag
- User engagement (click-through rate per position)
8. Trade-Offs
Latency vs. freshness: Precomputed indexes minimize query-time work but require periodic rebuilds. Trending pipeline bridges this gap for time-sensitive queries.
Memory vs. completeness: Pruning rare queries and long prefixes reduces footprint but may miss niche completions. Acceptable given 95%+ of traffic hits short, common prefixes.
Personalization vs. cache efficiency: User-specific results reduce edge cache effectiveness. Mitigate by capping personal results and maintaining strong global baseline.
Complexity vs. flexibility: Immutable snapshots simplify consistency but require rebuild infrastructure. Mutable indexes would need distributed coordination—harder to reason about.
Common pitfall: Over-investing in fuzzy matching early. Exact prefix matching handles the vast majority of use cases; typo tolerance can be layered later where data shows benefit.