Interview Setup
Interview Prompt
Design a search ranking system that takes a user query and returns the most relevant documents from billions of indexed pages. The system should improve over time using click feedback.
Clarifying Questions (ask before designing)
| Question | Why it matters |
|---|---|
| What is the corpus size and query QPS? | Handling 100K QPS over 100B documents requires hybrid lexical and ANN retrieval with staged ranking rather than brute-force scoring. |
| Offline metric vs online metric: which do we optimize? | Offline evaluation targets NDCG@10 while online evaluation measures CTR@1. They can diverge due to position bias in user click logs. |
| Is personalization required or global ranking? | Personalization introduces a user feature store latency budget of about 5ms and cold start complexity for newly registered users. |
| What is the latency budget for the full pipeline? | A total budget of 200ms requires explicit stage budgets and early exits because retrieval, ranking, reranking, and rendering cannot all consume their maximum isolated latency simultaneously. |
Scope
In scope
- Multistage ranking pipeline from hybrid retrieval through coarse ranking, fine ranking, and business reranking
- Low latency online feature store for inference
- Offline training pipeline with NDCG loss optimization
- Safe model deployment with shadow and interleaving validation
Out of scope (state explicitly)
- Full index construction (covered in Search Engine)
- Web crawling and raw document ingestion
- Ad auction and sponsored listing monetization
Functional Requirements
Start by asking your interviewer for corpus size, query QPS, and the full pipeline latency budget. A corpus of 100B documents at 100K QPS forces a multistage funnel rather than a single monolithic model. Clarify personalization requirements and align on whether offline NDCG or online CTR is the primary evaluation target before detailing LambdaMART or neural rankers.
- Multistage ranking pipeline: Hybrid lexical and ANN retrieval narrows the corpus before coarse ranking, fine ranking, and business reranking.
- Feature extraction: Dynamic extraction of query tokens, document quality indicators, user context, and deep query document interaction signals.
- Multi objective optimization: Balance topical relevance, content freshness, category diversity, safety, and individual personalization.
- Online experimentation: Support shadow evaluation, Team Draft interleaving, and canary A/B experiments.
- Click feedback loop: Safely ingest impressions, clicks, dwell signals, and experiment metadata with position debiasing to refine models.
- Vertical search customization: Adaptable ranking pipelines across web, images, news, and electronic commerce shopping.
Non-Functional Requirements
Address the strict 200ms latency budget, with ~50ms ANN retrieval, ~100ms isolated ranking compute, and ~50ms reranking as component targets rather than additive end to end allowances. The serving path must optimize the actual critical path and use early exit when any component threatens the budget. Explain how offline NDCG and online CTR can diverge because of presentation bias. Detail how position debiasing and automated rollback guardrails protect quality during active model deployments.
- Low Latency: The entire multistage pipeline must complete within 200ms p99.
- High Throughput: Sustain 100K+ queries per second during peak search traffic.
- Freshness: Models update daily with fresh click feedback, while index documents refresh hourly.
- Ranking Quality: Offline NDCG@10 serves as the primary benchmark alongside online CTR@1 tracking.
Capacity Estimations
Scoring 100B documents per query is computationally infeasible. Hybrid BM25 and ANN retrieval produces a bounded candidate pool, after which pruning from 10K candidates to 500 cross encoder inputs makes 100K QPS practical. Feature store access at 2M lookups per second can become a bottleneck before GPU inference, so feature batching and cache locality are part of capacity planning.
| Metric | Calculation | Value |
|---|---|---|
| Queries / sec | Given | 100K |
| Index size | Given | 100B documents |
| Retrieval candidates | ANN top-K | 10K per query |
| Coarse rank input | Bi-encoder scores 10K | ~30ms GPU batch |
| Fine rank input | Cross encoder on top 500 | ~100ms |
| Coarse scoring volume | 100K QPS x 10K candidates | ~1B candidate scores/sec before batching |
| Fine ranking volume | 100K QPS x 500 candidates | 50M candidate evaluations/sec before batching |
| Feature store access | 100K QPS x 20 features | 2M feature values/sec |
| Daily training data | 100K x 86400 x 10 results at sustained 100K QPS | ~86B impression logs/day |
Architecture Diagram
The ranking funnel operates progressively from left to right. Hybrid BM25 and ANN retrieval over 100B documents produces a deduplicated candidate pool of about 10K items in ~50ms. A coarse ranker such as LambdaMART narrows those candidates to 500 in ~30ms, and a cross encoder scores the top 500 in ~100ms as an isolated compute target.
Business rule reranking operates on the final 50 candidates and enforces category diversity, freshness, and final policy checks. Unsafe or disallowed content should also be filtered earlier when reliable metadata is available, so expensive ranking compute is not wasted on known violations. The serving layer enforces the 200ms p99 SLO with explicit admission budgets, batching, cache hits, and an early exit that bypasses the fine model when latency is at risk.
Offline training pipelines optimize NDCG@10 using human relevance judgments paired with debiased click logs. Production deployments progress through shadow evaluation, Team Draft interleaving, and canary rollouts with automated rollback on quality regression.
In the room
Clarify whether personalization is required, because it introduces a user feature store lookup on the critical serving path and creates cold start challenges for unregistered visitors.
Component Deep Dives
Overview
Staff level depth centers on position debiasing, multistage candidate distillation, feature consistency, and safe model deployment using shadow evaluation and interleaving.
Learning to Rank Approaches
Learning to rank approaches differ in their loss formulations. Pointwise methods treat relevance independently, pairwise methods optimize relative preferences, and listwise methods optimize a ranking objective over a result list. LambdaMART is best described as a pairwise lambda based approach that weights pair updates using changes in the target ranking metric such as NDCG.
Pointwise: Treat ranking as regression or classification Input: (query, document) -> Output: relevance score (0-4) Loss: Mean Squared Error (MSE) or cross entropy Problem: Does not optimize relative ranking order directly Pairwise: Predict which of two documents is more relevant Input: (query, doc_A, doc_B) -> Output: P(A better than B) Better than pointwise: learns relative pairwise ordering Example: LambdaMART uses pairwise lambda gradients weighted by changes in a target ranking metric such as NDCG Listwise: Optimize a ranking objective across a whole result list Input: (query, [doc_1, ..., doc_n]) -> Output: ranked list Loss: listwise objectives such as ListNet or ListMLE Advantage: models the full result list rather than isolated pairs
Relevance Labels and Training Data
High quality training combines human relevance judgments with continuous implicit feedback. Human labels provide the gold standard, while click data provides scale once it is debiased for position and selection effects. In practice, monitor propensity estimates for instability and clip extreme inverse propensity weights when necessary so a small number of rare observations does not dominate training.
Expert evaluators judge (query, document) pairs on a calibrated 0-4 scale, providing the highest quality supervised signal. Click logs add scale once they are debiased for position and selection effects. Each impression records the model version, rank position, experiment assignment, retrieval source, timestamp, and query context so feedback can be replayed and analyzed without ambiguity. Dwell time, scroll depth, and shares can reinforce relevance signals when interpreted with care.
Key Features for Search Ranking
Feature categories span static document qualities, dynamic query attributes, and dense semantic interaction embeddings that the ranker combines into unified scores.
Query Features: - Query token length, intent classification (navigational, informational, or transactional) - Named entity tags, historical query frequency, and spell corrected canonical tokens Document Features: - PageRank, domain authority scores, and content freshness timestamps - Document body length, historical click through rate, and spam probability score Query Document Interaction Features: - BM25 score (title, body, and anchor text) and TF-IDF cosine similarity - Optional cross encoder score for final candidates using query and document text - Dense embedding cosine similarity computed via bi encoder models User Features (Personalization): - User search and click history, geolocation, language preference, and device type
Feature Store Architecture
The feature store powers both low latency online inference and reproducible offline model training. Point in time joins eliminate future feature leakage, while explicit feature schema versions prevent training and serving drift.
Feature Store Architecture: - Feature Pipeline: Processes raw event logs via Apache Beam or Flink. Computes rolling aggregations defined in feature registry and writes to online and offline stores. - Online Feature Store (Redis): Low latency storage for real time inference. Keyed by entity_id, returning dense feature vectors in under 5ms. - Offline Feature Store (S3 / Parquet): Historical feature repository. Maintains point in time correct values joined with historical impression labels. - Feature Versioning: Model contracts pin to explicit feature set versions, preserving legacy version schemas until all production rankers migrate.
Serving Optimization and Candidate Budgeting
At 100K QPS, the system cannot rely on raw per query model execution. Retrieval and ranking services batch work aggressively, reuse head query and feature results when safe, and apply early exits when the latency budget is threatened. Candidate budgets are explicit so every later stage receives a bounded workload.
- Head Query Caching: Cache highly repeated query results and stable query features with short TTLs while bypassing the cache for personalized or freshness sensitive searches.
- Micro batching: Group requests over very short windows to improve accelerator utilization without violating the 200ms p99 budget.
- Candidate Budgeting: Treat 10K retrieved candidates and 500 fine ranking candidates as capacity targets. Reduce the fine ranking set when GPU saturation or tail latency rises.
- Early Exit: Skip expensive cross encoder evaluation when an offline validated score margin indicates that the remaining candidates are unlikely to change the top results, or when the remaining latency budget is too small.
Retrieval Quality and Candidate Fusion
Hybrid retrieval should optimize recall before ranking optimizes precision. BM25 and ANN retrieval can run in parallel, then merge and deduplicate their candidates into the bounded 10K pool. Monitor recall at several cutoffs against a sampled exhaustive relevance set so ANN recall regressions are detected before they contaminate downstream ranking metrics.
- Lexical Recall: Preserve strong exact match behavior for names, rare terms, identifiers, and highly specific queries.
- Semantic Recall: Use ANN retrieval to recover paraphrases and conceptually related documents that lexical matching may miss.
- Candidate Fusion: Merge candidates from both sources, deduplicate by document ID, and retain retrieval provenance for downstream features and debugging.
- Recall Guardrail: Alert when Recall@K drops against a stable judged benchmark, even if downstream CTR has not moved yet. This catches retrieval regressions before the ranker can compensate.
- Retrieval Provenance: Record the retrieval source and index snapshot version with each impression so a ranking decision can be reproduced after index refreshes or retrieval model changes.
Model Deployment Pipeline
Safe deployment guardrails reduce the chance that a new ranker degrades user experience. Shadow traffic exposes feature and latency issues without changing responses, while interleaving provides a paired comparison of rankers before canary traffic is increased. Offline NDCG remains the primary judged quality measure, while live monitoring relies on click and satisfaction proxies until enough judged data is available.
Stage 1: OFFLINE EVALUATION Train challenger model, evaluate on holdout test set: Check if NDCG@10 improved >= 0.5% and latency p99 <= 150ms. Stage 2: SHADOW MODE (1-3 days) Both models score every live query asynchronously. Only the champion's results are returned to users. Evaluate: NDCG on labeled shadow samples or judged replay, execution latency, and error distribution. Stage 3: INTERLEAVING EXPERIMENT (3-7 days) Interleave ranked results from both models in the same SERP (Team Draft algorithm). Measure which model's candidate results capture higher genuine clicks. Treat 10x fewer queries as an illustrative sample efficiency target rather than a universal statistical guarantee. Actual sample efficiency depends on query volume, preference strength, and experiment design. Stage 4: CANARY (1% traffic, 2-3 days) Serve challenger output to 1% of live search users. Monitor judged or shadow based NDCG, CTR@1, abandonment rate, and latency p99. Auto rollback triggers if the evaluated quality signal drops > 1%, p99 latency > 200ms, or error rate > 0.1%. Stage 5: GRADUAL RAMP (1-2 weeks) 1% -> 5% -> 25% -> 50% -> 100% with a 2-day bake period per tier. Rollback at any stage executes via dynamic configuration in under 60 seconds.
API Design
API Overview
The primary search API uses POST so the request can carry structured query context and the response can identify the active model version. User identity should come from the authenticated request context rather than a client supplied identity field. Click and dwell feedback streams asynchronously through a decoupled endpoint so feedback collection never blocks search latency. The feedback collector should validate each event against the original impression record instead of trusting model or experiment metadata supplied by the client.
Domain Types
export interface SearchRequest {
query: string;
vertical: "web" | "images" | "news" | "shopping";
limit: number; // API validates a bounded page size, such as 1 through 50
}
export interface AuthenticatedSearchContext {
userId?: string;
locale?: string;
deviceType?: "web" | "mobile" | "tablet";
}
export interface SearchResult {
docId: string;
title: string;
score: number;
snippet: string;
}
export interface SearchResponse {
queryId: string;
results: SearchResult[];
latencyMs: number;
modelVersion: string;
}
export interface ClickFeedbackRequest {
queryId: string;
docId: string;
position: number;
dwellMs: number;
}
export interface RecordedClickFeedback extends ClickFeedbackRequest {
modelVersion: string;
experimentId?: string;
featureSchemaVersion: string;
retrievalSnapshotVersion: string;
}Search API
POST /api/v1/search
Content-Type: application/json
{
"query": "best noise cancelling headphones",
"vertical": "web",
"limit": 10
}
Response: 200 OK
{
"query_id": "q-789",
"results": [
{ "doc_id": "d-456", "title": "...", "score": 0.92, "snippet": "..." }
],
"latency_ms": 142,
"model_version": "ranker-v47"
}Click Feedback (async)
The client submits only event fields that it can observe. The collector resolves model version, feature schema version, retrieval snapshot, and experiment assignment from the stored impression record so clients cannot forge training lineage.
POST /api/v1/feedback/click
Content-Type: application/json
{ "query_id": "q-789", "doc_id": "d-456", "position": 1, "dwell_ms": 4200 }Common Error Responses
400 Bad Request: invalid input, missing required fields, or malformed JSON payload 401 Unauthorized: missing or invalid authentication token or API key 403 Forbidden: authenticated caller lacks required permissions for this resource 404 Not Found: requested resource ID does not exist 409 Conflict: duplicate write or version conflict, retry with a unique idempotency key 422 Unprocessable Entity: syntactically valid request failed semantic business validation 429 Too Many Requests: rate limit quota exceeded, client should honor Retry-After header 500 Internal Error: unexpected server failure, retry safely with an idempotency key 503 Service Unavailable: downstream dependency is unavailable or overloaded, retry with exponential backoff 504 Gateway Timeout: search index shard responded slowly, narrow query parameters or retry
Data Model
Online Feature Store (Redis)
user_features:{user_id} -> Hash (embedding, history, locale)
doc_features:{doc_id} -> Hash (pagerank, freshness, spam_score)
query_runtime:{query_hash}:{doc_id} -> short-TTL cache for reusable query-doc features
Cross encoder scores are computed online for final candidates rather than stored as canonical document features.Offline Training Store (S3 / Parquet)
Columns: query, doc_id, label (0-4), features[], timestamp, model_version, feature_schema_version Partitioned by: date/hour Point in time joins: feature snapshot captured at impression time to avoid data leakage
Impression Log Schema
Every served result should carry enough context to reconstruct the ranking decision and separate experiments during training. This prevents feedback from being attributed to the wrong model version or feature snapshot.
{
"query_id": "q-789",
"doc_id": "d-456",
"position": 1,
"model_version": "ranker-v47",
"feature_schema_version": "features-v12",
"retrieval_source": "bm25+ann",
"retrieval_set_version": "retrieval-v8",
"experiment_id": "exp-12",
"timestamp": 1710000000
}Fault Tolerance
- Model failure: Fall back immediately to deterministic BM25 keyword scoring if ML inference fails, while retaining safety and policy filters.
- Feature store unavailable: Serve requests with cached default feature vectors or nonpersonalized defaults rather than dropping queries.
- Latency spike: Dynamically bypass the cross encoder fine ranking stage and serve coarse ranking results under traffic surges.
- Index failure: Route traffic to warm replica index shards while rebuilding failed partitions asynchronously.
- Training and serving skew: Freeze the affected model rollout when feature schema versions diverge, then compare online feature distributions with point in time training snapshots before resuming traffic.
- Feedback pipeline delay: Continue serving the current model while monitoring stale training data and prevent delayed feedback from being mixed into the wrong model or experiment cohort.
Additional Considerations
System Comparisons and Related Links
- Search Engine: Provides crawling, tokenization, inverted index construction, and lexical retrieval that supplies candidates into this Learning to Rank pipeline.
- Vector Database: Manages high dimensional dense document and query vectors for the under 50ms Approximate Nearest Neighbor (ANN) retrieval portion of candidate generation.
- User Analytics Pipeline: Aggregates impression logs, clicks, and dwell events to construct debiased training datasets and compute rolling click through rate features.
Evaluation Metrics Overview
Offline Quality Metrics: Normalized Discounted Cumulative Gain (NDCG@K) serves as the primary metric, supplemented by Mean Average Precision (MAP) and Mean Reciprocal Rank (MRR).
Online Behavioral Metrics: First position click through rate (CTR@1), search abandonment rate, time to first click, and pogo sticking bounce rates reflect live user satisfaction.
Privacy, Abuse, and Data Governance
Ranking systems learn from behavioral signals, so logging and feature storage need explicit retention and access controls.
- Query privacy: Minimize personally identifying information in search logs, apply access controls, and define retention windows for raw queries and click events.
- Feature access: Restrict user history, geolocation, and personalization features to authorized ranking services and avoid exposing them to downstream analytics consumers unnecessarily.
- Abuse resistance: Rate limit synthetic clicks, detect repeated automated interactions, and keep experiment traffic separate from training data until quality checks pass.
- Training lineage: Keep model version, feature schema version, and experiment assignment with each impression so training examples remain auditable and reproducible.
Interview Walkthrough
- 25 minute interview progression
Balance the machine learning pipeline with systems latency constraints.
- Distinguish retrieval recall (BM25 and ANN) from learning to rank scoring stages (5 min)
- Explain click log training data with position debiasing and propensity scoring (6 min)
- Cover feature engineering categories spanning query, document, and interaction signals (5 min)
- Detail offline NDCG evaluation and shadow/interleaving deployment safety (5 min)
- Discuss hybrid semantic embedding and keyword score fusion tradeoffs (4 min)
- Emphasize the multistage funnel: high recall hybrid candidate generation followed by coarse ranking, fine ranking, and final policy and diversity checks.
- Detail position debiasing using Inverse Propensity Scoring so top ranked documents do not unfairly dominate training labels.
- Structure features into query only, document only, and deep interaction features with point in time consistency.
- Explain offline NDCG evaluation and why live interleaving can detect subtle relative quality differences efficiently when the two rankers return comparable candidate sets.
- Highlight the common pitfall of optimizing solely for click through rate, which incentivizes sensational clickbait over genuine satisfaction.
Serving Reliability and Failure Boundaries
Retrieval Failure and Partial Degradation
Search should degrade progressively rather than fail the entire request when one retrieval path is unavailable. The serving layer can fall back from hybrid retrieval to BM25, from fine ranking to coarse ranking, and from personalized features to global defaults while continuing to enforce safety and policy filters.
Training Data Sampling and Lineage
The 86B raw impression calculation is an upper bound on daily event volume at sustained 100K QPS. Training systems normally sample or weight impressions, retain impression lineage, and preserve feature schema and model versions so the reduced training set remains statistically representative and reproducible. Click events should join to that impression lineage by query ID and document ID, with server recorded attribution, rather than accepting model or experiment labels from the browser.
Engineering Trade-offs
NDCG Calculation and LambdaMART Gradients
Query: "best noise cancelling headphones" 5 results, human relevance judgments (0-4 scale): Position 1: Result A -> relevance = 3 Position 2: Result B -> relevance = 2 Position 3: Result C -> relevance = 0 Position 4: Result D -> relevance = 1 Position 5: Result E -> relevance = 0 Step 1: DCG = Sum (2^rel_i - 1) / log2(i + 1) Pos 1: (2³-1)/log2(2) = 7.000 Pos 2: (2²-1)/log2(3) = 1.893 Pos 3: (2^0-1)/log2(4) = 0.000 Pos 4: (2¹-1)/log2(5) = 0.431 Pos 5: (2^0-1)/log2(6) = 0.000 DCG@5 = 9.324 Step 2: IDCG (ideal order: [3, 2, 1, 0, 0]) = 9.393 Step 3: NDCG = 9.324 / 9.393 = 0.993 LambdaMART illustration: swapping C and D changes NDCG by approximately 0.007 The lambda update is proportional to the metric change and also depends on the model's current pairwise score difference
Semantic Search vs Keyword Search
Production search platforms often use a hybrid scoring baseline that combines BM25 keyword matching with dense embedding cosine similarity. A learning to rank model can then learn the contribution of both signals instead of treating lexical and semantic retrieval as mutually exclusive engines.
score = α x BM25_score + β x embedding_similarity. The coefficients can be learned by the LTR model, with both values supplied as ranker features rather than fixed application constants.
Review
How helpful was this walkthrough?
Click a star to rate. We actively use this feedback to refine and update our system design content.
Discussion
Share your thoughts, ask questions, or help others.