Build a Real-Time Search Autocomplete System
System DesignModel answerLast updated
Design an autocomplete service that delivers personalized query suggestions with sub-50ms latency, handling millions of concurrent users and live trend updates.
You're tasked with architecting a search autocomplete system that powers the query suggestion dropdown for a large-scale search platform. As users type each character, the system must return ranked suggestions instantly.
Core Requirements
Your design must support:
- Suggestion delivery: Return the 10 most relevant completions for any input prefix
- Live popularity updates: Incorporate recent search activity so trending topics surface within minutes
- Consistent ordering: When multiple suggestions share identical scores, break ties alphabetically by normalized query text
- Scale: Handle 100 million daily active users generating approximately 150,000 queries per second at peak
- Performance: Achieve P99 response latency below 50 milliseconds measured at the server
Design Scope
Address the following components in your solution:
-
Storage architecture: Select appropriate data structures and backing stores for the suggestion corpus. Justify your choice between trie-based indexing, key-value lookups, inverted indexes, or hybrid approaches.
-
Partitioning: Explain how you'll distribute the dataset across machines to avoid coordination overhead during reads while keeping the system balanced.
-
Multi-tier caching: Identify what should be cached at each layer (edge/CDN, application server, client) with appropriate invalidation policies.
-
Ranking signal computation: Describe how to blend long-term popularity with short-term trending signals, and how to update scores as new search activity arrives without reprocessing the entire corpus.
-
Quality and safety: Outline defenses against spam, coordinated manipulation, and harmful content appearing in suggestions.
Assumptions
- Your corpus contains roughly 100 million servable queries after filtering
- Prefixes are capped at 20 characters
- Eventual consistency is acceptable; trending queries don't need to appear instantly everywhere
- The system must remain available during datacenter or node failures
Hints
Hint 1
Precomputing top results per prefix at write time eliminates expensive ranking during reads, trading storage for latency.
Hint 2
Exponential decay for trending signals can be implemented efficiently by storing scores in log-space with timestamps, avoiding the need to rewrite every entry on each tick.
Hint 3
Short prefixes (1-3 characters) represent a tiny fraction of the keyspace but handle most traffic; replicate these aggressively across all serving layers.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Capacity Planning and Scale Estimation
Start by establishing concrete numbers to anchor the design:
- Query volume: 100M users × 10 searches/day × 4 autocomplete requests per search = 4 billion requests daily, averaging 46K QPS with peaks around 150K QPS
- Corpus size: 100 million servable queries after filtering for quality and safety
- Prefix cardinality: With 20-character max length and typical distributions, expect roughly 500 million distinct prefixes
- Memory footprint: Storing top-10 suggestions per prefix (with a 50-entry buffer for stability) requires approximately 150 bytes per prefix, totaling around 75 GB—easily fits in distributed RAM
Target P99 latency of 50ms server-side. Budget roughly 5ms for load balancing and network, 5ms for application logic, and 2ms for storage lookup, leaving headroom for tail scenarios.
API Design
GET /v1/autocomplete?q=java&locale=en_US&limit=10
Response:
{
"suggestions": [
{"text": "javascript tutorial", "score": 0.91},
{"text": "java vs python", "score": 0.87},
...
]
}
The client debounces keystrokes by 100-150ms and cancels inflight requests when the user continues typing. A separate internal ingestion pipeline consumes search events from a message queue.
Storage Model: Precomputed Prefix Lists
The core insight is to shift computational cost to write time. Every prefix maps to a precomputed, pre-sorted list of the top suggestions, making reads a single O(1) key lookup with no traversal or live scoring.
Schema:
prefix_store: key = (locale, normalized_prefix)
value = [(query_id, score), ...] up to K=50 entries
query_metadata: query_id → {display_text, normalized_form, safety_flags}
score_tracker: query_id → {base_popularity, trending_score, last_updated}
Why not a trie? While tries offer prefix compression, they're challenging to shard, replicate, and fail over in a distributed setting. A distributed key-value store (Redis Cluster, or a custom service backed by RocksDB) provides:
- O(1) reads with predictable latency
- Trivial horizontal sharding and replication
- Battle-tested failure modes
The write amplification (updating up to 20 prefix entries per query score change) is acceptable since updates are asynchronous and batched. Use a trie offline in the batch builder to generate prefix lists efficiently.
Deterministic tie-breaking: Sort by (-score, normalized_text). In Redis sorted sets, store the negative score so ZRANGE returns ascending order; members with equal scores naturally fall back to lexicographic order. Quantize scores to avoid floating-point nondeterminism.
Architecture Overview
Users → Edge Cache → Load Balancer → Suggestion Service (LRU cache) → Prefix KV Store
↑
Search Events → Kafka → Stream Processor (Flink) → Score Updater ──┘
↓
Batch Rebuilder (daily) → Full Snapshot
This lambda architecture combines:
- Batch layer: Daily full recomputation of base popularity scores with safety filtering, producing clean snapshots and serving as disaster recovery
- Streaming layer: Near-real-time updates for trending signals, patching affected prefix lists within seconds
Real-Time Scoring with Exponential Decay
Combine two signals: score = α·base_popularity + β·trending
The trending component uses exponentially decayed counts of distinct users. Naive decay would require touching every score on every time tick. Instead, store scores in log-space anchored to event time:
stored_score = log(event_count) + λ·t_event
Since global decay is multiplicative, it doesn't change relative ordering. Only queries receiving new events need updates—add log1p(new_events) + λ·t_now to the stored score. This keeps the write rate proportional to active queries, not corpus size.
Incremental Top-K Maintenance
When a query's score changes:
- Identify all prefixes of that query (up to 20)
- For each prefix, fetch its current top-50 buffer
- If the query's new score exceeds the buffer's minimum (or the query is already present), insert/update it and re-sort
- Otherwise skip—most updates for tail queries exit early here
- Micro-batch updates per prefix in 10-second windows to collapse writes for hot prefixes
The 50-entry buffer provides stability: a query can drop from position 8 to 15 without immediate eviction. The daily batch rebuild corrects any drift.
Sharding Strategy
Hash-shard on (locale, full_prefix). Each read hits exactly one shard; no cross-shard coordination needed. Writes fan out to multiple shards (one per prefix length) but are asynchronous and idempotent.
Avoid range-sharding by first character—prefixes like "a", "s", "w" would create hot spots.
Hot prefix optimization: The ~50K prefixes of length 1-3 characters handle disproportionate traffic. Replicate these to:
- Every application server's in-process memory
- CDN/edge locations
Use 3 replicas per shard across availability zones. Read from any replica; issue hedged requests to a second replica after P95 latency (~5ms) to trim tail latency.
Multi-Tier Caching
| Layer | Contents | TTL | Purpose |
|---|---|---|---|
| Client | Session-local results per prefix | Session | Filter further as user types |
| CDN/Edge | Generic suggestions for short prefixes | 30-60s | Offload origin for common traffic |
| App Server | Hot prefix results | 5-10s | Absorb spikes, reduce KV load |
| KV Store | Full index | - | Source of truth |
Short TTLs bound staleness well within the 1-5 minute freshness target. Apply the safety deny-list at the application layer after cache hits, so takedowns propagate instantly even for cached entries.
Abuse Prevention and Content Safety
- Count distinct users, not raw events: Cap each user's contribution to 1 per query per time window
- Trust scoring: Weight by account age, engagement history, and device/network reputation; heavily discount bot-detected traffic
- Eligibility thresholds: Require minimum distinct users across diverse networks/geos before a new query can be served
- Anomaly detection: Flag sudden spikes with low user diversity or suspicious referrer patterns
- Content filters: Run classifiers and blocklists for prohibited categories (adult, hate, PII, spam domains); queue sensitive terms (medical, names, tragedies) for human review before trending
- Real-time deny-list: Check every response against a continuously updated blocklist with sub-second propagation
Normalization and Localization
- Unicode normalization: Convert to NFC form, lowercase via locale-aware rules (Turkish 'i' vs English)
- Diacritic handling: Store both original and ASCII-folded versions; match on folded but display original
- Tokenization: Split on whitespace and punctuation; handle CJK via bigrams or language-specific segmenters
- Per-locale indexes: Shard by locale to keep models and stopword lists separate; falling back to English when user locale has insufficient data
Common Pitfalls
- Ignoring write amplification: Every score update touches L prefixes; batch and rate-limit to avoid overwhelming the KV store
- Hot-key bottlenecks: Short prefixes concentrate traffic; must replicate aggressively
- Stale trending signals: With long cache TTLs, breaking news won't surface; balance freshness vs load
- Floating-point tie instability: Different machines may order equal scores differently; quantize and use deterministic tie-breakers
- Coordinated abuse: Count distinct users, not clicks; require diversity signals before serving new queries
Monitoring and Operations
Key metrics:
- P50/P95/P99 latency per layer (client → edge → app → KV)
- Cache hit rates at each tier
- Query score update lag (event timestamp to index visibility)
- Per-prefix QPS to identify hot keys
- Deny-list propagation delay
This design delivers sub-50ms P99 latency by precomputing all expensive work, replicating hot data aggressively, and using eventual consistency to decouple write-path complexity from read-path simplicity.