Build a Low-Latency Autocomplete System
System DesignModel answerLast updated
Design an autocomplete service that returns ranked suggestions in under 100ms, handling scale, personalization, and freshness.
You need to design an autocomplete system that delivers suggestions as users type into a search box. The system should support multiple entity types (such as stock symbols, product names, help documentation, and common search queries), return results quickly enough to feel instant, and incorporate both popularity signals and user-specific context.
Your design should address:
- API contract: How clients request suggestions and what the response looks like
- Data structures and indexing: How you store and retrieve prefix matches efficiently
- Ranking approach: How you order results using popularity, relevance, and personalization
- Latency requirements: Achieving sub-100ms P95 end-to-end latency
- Caching strategy: Where and how you cache to reduce load and improve speed
- Freshness: Getting newly created entities into the index quickly
- Scale: Supporting thousands of queries per second with millions of searchable items
- Failure modes: How the system degrades when dependencies are slow or unavailable
- Privacy and compliance: Ensuring user data is handled appropriately
State your assumptions about traffic volume, corpus size, and acceptable trade-offs. Explain the reasoning behind your choices and identify the most critical bottlenecks.
Hints
Hint 1
An in-memory prefix structure that precomputes top candidates at each node eliminates expensive traversals at query time.
Hint 2
Separate the global ranking from the personalization layer so you can cache aggressively at the edge while still tailoring results per user.
Hint 3
Use timeouts and fallback paths: personalization should enhance results, not block them when the user service is slow.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and Scale Assumptions
Begin by clarifying what the system needs to do and what volume it must handle.
Functional scope:
- Return top-K suggestions (typically 8–10) for each prefix a user types
- Support multiple entity types: stock tickers, financial products, articles, popular historical queries
- Personalize using the user's portfolio, watchlist, and recent activity
- Tolerate simple typos and support fuzzy matching
- Get new content searchable within minutes of creation
Non-functional targets:
- P95 latency under 100ms total, with server processing under 30ms
- High availability (99.9%), with graceful degradation when dependencies fail
- Privacy: never expose other users' searches or personally identifiable information
Scale estimate:
- Assume 10 million daily active users, each performing 5 searches, with ~6 autocomplete requests per search after debouncing
- That yields roughly 300 million requests per day, or 3,500 QPS average and 20,000 QPS at peak
- Corpus size: ~10,000 stock tickers, ~5,000 products and articles, ~5 million popular historical queries
- Total index size: approximately 1–2 GB, small enough to fit entirely in memory on each server
This last insight is crucial: we can avoid remote lookups for the core index.
2. API Design
Use a simple GET endpoint so responses can be cached:
GET /api/v1/autocomplete?prefix=app&limit=8&types=ticker,query,article
Authorization: Bearer <token>
X-Request-ID: <uuid>
Response 200 OK:
{
"prefix": "app",
"request_id": "abc123",
"suggestions": [
{
"display": "AAPL — Apple Inc.",
"type": "ticker",
"id": "AAPL",
"score": 0.94,
"reason": "in_portfolio"
},
{
"display": "apply for loan",
"type": "query",
"score": 0.68
}
],
"degraded": false
}
Key design points:
request_idenables joining with click logs for offline analysisdegradedflag signals when personalization was skipped due to timeouts- Clients should debounce input (50–100ms), cancel stale requests, and cache responses locally
3. Data Structures and Indexing
Primary index: prefix trie with precomputed top-N per node
Build a trie where each node stores the globally top 50 candidates by static score for all completions under that prefix. Lookups are O(prefix length) with no subtree traversal needed at query time.
For even better memory efficiency, use a finite-state transducer (FST), which compresses the trie while preserving the same query semantics.
Secondary index: inverted index for fuzzy and infix matching
Tokenize entries and build n-gram indexes to handle:
- Infix matches ("loan" matching "personal loan")
- Fuzzy matches within edit distance 1 for prefixes ≥4 characters
Query this index only when the trie returns fewer than K results, to protect latency.
Entity metadata (stored in a catalog database):
{
id, display_text, type, aliases,
static_score, popularity_recent,
compliance_approved, locale, updated_at
}
User context (stored in Redis, keyed by user ID):
- Recent search queries (capped at 50, with TTL)
- Portfolio holdings and watchlist
- User segment (investor type, membership tier)
Keep user records small (<5KB) so reads complete in 1–2ms.
4. Architecture Overview
Client → CDN → API Gateway → Autocomplete Service (stateless)
↓
┌───────────┼───────────┐
↓ ↓ ↓
In-memory User Store Experiment
Index (Redis) Config
↓
Click/Impression Logs → Kafka
↓
┌───────────┴───────────┐
↓ ↓
Stream Processor Data Lake
(trending, 1–5 min) ↓
Batch Index Builder (daily)
↓
Object Store (versioned snapshots)
↓
Autocomplete Service nodes
Request flow:
- Look up prefix in the in-memory trie → get ~50 candidates
- Merge in trending signals from the streaming layer
- Fetch user context from Redis with 5ms timeout
- Re-rank candidates using a lightweight model
- Filter and return top K
5. Ranking and Personalization
Use a two-stage funnel:
Stage 1: Candidate retrieval from the trie, ordered by a precomputed static score that blends:
- Historical click-through rate
- Global popularity (time-decayed)
- Entity type prior
Stage 2: Re-ranking with a fast model (gradient-boosted trees or logistic regression) that runs in ~3ms on 50 candidates. Features include:
- Prefix match quality (exact vs. fuzzy, position of match)
- Time-decayed popularity and CTR
- Freshness (newly added entities get a temporary boost)
- User affinity: is this ticker in the user's portfolio or watchlist? Was it searched recently?
Critical privacy constraint: Only surface the current user's own search history. The global query corpus must pass a k-anonymity threshold (e.g., used by ≥50 distinct users) and filter out patterns that look like account numbers, emails, or names.
6. Caching Strategy
Three layers:
-
Client-side: Cache results for each prefix. When the user types another character, filter the cached results locally if the previous response had fewer than K items.
-
CDN/edge cache: Cache non-personalized responses keyed by
(prefix, locale, experiment_variant)with 1–5 minute TTL. Short prefixes (1–3 characters) have tiny key spaces and very high hit rates. -
In-process LRU cache: Each service node caches the global top-K per prefix.
Personalization happens after retrieval from cache. Fetch the global top-N, then apply user-specific boosts. This allows aggressive caching while still personalizing every response.
7. Freshness and Data Pipeline
Batch pipeline (daily):
- Aggregate 30 days of click and impression logs
- Apply time decay and compliance filters
- Build the trie or FST snapshot
- Validate: size within ±10% of previous, golden queries return expected results
- Publish versioned artifact to object storage
- Nodes poll and reload atomically
Streaming pipeline (1–5 minutes):
- Flink or Spark Streaming computes trending entities over sliding windows
- Produces a small delta map:
prefix → [(entity, boost)] - Nodes merge this at query time before re-ranking
Catalog events (real-time):
- New entities (IPO announcements, new products) arrive via CDC from the catalog database
- Service applies them to an in-memory overlay immediately
- Deletions act as tombstones, filtering results at query time
8. Failure Modes and Degradation
- User store timeout: Skip personalization, set
degraded: true, return global results. Availability > personalization. - Streaming delta unavailable: Serve from static index. Slight staleness is acceptable.
- Catalog database down: Continue serving from the last snapshot. New entities wait.
- CDN cache miss storm: Rate-limit per-prefix to protect backend; serve stale cached results if available.
- Ranking model error: Fall back to static scores from the trie.
9. Key Trade-Offs and Bottlenecks
Memory vs. latency: Keeping the full index in memory on every node eliminates network hops and keeps P95 latency low, but requires horizontal scaling as the corpus grows.
Freshness vs. consistency: The streaming and overlay approach introduces eventual consistency. New entities may not appear instantly on all nodes.
Personalization cost: Fetching user context adds 1–2ms per request. We mitigate this with aggressive timeouts and fallback to global results.
Privacy vs. relevance: Strict filtering of the global query corpus may remove useful suggestions. Monitor query coverage and adjust thresholds based on compliance requirements.
The most critical bottleneck is re-ranking latency. Keep the candidate set small (~50), use a simple model, and profile inference time carefully.
10. Monitoring and Rollout
- Track P50/P95/P99 latency, cache hit rates, degraded response rate, and user store timeout rate
- Log
request_idwith every impression and click to enable offline evaluation of ranking changes - Use feature flags to control personalization strength and model versions
- A/B test ranking changes on a small percentage of traffic, measuring CTR and user engagement
This design balances low latency, high availability, and personalization while respecting privacy constraints—critical for any user-facing search experience in a regulated environment.