Building an End-to-End ML Ranking Pipeline
Machine LearningModel answerLast updated
Design a complete machine learning ranking system for personalized content, covering architecture, features, training, serving, and production considerations.
You're tasked with designing a production machine learning system that ranks and recommends content to users.
Part 1: Describe Your Experience
Walk through an ML system you've built or worked with extensively. Cover:
- The business problem and how you formulated it as an ML task
- Where training data came from and how you constructed labels
- Your feature engineering approach and how features reach production
- The training infrastructure and update cadence
- How predictions are generated and served to users
- Monitoring strategy and how you detect issues
- One significant production incident and what you learned
Part 2: Design from Scratch
Design a ranking system for a high-traffic personalized content feed (video, news, social posts, etc.). Address:
- How you'll define success and optimize for it
- The full serving architecture from request to response
- Candidate retrieval strategy given millions of items
- Model architecture and what signals you'll use
- Feature computation and storage approach
- Training data construction and model update strategy
- Latency requirements and how you'll meet them
- Handling new users and new content
- Preventing filter bubbles and encouraging exploration
- Detecting and responding to model degradation
- Experimentation methodology
Specify scale assumptions, make concrete technology choices, and discuss trade-offs.
Hints
Hint 1
Start Part 1 by clearly stating what metric the business cared about and why your ML formulation was a good proxy for it
Hint 2
For candidate generation, you'll need multiple retrieval strategies working in parallel—no single method can handle both relevance and diversity
Hint 3
Think through the entire feature lifecycle: not just what features to use, but how they're computed in batch vs streaming, stored, and kept consistent between training and serving
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Building an End-to-End ML Ranking Pipeline
Part 1: System You've Built
Strong candidates demonstrate ownership by diving deep into one system rather than superficially covering many. Structure your answer chronologically through the ML lifecycle:
Problem Formulation Start with the business objective and your ML translation. For example: "We wanted to increase revenue from our marketplace. We modeled this as predicting purchase probability within 7 days, combined with estimated transaction value. The combined score let us optimize for expected revenue rather than just clicks."
Data and Labels Identify your data sources explicitly: user behavior logs, item catalogs, purchase transactions, etc. Discuss label construction choices: "We used 7-day conversion windows. Shorter windows gave noisier signals; longer windows made the model too stale. We stratified by price tier because luxury items naturally have lower conversion rates."
Mention bias handling: "Our training data had position bias—top-ranked items got more clicks regardless of quality. We trained with inverse propensity weighting using historical position data."
Feature Engineering Separate your features into categories:
- Batch features computed daily in Spark: 30-day purchase rates, category preferences, aggregate statistics
- Real-time features from stream processing: current session behavior, last-hour trends
- Request-time features: time of day, device type, current inventory
Explain skew prevention: "We logged exactly which feature values were used at inference time, then trained on those logged features. This 'log-and-wait' pattern eliminated most training-serving skew."
Training Pipeline Cover your training cadence and why: "Full retrains every 3 days with incremental updates every 6 hours. Daily retrains were too expensive; weekly was too stale for trending products."
Discuss validation: "We split by time, never randomly, to simulate real deployment. Validation set was always 2-3 days ahead of training data."
Serving Infrastructure Be specific about the stack: "The ranker ran in a Kubernetes cluster with GPU instances for the neural network. P99 latency was 45ms at 50K QPS. We cached user features for 5 minutes and item features for 30 minutes, giving us a 70% cache hit rate."
Monitoring and Refresh List what you monitored: feature distributions, prediction calibration, null rates, business metrics. "We alerted when prediction distributions shifted more than 2 standard deviations from the rolling 7-day baseline. We also tracked per-category conversion rates daily."
Production Issue Close with a real failure: "An upstream service changed their user ID format without warning. Our feature lookup silently failed and returned defaults, causing a 15% drop in conversion. Now we have explicit schema contracts and alert on feature null rate spikes above 1%."
Part 2: Design a Video Feed Ranking System
Requirements and Scale
Clarify the scope upfront:
- Platform: Mobile app with full-screen vertical video feed
- Scale: 300M daily active users, average 15 feed requests per user = ~50K QPS average, 150K peak
- Corpus: 800M videos total, 3M new uploads daily
- Latency: 150ms p99 server-side to return 20 ranked videos
- Out of scope: Ads integration, content moderation (assume pre-filtered)
Success Metrics
Avoid optimizing a single metric. Use a weighted multi-objective function:
score = 0.4·P(watch_complete) + 0.3·watch_time_minutes
+ 0.2·P(like) + 0.15·P(share) + 0.1·P(follow_creator)
- 0.25·P(skip_immediately) - 0.5·P(report)
The weights are learned through online experiments against a north-star metric like D7 retention or daily time spent. Negative weights discourage low-quality engagement. Monitor creator-side health metrics separately (e.g., % of new creators getting traction).
Architecture Overview
Use a progressive refinement funnel:
Request (user_id, cursor)
→ Candidate Retrieval (10K videos)
→ Coarse Ranking (500 videos)
→ Fine Ranking (100 videos)
→ Calibration & Policy (20 videos)
→ Response
Latency budget breakdown:
- Candidate retrieval: 25ms (parallel calls)
- Feature fetching: 35ms (parallel from multiple stores)
- Coarse ranking: 15ms (lightweight model)
- Fine ranking: 50ms (deep model on GPU)
- Policy layer: 15ms
- Slack: 10ms
Candidate Retrieval
Run multiple retrieval strategies in parallel, each returning 2-4K candidates:
Embedding-based retrieval: Train a two-tower model where user and video are embedded into the same space. User tower takes user history and context; video tower takes content features. Serve video embeddings from an approximate nearest neighbor index (FAISS or ScaNN). Compute user embedding on-the-fly. Update video embeddings hourly in batch.
Social graph retrieval: Videos from followed creators and friends. Critical for platforms with strong social features.
Trending/popular: Recent high-engagement videos by geography and category. Helps with exploration.
Cold-start pool: Dedicated retrieval of very recent uploads to give new content a chance.
Deduplicate and merge to get ~10K candidates.
Ranking Models
Coarse ranker: Lightweight gradient boosted trees or small neural network. Scores all 10K candidates quickly using a subset of features to cut down to 500.
Fine ranker: Multi-task deep neural network with shared backbone and task-specific heads for each engagement type. Architecture:
- User tower: embedding lookup for user ID + transformer over last 100 watched videos
- Video tower: pre-trained embeddings from video/audio content + creator features + engagement statistics
- Context features: time, device, location
- Interaction features: user-video affinity scores, category matches
- Combine with cross-attention and feed into task heads
Handle position bias by including position as a training feature but fixing it at inference (e.g., always set to position 5).
Feature Store Architecture
Offline store: Data warehouse with point-in-time correct feature snapshots for training data generation.
Online store: Distributed key-value store (Redis Cluster or similar):
- User features keyed by user_id (last updated activity, preferences, demographics)
- Video features keyed by video_id (engagement rates, content embeddings, metadata)
Feature computation:
- Batch features: Computed daily via Spark jobs—30-day aggregates, long-term preferences
- Streaming features: Computed via Flink—last-hour engagement rates, trending signals, current session state
Training Data and Model Updates
Label construction: Join impression logs with engagement events. Wait 2 hours after impression before finalizing labels to capture delayed engagement. Downsample negatives (no engagement) to 10% to manage data volume, then recalibrate predictions post-training.
Data splits: Always split by time. Use 14 days for training, next 2 days for validation.
Update cadence: Full retrain every 2 days with warm-start incremental updates every 4 hours. This balances freshness against computational cost.
Skew prevention: Log exact feature values used at serving time. Train exclusively on these logged features, never recompute them.
Cold Start Strategies
New users:
- Use collaborative filtering based on demographic/geographic cohorts
- Show trending content with category diversity
- Use onboarding questionnaire to seed initial interests
- Switch to personalized ranking after 10-20 engagement events
New videos:
- Force-allocate 5% of traffic to videos with <1000 impressions
- Use content-based features (embeddings, creator history) before sufficient engagement data
- Boost scoring slightly for first 6 hours after upload
- Monitor performance; demote aggressively if early engagement is poor
Exploration vs Exploitation
Implement epsilon-greedy with decay: Reserve 10% of slots for exploration, decreasing to 2% as user history grows. Use Thompson sampling to efficiently explore new content types. Apply diversity constraints via Maximal Marginal Relevance to prevent repetitive feeds (no more than 2 consecutive videos from same creator or topic).
Detecting Model Drift
Monitor continuously:
- Data drift: Alert on feature distribution shifts (KL divergence >0.1 from baseline)
- Prediction drift: Track mean predicted probability by decile
- Performance drift: Daily per-task metrics (watch rate, like rate) with 5% degradation threshold
- Calibration: Expected vs observed engagement rates in buckets
- Business metrics: Sessions per user, retention, time spent
Set up shadow scoring where new model candidates run alongside production but don't serve results, allowing safe comparison before rollout.
Experimentation Framework
Offline evaluation: AUC, log-loss, and NDCG on held-out time periods. Require improvements on all metrics.
Online A/B testing:
- 2% traffic for 10 days minimum
- Primary: D7 retention and daily time spent
- Guardrails: Skip rate, report rate, creator diversity (Gini coefficient)
- Watch for novelty effects with post-experiment retention checks
Interleaving: For ranking changes, interleave results from two models in the same session for more sensitive comparison.
Long-term holdout: Keep 0.5% of users in a permanent control group to measure compounding effects over months.
Common Pitfalls
- Optimizing for clicks alone leads to clickbait
- Ignoring position bias inflates performance estimates
- Training on recomputed features rather than logged features causes skew
- Not accounting for delayed conversions or engagement
- Over-indexing on popular content creates filter bubbles
- Missing creator-side health metrics leads to winner-take-all dynamics
The key is balancing model sophistication with operational simplicity, ensuring every component can be monitored, debugged, and iterated on independently.