Building a Query Completion Prediction System
Machine LearningModel answerLast updated
Design an ML system that predicts and ranks query completions in real-time as users type search terms.
You need to design a machine learning system that provides query completion suggestions while users type into a search box. For instance, when someone types "ipho", the system should offer completions like "iphone 15" or "iphone charger".
Your design should address:
- Business goals and metrics: What defines success? Consider response time, suggestion quality, user engagement, result variety, and content safety.
- Data collection and training labels: Where does training data come from? How do you create labels while accounting for biases in user behavior?
- System architecture: How do you structure candidate retrieval versus final ranking? What are the computational trade-offs?
- Model inputs and algorithms: What signals inform predictions? How do you incorporate user history and context? Which algorithms fit the latency constraints?
- Training infrastructure and evaluation: How do you build the offline pipeline? What offline metrics predict online success?
- Production serving: How do you meet strict latency requirements? What caching and fallback strategies work?
- Experimentation and monitoring: How do you run experiments safely? What can go wrong in production?
- Special scenarios: How do you handle new queries that haven't been seen before, sudden spikes in interest for specific terms, and malicious or inappropriate content?
Discuss the full system end-to-end, making concrete technology choices and explaining the rationale behind each decision.
Hints
Hint 1
Think about the two-stage funnel: first quickly find hundreds of plausible completions, then carefully rank the best ones
Hint 2
User clicks are biased—suggestions at the top get more clicks regardless of quality. How do you correct for this in training?
Hint 3
Sub-100ms latency means aggressive caching and precomputation. What can you prepare offline versus what must happen per request?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Query Completion Prediction System
1. Requirements and Success Criteria
Begin by establishing clear scope and scale parameters. For an e-commerce platform, determine whether this serves individual merchant storefronts or a unified marketplace. Both scenarios are viable, though they differ in data availability and personalization depth.
Functional scope:
- Deliver approximately 8 completion suggestions per keystroke with client-side debouncing around 50-100ms
- Handle misspellings and typos gracefully
- Support multi-word queries and potentially enrich suggestions with entity types (products, categories, brands)
- Apply light personalization using recent behavior and location
Scale estimates:
- Assume 10M daily searches, each generating 4-5 autocomplete requests = ~50M requests/day
- Peak traffic around 600-1000 QPS with surge capacity for flash events
- Historical query vocabulary of 100M queries, filtered down to 10-20M viable suggestions
- Latency budget: 100ms end-to-end p99, with server processing under 30ms (split: 5ms retrieval, 20ms ranking, 5ms safety checks)
Success metrics:
- Primary online: Suggestion acceptance rate, keystrokes saved, downstream conversion (purchases per search session)
- Quality guardrails: Zero-result rate after accepting a suggestion, policy violation rate
- Offline evaluation: MRR (Mean Reciprocal Rank), NDCG@8, and Success@K (does the user's final query appear in top K suggestions?)
- Coverage: Percentage of prefix queries that receive at least one suggestion
2. Two-Stage Architecture
Use a candidate generation plus ranking funnel to balance recall and precision under tight latency constraints.
Candidate Generation (high recall, low latency):
- Prefix trie: Precomputed data structure storing top 50 completions per node based on historical popularity. Lookup is O(prefix_length). Shard by locale and load entirely in memory (~10-20GB).
- Fuzzy matching: For typo tolerance, use edit distance (1-2 edits) with keyboard-adjacency awareness. This catches "iphoen" → "iphone".
- Catalog lookup: For merchants with sparse query history, mine product titles, categories, and brand names.
- Session context: Include the user's recent queries from the current session.
- Trending tracker: Maintain a streaming windowed count (last hour) to surface emerging queries quickly.
These generators run in parallel and produce ~100-300 candidates total within 5ms.
Ranking (precision): A gradient boosted decision tree (LightGBM with LambdaMART loss) ranks candidates. GBDTs are ideal for initial deployment: they score hundreds of items in under 10ms on CPU, handle mixed feature types naturally, and provide strong performance. Neural rankers (transformers, deep cross networks) can follow later if needed, potentially distilled from larger models to maintain latency.
3. Features for Ranking
Query-level signals:
- Aggregate popularity: log-scaled counts over multiple time windows (1 day, 7 day, 90 day)
- Trend velocity: ratio of recent to historical popularity (1h/7d) to detect rising queries
- Historical engagement: Click-through rate, conversion rate, average results returned
- Never rank queries with zero historical results highly
Match quality:
- Exact prefix match vs. fuzzy match indicator
- Edit distance between prefix and candidate
- Word boundary alignment (does the match start at word boundaries?)
- Characters remaining to complete the query
Contextual features:
- Shop identifier and vertical category
- User locale and device type
- Time of day and seasonality indicators
- Geographic region
Personalization (apply carefully):
- Cosine similarity to the user's recent query history
- User's category affinity vector (learned from past interactions)
- Price range alignment with user's historical purchases
- Session duration and engagement level
Keep personalization subtle—autocomplete is highly visible and over-personalization can feel invasive. Gate personalized features on explicit user consent.
Entity features:
- Whether the completion maps to an in-stock product
- Product availability and popularity in the current shop
- Price band indicators
4. Training Data and Handling Bias
Training examples come from impression logs: each request creates a ranking group containing the prefix, the list of shown suggestions, and user interactions.
Labeling strategy:
- Direct click on a suggestion: label = 1
- Click followed by downstream purchase: label = 2
- Crucially: Mine the final submitted query. If a user types through suggestions and submits "iphone 15 pro case", retroactively label this as positive for all earlier prefixes ("i", "ip", "iph", etc.). This recovers signal from suggestions that were never shown.
Position bias correction: Top-ranked suggestions receive more clicks regardless of true relevance. Mitigate this:
- Introduce small-scale randomization: swap adjacent positions for ~1% of traffic
- Estimate position-dependent click propensities from this intervention data
- Apply inverse propensity weighting during training, or include position as a training feature then fix it at serving time
Negative examples: Suggestions shown but not clicked, down-weighted by their position.
5. Offline Training Pipeline
Daily batch processing:
- Normalize and clean queries: lowercasing, Unicode normalization, spelling clustering
- Aggregate statistics, filtering by minimum frequency threshold (e.g., 20+ unique users for privacy protection)
- Run safety and policy filters to remove inappropriate content
- Build updated trie and FST (finite state transducer) artifacts
- Retrain the ranking model on a rolling 30-day window
Evaluation methodology:
- Use time-based train/test splits (not random) to avoid leaking future trends into training
- Report MRR, NDCG@8, Success@K, and estimated keystrokes saved
- Slice metrics by prefix length, locale, head vs. tail queries, and shop maturity
- Maintain a golden test set of sensitive prefixes to catch regressions before deployment
6. Production Serving and Caching
Caching strategy:
- Short prefixes (1-3 characters) account for most traffic and change slowly. Cache at edge servers with 5-minute TTL, keyed by (prefix, locale, shop_id).
- Client-side caching: after fetching results for "iph", filter locally for "ipho" while the next request is in flight.
- Personalized reranking applies only to top-20 cached results to maintain latency.
Serving path:
Client (debounce + local cache)
→ Edge cache (popular prefixes)
→ Autocomplete service
→ Candidate generators (parallel)
→ Merge (~200 candidates)
→ ML ranker
→ Diversity + safety filters
→ Top K results
Fallback hierarchy: ML ranker timeout → static popularity ranking from trie → cached results → empty response. Never block the user from typing.
Freshness: Run a streaming pipeline (Kafka + Flink) that maintains sliding-window counts and updates a hot index every 1-2 minutes for trending queries, while the batch trie rebuilds daily.
7. Experimentation and Monitoring
A/B testing:
- Randomize by session or user, not by request (to maintain consistency)
- Primary metric: suggestion acceptance rate
- Guard metrics: latency p99, zero-result rate post-acceptance, policy violations
- Measure long-term effects: does increased suggestion usage improve or harm overall search quality?
Monitoring:
- Real-time dashboards: QPS, latency percentiles, cache hit rates, candidate generator timing
- Data quality: distribution drift in prefix lengths, sudden vocabulary shifts
- Feedback loop detection: Are highly-ranked suggestions becoming more popular simply because they're shown more? Monitor the Gini coefficient of query popularity over time.
8. Special Cases
Cold start (new shops):
- Bootstrap with catalog-based suggestions (product titles, categories)
- Apply transfer learning: use global model predictions weighted by shop similarity
- As shop data accumulates, blend shop-specific and global signals
Trending queries:
- Streaming aggregation over short windows (1 hour) to detect spikes
- Boost candidates with high recent velocity in ranking
- Manual curation for major events if needed
Safety and abuse:
- Maintain blocklists for offensive, violent, or adult content
- Apply real-time toxicity classifiers before showing suggestions
- Rate-limit suggestions for identical prefixes from the same session to prevent scraping
- Never expose queries with very low user counts to protect privacy
Common pitfalls:
- Over-fitting to head queries while ignoring tail performance
- Creating filter bubbles through excessive personalization
- Not accounting for position bias leads to feedback loops
- Ignoring latency variance causes poor user experience
- Failing to handle trending queries makes the system feel stale
This system balances retrieval speed, ranking quality, and scalability while maintaining strict latency requirements and protecting user privacy.