Building a Low-Latency Ad Ranking Pipeline with ML
Machine LearningModel answerLast updated
Design an end-to-end ML system that picks personalized ads for millions of users within a tight latency budget, covering data, models, exploration, evaluation and scaling.
Context
An ad platform serves personalized ads to a very large user base. Each time a user opens a page or app, the system has a short window to decide which ads to show, and the choice should maximize expected value for the platform while respecting advertiser and user constraints.
Task
Design the machine-learning system behind this ad selection. Your answer should address:
- Data collection and labeling: which events you log, how labels are built, and what goes wrong with them.
- Feature engineering: feature groups, real-time versus historical signals, and how you keep training and serving consistent.
- Model choice: a baseline, how you would evolve it, and how predictions feed the ranking and auction.
- Exploration versus exploitation: how new or uncertain ads get a fair chance without hurting revenue too much.
- Evaluation: offline metrics, counterfactual evaluation of a new policy, and online experiments.
- Latency and scalability: serving architecture, a latency budget, and capacity assumptions.
State your assumptions with numbers (users, requests per second, number of ads, latency target) and call out the trade-offs and failure modes you would watch for.
Hints
Hint 1
Think in a funnel: a cheap retrieval step shrinks a huge ad pool to a small candidate set, and only then does a heavier model score candidates. Allocate a latency budget to each stage.
Hint 2
Clicks are rare and only observed for ads you actually showed. Consider what this does to class balance, calibration after downsampling, position effects and selection bias, and what you must log at impression time to fix them later.
Hint 3
Separate how you pick a policy from how you evaluate it: log the probability each shown ad was chosen so that inverse-propensity-style estimators can score a new policy offline before an A/B test.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scope and scale
Goal: for each request (user, context, slot), return the top-k ads that maximize expected value, subject to budgets, targeting, frequency caps, policy rules and user-experience guardrails.
Objective: rank by expected revenue, eCPM = bid × pCTR (times pCVR for conversion-priced campaigns).
Assumptions:
| Quantity | Assumption |
|---|---|
| Daily active users | 100M |
| Requests per user per day | ~10, so ~1B/day, ~12K QPS average, ~40K peak |
| Active ads | ~1M |
| End-to-end latency | ≤100 ms p99, with ~30 ms for ML scoring |
| Logs | ~1 KB per impression, ~1 TB/day |
Fair-lending, housing and similar rules mean protected attributes and close proxies must be excluded from features and targeting for sensitive ad categories.
2. Architecture: a multi-stage funnel
- Retrieval (1M to ~1K, under 10 ms): filter by targeting and budget with an inverted index, then add personalized recall using a two-tower embedding model and approximate nearest neighbor search.
- Ranking (1K to ~50, ~20 ms): a CTR/CVR model scores candidates using features from an online feature store.
- Auction and re-ranking: compute eCPM, apply exploration, enforce frequency caps, diversity and pacing, then price with a second-price or GSP auction.
- Logging: a stream (Kafka) feeds a stream joiner that builds labeled examples, real-time counters for the feature store, and an offline warehouse for batch training.
Model lifecycle: daily full retrain plus hourly incremental updates; a registry, shadow scoring, then canary rollout.
3. Data and labels
- Click label: positive if a click arrives within a window (say 30 minutes) of the impression, joined by
request_id. - Delayed conversions: wait for an attribution window, or train with provisional negatives and correct them later, or model the delay explicitly.
- Class imbalance: with CTR near 1%, downsample negatives at rate
w, then recalibrate:q = p / (p + (1 − p)/w). Forgetting this inflates pCTR and distorts the auction because it multiplies the bid. - Position bias: train with position as a feature and fix it to a default at serving time, or use a separate position tower.
- Selection bias: labels exist only for shown ads, which is why exploration and propensity logging matter.
- Hygiene: remove bots and fraud, deduplicate events.
Log at impression time: the feature snapshot, score, position and selection propensity. This enables leak-free training and counterfactual evaluation.
4. Features
- User: long-term interest embeddings, category CTR history, recency.
- Ad/advertiser: category, creative embedding, smoothed historical CTR (Bayesian prior for new ads), landing-page quality.
- Context: device, time, page category, slot, geo.
- Cross features: user-category by ad-category, user by advertiser history.
- Real-time counters: impressions and clicks over 5 min, 1 h and 24 h.
A feature store defines each feature once and serves it online (Redis/Cassandra-style, low latency) and offline (point-in-time correct). Logging the served values removes training/serving skew. High-cardinality IDs use hashing or learned embeddings.
5. Model choice
- Baseline: logistic regression with hashed crosses, trained online (FTRL). Cheap, well calibrated, fresh within minutes.
- GBDT plus LR: trees learn non-linear interactions, LR on top stays calibrated.
- Deep CTR models (DeepFM, DCN-v2, sequence models over user behavior): often a 1 to 3% log-loss gain, which is significant at this scale, at the cost of heavier inference.
- Multi-task CTR/CVR (ESMM-style): training CVR over the impression space reduces sample-selection bias.
Always calibrate (Platt or isotonic) because the auction uses absolute probabilities, not just ordering.
6. Exploration versus exploitation
Pure exploitation starves new ads and entrenches model bias.
- Epsilon-greedy: random eligible ad on 1 to 5% of traffic. Simple, gives clean propensities.
- Thompson sampling / UCB: Beta posterior or model uncertainty per ad; rank by sampled CTR times bid, so exploration concentrates on uncertain ads.
- Contextual bandits (LinUCB, neural): personalize the exploration.
- Cold-start guarantees: a minimum impression budget per new creative with bounded cost to advertisers.
Log the selection probability every time.
7. Evaluation
Offline: AUC, normalized log loss, and calibration ratio (sum predicted over sum actual) overall and by segment. Use time-based splits, never random.
Counterfactual: with logged propensities, estimate a new policy's value with IPS, V = (1/n) Σ r_i · π_new(a_i|x_i) / π_log(a_i|x_i). Reduce variance with clipping, self-normalized IPS or doubly robust estimators. These filter out weak candidates cheaply before live tests.
Online: A/B test on revenue per thousand requests, CTR, conversions, advertiser ROI and guardrails (hide rate, latency, ad load). Watch for novelty effects, budget interference between arms, and run long enough to cover weekly cycles.
8. Latency and scalability
- Budget per stage: retrieval ~10 ms, feature fetch ~5 to 10 ms (batched, cached), ranking ~20 ms, auction ~5 ms.
- Shard the ad index; replicate the feature store; cache hot user and ad features.
- Use quantization, batching and distillation for heavy models.
- Degrade gracefully: if the deep model times out, fall back to the LR baseline; if features are missing, use defaults.
- Autoscale for peaks (~3x average).
9. Common mistakes
- Skipping recalibration after negative downsampling.
- Random train/test splits that leak future information.
- Not logging propensities, making offline evaluation biased.
- Training/serving skew from recomputed features.
- Ignoring position bias and feedback loops.
- Optimizing CTR alone and ignoring advertiser value and user experience.
- Using protected attributes or proxies for regulated ad categories.
A strong answer ties these together: a staged funnel to meet latency, a calibrated and fresh CTR model, principled exploration with logged propensities, and a layered evaluation path from offline to counterfactual to live experiments.