Build a Ranking Model for User Engagement
Machine LearningModel answerLast updated
Design a complete ML ranking system including data collection, feature engineering, model architecture, evaluation metrics, and production deployment.
You need to build a machine learning system that ranks items to maximize user engagement. Walk through the entire pipeline from data collection to production monitoring.
Start by selecting a specific use case (e.g., ranking video content, suggesting products, ordering search results, or prioritizing social feed posts). Then design:
- Data and labels: How you collect training examples, define positive/negative labels, and handle sampling
- Features: What signals you extract from users, items, and context
- Model: Architecture choice, loss function, and training approach
- Evaluation: Offline metrics and how they relate to online business goals
- Production: Serving infrastructure, A/B testing strategy, and debugging methods
Be concrete about trade-offs. Explain why you make each choice and what problems it solves or creates.
Consider:
- How do you prevent the model from learning patterns that don't generalize?
- What happens when users or items are new to the system?
- How do you know if the model is actually improving user experience?
- What can go wrong in production and how do you detect it?
Hints
Hint 1
Think carefully about temporal leakage—features available at training time might not exist at serving time
Hint 2
Your loss function should align with the ranking objective, not just classification accuracy
Hint 3
Offline metrics that correlate with online success are more valuable than those that don't
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
I'll design a video recommendation ranking system for a content platform, optimizing for watch time while maintaining content diversity.
Problem Formulation
Objective: Given a user and context, rank candidate videos to maximize total watch time over the session while exposing users to varied content.
Prediction target: Probability the user watches at least 50% of a video, combined with expected watch duration.
Data Collection and Labels
Positive examples: Videos where watch_time / video_duration ≥ 0.5
Negative sampling: Critical for efficiency and calibration. I use three sources:
- Impressed but not clicked (displayed in the feed): captures in-session preferences, roughly 10 impressions per positive
- Random sampling from catalog (5% of negatives): prevents model from only learning to distinguish recently-promoted content
- Clicked but abandoned (watched < 10%): teaches the model to avoid clickbait
Temporal correctness: Training examples use only features available before the user's decision. For a video impression at time T, I exclude any features computed after T, including aggregate statistics that would leak future interactions.
Label delay handling: Watch time labels arrive with delay (user may pause and resume). I use a 24-hour attribution window and retrain daily, accepting slight staleness rather than biasing toward short videos with immediate labels.
Feature Engineering
User features:
- Historical preferences: watch time by category/creator (exponentially decayed, last 90 days)
- Session context: time of day, device type, estimated session length
- Engagement velocity: clicks and watches in the last 10 minutes (captures "binge mode")
Item features:
- Content metadata: duration, category, upload recency, creator stats
- Historical performance: global CTR, completion rate, average watch time (with confidence intervals for new videos)
- Content embeddings: learned representations from thumbnail, title, and audio/video signals
User-item interactions:
- Similarity to recently watched content (cosine similarity in embedding space)
- Creator affinity score (prior engagement with this creator)
- Estimated match: dot product of user and item embeddings
Cold start: New users get population-level priors. New videos get creator-level priors plus content-based features from the thumbnail and metadata embeddings.
Model Architecture
Two-tower approach for candidate retrieval (reduces 10M videos to 1K candidates), followed by a gradient-boosted decision tree (GBDT) ranker for the final ordering.
The GBDT ranker uses all features above. I choose GBDT over deep learning because:
- Handles mixed feature types (categorical, numeric) naturally
- Better at capturing feature interactions without manual engineering
- Faster inference (important for ranking 1K candidates per request)
- More interpretable for debugging
Multi-objective modeling: I train two heads:
- Click probability (binary cross-entropy)
- Expected watch time given click (regression, Huber loss)
Final score: P(click) × E[watch_time | click]
This decomposition lets me separately tune for CTR and retention.
Loss Function and Training
Loss: Weighted combination of binary cross-entropy (for clicks) and Huber loss (for watch time), with importance weights inversely proportional to the current ranking position. Items shown higher in the feed get higher weight since they have more impact on user experience.
Class imbalance: The 10:1 negative:positive ratio is handled via:
- Loss reweighting (positives get 3× weight)
- Focal loss component (down-weights easy negatives)
Regularization: L2 regularization and early stopping on a temporally-held-out validation set (train on days 1-20, validate on day 21).
Offline Evaluation
Ranking metrics:
- NDCG@10: Measures ranking quality using watch time as relevance
- MRR: Mean reciprocal rank of first long-watch video
- Coverage@100: Fraction of creator base represented in top 100 predictions (diversity proxy)
Calibration: Predicted probabilities should match empirical rates in held-out data. I bin predictions into deciles and check observed vs. predicted click rates.
Why multiple metrics: NDCG captures overall ranking quality, but optimizing only NDCG can lead to filter bubbles. Coverage ensures we don't collapse to recommending only popular creators.
Offline-online correlation: I validate that improvements in offline NDCG (computed on day T for day T+1) correlate with A/B test wins in session watch time. Without this correlation, offline metrics are not predictive.
Online Evaluation and A/B Testing
Primary metric: Total watch time per user session
Secondary metrics:
- Session length (number of videos watched)
- Return rate (user comes back within 7 days)
- Creator diversity (unique creators watched)
Guardrails: No degradation in:
- Report rate (users reporting problematic content)
- Creator satisfaction (small/medium creators' content must still get distribution)
Experiment design: 1% treatment, 1% control, 98% production model. Run for 7 days to capture weekly patterns. Check for novelty effects by monitoring metric trends over the experiment duration.
Production Serving
Inference pipeline:
- Candidate generation: Two-tower model retrieves 1K candidates (30ms p99)
- Feature computation: Batch-fetch user history and item features (50ms p99)
- Ranking: GBDT scores all candidates (20ms p99)
- Post-processing: Diversity re-ranking (insert different creators in top 10)
Caching: User embeddings cached for 10 minutes, item embeddings cached until content changes.
Monitoring and Debugging
Real-time dashboards:
- Prediction distribution drift (are scores shifting?)
- Feature distribution drift (is device_type distribution unusual?)
- Latency percentiles (p50, p95, p99)
- Error rates and fallback frequency
Quality checks:
- Shadow scoring: Run new model alongside production, log disagreements
- Slice analysis: Break down metrics by user segment, content type, time of day
- Replay evaluation: Log production requests and recompute metrics offline with new models
Common failure modes:
- Position bias leakage: Model learns that top positions get more clicks, reinforces existing rankings. Fix: train with position features or inverse propensity weighting.
- Popularity collapse: Model only recommends viral content. Fix: add diversity constraints and exploration randomness.
- Feedback loops: Model creates its own training data, amplifying biases. Fix: exploration logging (show random items 5% of the time) and propensity-scored evaluation.
Key Trade-offs
- Exploitation vs. exploration: Pure optimization collapses diversity; 5-10% random exploration maintains long-term user satisfaction
- Complexity vs. interpretability: GBDT is more debuggable than neural networks but may underperform on very large feature spaces
- Freshness vs. stability: Retraining daily captures trends but risks instability; weekly retraining is more stable but slower to adapt
This system balances immediate engagement (watch time) with long-term health (diversity, cold-start fairness) through careful metric selection and online guardrails.