Building a Click-Optimized Search Suggestion Engine
Machine LearningModel answerLast updated
Design a production ML system that proposes search suggestions as users type, ranking them for clicks while controlling bias, safety, latency, and long-term search quality.
Task
You are asked to design a system that generates and ranks suggested search queries for a large consumer product. Suggestions appear in three places: as-you-type autocomplete, related-search chips on a results page, and zero-prefix suggestions on an empty search box. The system should maximize the click-through rate (CTR) on suggestions without hurting the quality of the search experience.
Walk through an end-to-end design and cover each of the following areas:
- Objectives and constraints. Precisely define how CTR is measured, plus latency and throughput targets, availability, language and locale coverage, and guardrail metrics (search success, abandonment, safety, privacy).
- Architecture. The online request path and the offline/streaming data platform that supports it.
- Logging and labels. Impression and click event schema, attribution windows, how positives and negatives are defined, position and propensity logging, and data-quality handling.
- Features. Text, embedding, popularity and recency, personalization, context, and presentation features, and how you keep online and offline values consistent.
- Candidate generation. Several complementary sources, such as prefix matching, trending queries, embedding-based nearest neighbors, co-click graphs, and a generative model.
- Ranking. Multi-stage ranking, loss choices (pointwise, pairwise, listwise), calibration, and a final re-ranking step for diversity and safety.
- Training and serving. Retraining cadence, and a serving stack that fits the latency budget.
- Exploration and debiasing. Bandit approaches, propensity logging, and correcting for position, selection, and popularity bias, including feedback loops.
- Evaluation. Offline metrics, counterfactual estimators (IPS, SNIPS, doubly robust), and online experiment design (randomization, power, guardrails, ramp-up).
- Personalization and cold start. Signals used, new users, new queries, new markets, and diversity or coverage controls.
- Safety and privacy. Blocklists, classifiers, PII handling, regional policy, and compliance.
- Scale, reliability, and iteration. Sharding, graceful degradation, and what you would do after launch.
State your assumptions (traffic, latency, languages) up front, and call out the trade-offs you are making.
Hints
Hint 1
Start by separating the three surfaces and defining an impression as 'actually rendered and visible'. Then treat the system as recall, then rank, then re-rank, and note that raw CTR can be gamed unless you pair it with a search-success guardrail.
Hint 2
Because users only click what they see, and top positions get clicked more regardless of quality, log the position, the candidate set, and the probability with which each item was shown. Those propensities power both debiased training and counterfactual evaluation.
Hint 3
Work backwards from the latency budget: allocate milliseconds to features, parallel recall, a light ranker, a heavy ranker, and re-ranking, then decide what must be precomputed or cached (hot prefixes, user embeddings, generative outputs).
Hint 4
Keep a calibrated pointwise click head even if you use a listwise loss, since bandits and score blending need real probabilities. Reserve a small exploration slot so new candidates can collect unbiased feedback.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
I would treat this as a recall, rank, re-rank pipeline that optimizes a calibrated click probability, adjusted by expected search success, under hard latency and safety constraints. Bias and feedback loops are first-class concerns, because the model's own outputs determine what data it sees next.
1. Objectives, constraints, metrics
- Primary metric: suggestion CTR = clicks / visible impressions, reported per surface, locale, and position (plus CTR@1 and coverage, the share of requests with at least one suggestion). An impression counts only when the suggestion was rendered in the viewport, not when the server returned it.
- Quality alignment: clickbait suggestions inflate CTR. Pair it with search success (a result click or meaningful dwell after the suggested query), reformulation rate, abandonment, and keystrokes saved.
- Guardrails: safety-violation rate, zero PII leaks, p99 latency, and long-term retention.
- Assumed scale: about 1B daily users, around 100k peak QPS for typeahead, p99 under 50 ms server-side (100 ms for chips), 99.95% availability, 40+ languages including CJK and mixed scripts.
2. Architecture
Request path: client, then edge cache for short popular prefixes, then a suggest orchestrator. The orchestrator builds context from an online feature store, fans out to recall sources in parallel, merges and dedupes (~500 candidates), runs a light ranker (to ~200), then a heavy ranker (to ~50), then a re-ranker, and returns top-K while logging request ID, candidates, scores, and propensities.
Data platform: client and server events flow through Kafka to a stream processor that sessionizes, joins impressions to clicks, and maintains real-time counters. A batch pipeline builds training sets, prefix indexes, and embeddings.
3. Logging and labels
- Impression: request_id, hashed user and session, timestamp, surface, locale, prefix, position, suggestion text, source, model version, score, logging propensity, visibility flag, latency.
- Click: request_id, position, timestamp, downstream outcome (result click, dwell).
- Labels: positive = click; strong positive = click followed by success within ~30 minutes. Negative = visible impression with no click where the user moved on (typed past it or submitted something else). Positions never shown are excluded, not treated as negatives.
- Attribution: a 5 to 30 minute join window with watermarks for late events, deduplicated on (request_id, position).
- Quality: bot filtering, schema registry, null-rate and volume anomaly alerts, sampled audits of join correctness.
4. Features
- Text: prefix-candidate edit distance, match type, length, script.
- Embeddings: multilingual query encoder, similarity to session queries and the user interest vector.
- Popularity and recency: counts over 1h/1d/7d per locale, trend velocity, Bayesian-smoothed CTR.
- Personalization: past queries and clicks, topic distribution, follows.
- Context and presentation: time, device, surface, keystroke count, position, number shown.
Parity: define features once, log the values actually served, and train on those logs. Use point-in-time-correct joins for backfills.
5. Candidate generation
Multiple sources, each with a quota:
- Prefix trie/FST per locale with precomputed top-k per node, plus fuzzy matching and transliteration.
- Trending via streaming heavy hitters (count-min sketch plus velocity), refreshed each minute.
- ANN (HNSW) over query embeddings for semantic matches.
- Co-click / co-search graph for related chips.
- Generative model for long-tail prefixes, precomputed or cached for hot prefixes, with strict timeouts. Outputs must pass a "looks like a real query" filter and safety checks.
6. Ranking
- L1: GBDT or two-tower, pointwise logloss, cheap.
- L2: DCN-style or transformer with multi-task heads: P(click), P(success | click), P(reformulate). Score:
P(click) * (1 + a * P(success|click)) - b * harm. - Loss: pointwise gives calibration (needed for bandits and blending); listwise improves order. Combine both and apply per-surface, per-locale isotonic calibration.
- Re-ranker: MMR or DPP diversity, normalized-form dedupe, safety filter, freshness boost.
7. Training and serving
- Daily retrain on ~30 days of logs, hourly incremental updates to embeddings and counters. Deployment gates: offline NDCG, calibration error, safety eval, then shadow, then canary.
- Latency budget (50 ms): network/orchestration 5, features 5, parallel recall 15, L1 5, L2 12, re-rank and logging 3. Precompute user embeddings per session and cache short prefixes at the edge.
8. Exploration and debiasing
- Reserve one lower slot for exploration using Thompson Sampling (Beta posteriors per candidate cluster) or LinUCB over embeddings.
- Log propensities for every shown item.
- Position bias: position as a training-time feature set to a default at inference, or a two-tower click model separating examination from relevance; validate with small randomized-position traffic.
- Selection and popularity bias: inverse-propensity weighting with clipping, exploration traffic, and caps on how much popularity features can dominate.
9. Evaluation
- Offline: NDCG/MRR on debiased labels, calibration error, coverage.
- Counterfactual: IPS, self-normalized IPS (lower variance), and doubly robust with a reward model. Check effective sample size and clip weights.
- Online: randomize by user, size for the minimum detectable CTR lift, run at least a full weekly cycle, watch guardrails (success, abandonment, latency, safety), then ramp 1%, 5%, 25%, 100%.
10. Personalization, cold start, diversity
- New users fall back to locale and context priors; new queries enter via content and embedding similarity plus exploration; new markets start from transferred multilingual models and seed lists.
- Cap near-duplicates and enforce intent diversity.
11. Safety and privacy
Blocklists, toxicity and sensitive-topic classifiers on both candidates and generated text, k-anonymity thresholds (a query must be issued by many distinct users before it is suggestible), PII pattern scrubbing, regional policy rules, retention limits, and deletion support.
12. Scale and iteration
Shard indexes by locale and prefix range, replicate hot shards, and degrade gracefully: if the heavy ranker times out, serve L1 results; if features are missing, use defaults; if everything fails, serve cached popular suggestions. After launch, monitor drift and calibration, run error analysis by locale, and iterate on sources and objectives.
Common mistakes
- Counting server-returned items as impressions.
- Treating unseen positions as negatives.
- Optimizing CTR with no success guardrail.
- Training on data without propensities, creating a self-reinforcing loop.
- Ignoring training/serving feature skew.
- Running generative models synchronously on every keystroke.