Design a Short-Video Feed Ad Ranking System
Machine LearningModel answerLast updated
Design an end-to-end ML pipeline that selects, scores, and ranks ads in a short-video feed under strict latency, handling position bias and multiple competing objectives.
Scenario
A short-video platform serves a continuous feed mixing organic content with sponsored ads. The ad inventory holds roughly one million active creatives, but only a handful of slots per session are available. Your task is to design the ML system that decides which ads to show and in what order.
What You Need to Design
1. Architecture overview Describe a multi-stage pipeline that fits within a 100 ms end-to-end latency budget. Explain what each stage does, how many candidates it processes, and why the pipeline is structured that way.
2. Multi-objective ranking model The platform cares about at least three things simultaneously: whether the user engages with the ad (click-through rate), how much revenue the ad generates (expected CPM), and whether the feed stays healthy over time (avoiding fatigue and reports). Propose a modeling approach that balances these goals, and explain the final scoring formula used to rank and price ads.
3. Position bias An ad shown in the first slot is far more likely to be clicked than an identical ad in slot five, purely because of its position. If you train naively on logged data, the model learns to associate high position with quality rather than learning true ad relevance. Describe a concrete strategy to remove this bias at training time without sacrificing serving-time performance.
4. Delayed conversions A user may click an ad now but complete a purchase hours or days later. Explain the problem this creates for training and propose a practical solution.
5. Real-time adaptation If a user just interacted with three ads in a row, the system should adapt immediately — without waiting for the next daily model retrain. Describe your data pipeline and feature strategy to make this happen.
6. Evaluation Define the offline metrics you would track before pushing a new model, and the online metrics you would use to decide whether to roll it out fully.
Constraints and Assumptions
- ~300 M daily active users, ~15 ad slots served per user per day → roughly 200 K QPS at peak.
- Inventory: ~1 M active ads; after targeting and budget filters, a few thousand are eligible per request.
- Latency budget: < 100 ms p99 end-to-end.
- Billing types include CPM, CPC, and CPA; ranking must output calibrated probabilities, not just a relative ordering.
- The platform runs a second-price auction, so miscalibrated scores directly mis-price inventory.
What a Strong Answer Covers
- A justified two-stage retrieval → ranking split and latency allocation per stage.
- A multi-task model architecture (e.g., MMoE) with clear reasoning about task conflict and negative transfer.
- A position bias solution that is practical at serving time (not just theoretically correct).
- A concrete approach to delayed conversions — either fake-negative correction, a delay-distribution model, or a hybrid.
- A streaming feature pipeline that keeps session context fresh with no model retraining.
- Offline metrics (AUC, calibration, GAUC) and online metrics (CTR, RPM, hide rate, long-term retention) with explicit trade-off awareness.
Hints
Hint 1
Before scoring, you need to shrink 1 M ads to a manageable set. Think about what cheap signals let you cut 99% of candidates before the expensive model ever runs — and what you'd lose by doing that aggressively versus conservatively.
Hint 2
Position bias creates a feedback loop: the model favors high-position ads, so they keep getting shown in high positions, which makes them look even better. A separate shallow tower trained only on position signals — and dropped at inference — breaks that loop cleanly. Think about why you'd drop it at inference rather than just set position = 1.
Hint 3
For delayed conversions, consider what label you assign to a click that has no conversion yet. Treating it as a negative immediately will train the model to underestimate conversion rate. One clean fix is to ingest the click as a negative first, then re-ingest a positive when (and if) the conversion arrives, with importance weights to keep the expected gradient unbiased.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Scale and Constraints
State assumptions before designing. At 300 M DAU with 15 ad slots each, that is 4.5 B ad decisions per day, or roughly 200 K QPS at peak. A 100 ms p99 budget is tight, so latency allocation across stages is a first-class design decision, not an afterthought.
Reasonable budget split:
| Stage | Budget |
|---|---|
| Candidate filtering | 10 ms |
| Retrieval (ANN lookup) | 15 ms |
| Feature fetch | 15 ms |
| Ranking model inference | 40 ms |
| Auction + re-ranking | 10 ms |
| Network slack | 10 ms |
Billing types matter: CPM bids need p(impression value), CPC bids need pCTR, CPA bids need pCTR × pCVR. Because a second-price auction prices on these outputs, they must be calibrated probabilities. A model with good AUC but poor calibration will mis-price ads and either overcharge advertisers or leave revenue on the table.
2. Pipeline Architecture
Stage 1 — Candidate filtering (~1 M → ~10 K). Apply targeting rules (geo, age, interest segments), budget exhaustion checks, and frequency caps with an inverted index. This is cheap, rule-based, and runs in a few milliseconds.
Stage 2 — Retrieval (~10 K → ~500). A two-tower model pre-computes ad embeddings offline; user embeddings run at request time. An approximate nearest-neighbor index (HNSW or ScaNN) returns the top candidates in under 15 ms. Supplement with deterministic sources: retargeting lists and high-bid campaigns that should never be dropped by retrieval. Retrieval optimizes recall, so it can be relatively crude — missing a great ad here is more costly than returning a mediocre one.
Stage 3 — Ranking (~500 → scored list). A deep multi-task model with cross features runs on GPU with request batching. This is where precision matters and where most of the modeling complexity lives.
Stage 4 — Auction and re-ranking. Compute a composite value score, run the auction, then apply business rules: no two ads back-to-back, advertiser diversity caps, brand-safety filters, a fatigue penalty based on session and 24-hour advertiser frequency.
The two-stage split exists because scoring 10 K candidates with a deep network at 200 K QPS is not feasible. Retrieval buys a ~20× compute reduction at the cost of a small recall loss — typically acceptable when retrieval recall at 500 is above 95%.
3. Multi-Task Ranking Model
Tasks to model:
- pCTR — probability of a click or swipe-up
- pCVR — probability of conversion given a click
- p(long view) — user watched most of the ad
- p(hide/report) — negative quality signal
Architecture: Multi-gate Mixture of Experts (MMoE). A shared embedding layer encodes user, ad, and context features. N expert networks sit on top of the shared layer. Each task has its own softmax gate that weights the experts differently, followed by a task-specific tower. This matters because CTR and hide-rate can conflict: gates let the hide-rate task down-weight experts that learned "high engagement" patterns.
A simpler shared-bottom model works as a baseline but suffers from negative transfer when task gradients disagree.
CVR sample selection bias. Conversions are only observable after clicks, so naively training pCVR on clicked impressions introduces selection bias. The fix is ESMM: train pCTCVR = pCTR × pCVR jointly, using all impressions as the training surface. pCVR is derived rather than directly supervised, which removes the bias.
Final scoring formula:
eCPM = 1000 × bid × {1 | pCTR | pCTR·pCVR} (depending on bid type)
score = eCPM + α·UserValue(pLongView, pCTR) − β·pHide − γ·Fatigue
Tune α, β, γ via online experiments on the revenue-vs-retention trade-off curve. Offline tuning is unreliable for business weights because the objective is not fully captured by any offline metric.
Calibration. Apply isotonic regression or Platt scaling per bid type and surface. Monitor predicted/observed ratio and alert on drift above ±5%. Miscalibration is a silent revenue bug.
4. Position Bias
The problem. Slot 1 gets clicked more than slot 5 regardless of ad quality. Training on logged clicks without correction teaches the model that "appeared in slot 1" predicts CTR, creating a self-reinforcing loop.
Solution: shallow position tower (PAL-style).
- Feed position, surface, and device type into a small separate sub-network that outputs a scalar bias logit.
- During training:
final_logit = main_logit + bias_logit. - At inference: drop the bias tower entirely, or fix position to a neutral constant.
The main tower is now trained to predict position-independent relevance — the bias tower absorbs the position signal so the main tower doesn't have to. Dropout on position features during training prevents the main tower from learning position correlations through other correlated features.
Alternative: inverse propensity weighting. Estimate examination probability per position from a small randomized-slot experiment (1–2% of traffic), then weight each training example by 1/propensity. This is unbiased but noisier and requires the randomization infrastructure. The shallow-tower approach is usually preferred in production because it is cheaper and more stable.
5. Delayed Conversions
The failure modes. If you label every recent unconverted click as negative and train immediately, pCVR is systematically underestimated. If you wait for the full attribution window (up to 7 days), the model goes stale and can't react to campaign changes.
Practical approach — fake-negative correction:
- Ingest each click immediately as a negative training example.
- When a conversion arrives (via pixel or postback), ingest a duplicate positive example.
- Apply importance weights to correct the expected gradient: the positive example gets weight proportional to how long conversion was delayed relative to your training lag.
This keeps the model training continuously while remaining unbiased in expectation. A cleaner but more complex alternative is to model the delay distribution explicitly (Chapelle's delayed feedback model) and treat unresolved clicks as censored observations.
In practice, a hybrid works well: train pCTR online every 10–30 minutes (clicks are near-instant), and train pCVR in hourly batches on events older than a short safety window, with a learned correction for still-pending conversions.
6. Real-Time Adaptation
Streaming features. Kafka → Flink pipelines write to an online feature store (Redis or Aerospike) with sub-second lag:
- User session state: last N ad interactions, session ad count, last-clicked category.
- Ad-level CTR in the last 5 min and 1 hour (for trend detection).
- Trending topic counters.
These are read at request time and fed as input features. Because recent interactions appear in the model's input sequence (via attention), a just-made click affects the very next ad request without any model retraining.
Model freshness. Daily full retrains capture long-term distribution shifts. Incremental pushes every 10–30 minutes update embedding tables for new or trending ads. Each push runs automated validation — AUC delta, calibration ratio — and auto-rejects on regression above a threshold.
7. Measuring Success
Offline (pre-launch):
- AUC and GAUC (per-user AUC, which is more robust to popularity bias) for each task.
- Calibration: predicted/observed ratio per bid type and position bucket.
- Coverage: fraction of eligible ads that retrieval returns.
Online (A/B test):
- Primary: RPM (revenue per thousand impressions) and CTR.
- Guardrails: hide/report rate, session length, D7 retention. A model that lifts CTR by 2% but increases hide rate by 10% is not a win.
- Long-term: advertiser ROAS and return rate (do advertisers keep spending?).
Common mistakes to avoid. Optimizing purely for CTR short-term degrades user experience and hurts retention. Neglecting calibration silently mis-prices auctions. Ignoring position bias in training leads to feedback loops that are hard to break once deployed. Treating all unresolved clicks as negatives will suppress CVR estimates and starve CPA campaigns of spend.