Design an Ads Ranking System
Understanding the Problem
📣 What is ads ranking? Every time a feed, search page or video player has an ad slot, the ad system picks which ad fills it out of millions of live campaigns. Advertisers say what they'll pay for an outcome (an impression, a click, an install, a purchase); the platform predicts how likely each ad is to produce that outcome for this user right now, multiplies by the bid, and runs an auction. The ML problem at the center is click-through rate (CTR) and conversion rate (CVR) prediction, and unlike most recommenders, the predictions are used as numbers in a pricing formula, not just to sort a list.
"Design an ML model for ads recommendation" is the same question. The serving infrastructure, including the targeting index, budget pacing, real-time bidding with external buyers and impression counting, is covered in Design an Ad Serving System and Ad Click Aggregator. Here we go deep on the models and how their outputs feed the auction.
Functional Requirements
Core Requirements
- For each ad request (a feed slot, a search results page), the system should choose which ads to show and what each advertiser pays.
- The system should predict, for every eligible ad, the probability of a click and, for conversion-optimized campaigns, of a conversion after the click.
- Those predictions must be calibrated: a predicted 2% CTR should mean about 2 clicks per 100 impressions.
- The ranking should balance advertiser value, platform revenue and user experience (ads people hate shouldn't win just because they bid high).
Below the line (out of scope)
- Campaign creation, review and targeting setup.
- Budget pacing and billing (we take a pacing multiplier as an input).
- Click fraud detection (we assume invalid clicks are filtered before they become labels).
- Generating ad creatives.
Non-Functional Requirements
Core Requirements
- 1 billion daily active users, each seeing around 40 ads a day: 40 billion impressions a day, about 460,000 per second on average.
- About 500,000 ad requests per second at peak, each with a few thousand eligible ads after targeting.
- Ad ranking gets under 100 ms at p99 inside the feed or search request.
- Freshness: new campaigns launch every minute, and an ad's CTR can change within hours (creative fatigue, news events). Models should update at least hourly.
- Calibration: aggregate predicted clicks should be within a few percent of observed clicks, overall and for each major segment (country, placement, device, advertiser vertical).
Below the line (out of scope)
- Cross-device attribution and the measurement products advertisers see.
Two pieces of arithmetic frame the design.
Scoring cost. 500,000 requests × 5,000 candidates is 2.5 billion candidate scorings per second at peak. A heavy deep model can't do that. A two-tower dot product can (it's a few hundred floating-point operations per candidate). So, as in every recommender, we use a funnel: a light model narrows 5,000 to ~300, and the heavy model scores those 300, which is still 150 million heavy scorings per second.
Money. Say the average price is $5 per thousand impressions. 40 billion impressions a day is then $200 million a day. A 1% relative improvement in how well we match ads to users is worth on the order of $2 million a day, and a 5% calibration error in one country is a 5% pricing error for every advertiser there. That's why ads teams care about log loss in the third decimal place.
The single most important thing to say early: in ads, a model that ranks well but is miscalibrated is broken. Feed ranking only needs the order of the items to be right. The ad auction multiplies the prediction by a bid and compares across advertisers who bid very differently, so the absolute value of each prediction is what sets prices.
Framing It as an ML Problem
ML Objective
The business objective is long-term revenue, which depends on three parties staying happy:
- Advertisers get good outcomes for their money (high return on ad spend), so they keep spending.
- Users see ads that are relevant or at least not annoying, so they keep using the app.
- The platform earns revenue per impression.
The model doesn't optimize any of these directly. It predicts per-impression probabilities, and the auction score combines them:
expected value (per impression) =
bid_per_click × pCTR # CPC campaigns
| bid_per_conversion × pCTR × pCVR # CPA campaigns (pCVR = P(convert | click))
| bid_per_impression # CPM campaigns
total score = expected value + quality bonus − user cost
The quality bonus and user cost terms are where user experience enters: predicted probability that the user hides or reports the ad, predicted dwell on the landing page, low-quality landing pages. Converted to the same units as the bid, they let a relevant ad with a lower bid beat an irrelevant one with a higher bid.
Inputs and Outputs
- Input: an ad request (user ID, placement, surface, device, page context such as the search query or surrounding feed items) and the set of eligible ads (those whose targeting matches and whose budget isn't exhausted).
- Output: for each ad, calibrated pCTR and pCVR, plus the auction result: winners, their positions and their prices. Every prediction is logged with the request ID.
Choosing the ML Approach
The core is binary classification (click / no click, convert / no convert) trained with log loss, because log loss is a proper scoring rule: minimizing it pushes the model towards true probabilities, not just a good order. We wrap it in a funnel:
- Eligibility: targeting and budget filters pick ~5,000 eligible ads from ~10 million live ones. Not ML, but it's the retrieval stage.
- Light ranker: a two-tower model (user tower, ad tower) scores all eligible ads by dot product and keeps the top ~300.
- Heavy ranker: a deep multi-task model predicts pCTR and pCVR for those 300.
- Calibration and auction: correct the predictions, compute scores and prices, pick winners.
Data and Labels
Sources
- Impression logs from the ad server: which ad, in which slot, for which user and request, with the features used and the predictions made.
- Clicks, which arrive within seconds of the impression.
- Conversions (installs, sign-ups, purchases), reported by the advertiser's pixel, SDK or server-side conversion API, which arrive minutes to days later.
- Negative feedback: hide ad, report ad, "why am I seeing this."
- Ad metadata: advertiser, campaign, objective, creative image and text, landing page, vertical.
How labels are produced
- Click label: did this impression get a valid click within a short window? We wait about 15 minutes, then emit the example. Almost all clicks come within seconds.
- Conversion label: did the click lead to a conversion within the attribution window (commonly 1 to 7 days)? This label is delayed, which is the hardest part of the data. If we train on yesterday's clicks, many of tomorrow's conversions haven't happened yet, and the model sees them as negatives.
Class imbalance. CTR for feed ads is on the order of 1%, and CVR per click a few percent, so conversions are roughly one in several thousand impressions. We keep all positives and downsample negatives, then correct the predictions (see calibration).
Invalid traffic. Bot clicks and accidental clicks (a click followed by a bounce within a second) are filtered or down-weighted before training. Otherwise the model learns to predict fraud.
Privacy constraints. Conversion data is increasingly limited: mobile platforms restrict cross-app tracking, and some conversions come only as delayed, aggregated reports. Modern ads systems have to train on partial conversion labels and model the rest; say so if the interviewer goes there, but you don't need to design a privacy-preserving attribution system.
Label leakage. Counting features are the main trap. "This ad's CTR over the last hour" must be computed as of the impression time, excluding the current impression. If the counter includes the click you're predicting, offline AUC looks amazing and production is terrible. Logging features at serving time and training on those logs prevents it.
Feature Engineering
Ads models are famous for having thousands of features, most of them sparse IDs and counts.
User features
- Demographics (age bracket, country, language), device, OS, connection type.
- Interest embeddings from organic behavior: pages followed, content engaged with.
- Ad history: recent ad clicks and conversions, by advertiser and vertical. A user who installed three games last week is a strong game-install prospect.
Ad features
- IDs: ad, creative, campaign, advertiser, vertical. These are the backbone of the model.
- Creative embeddings from image and text encoders, which let a brand-new ad borrow from similar ones.
- Landing page category and quality score, campaign objective, bid type.
Context features
- Placement (feed, stories, search, video), slot position, time of day, the search query or surrounding content.
Cross features
- User × advertiser: has this user clicked or converted with this advertiser before?
- User interest × ad vertical, query × ad keywords (for search ads).
Counting features are historical rates at many granularities: CTR of this ad, this advertiser, this ad × age bracket, this ad × placement, over 1 hour, 1 day, 7 days. They're smoothed with a Bayesian prior so a new ad with 1 click in 10 impressions doesn't look like a 10% CTR:
smoothed_ctr = (clicks + α) / (impressions + α + β)
# α / (α + β) = the parent's CTR (e.g. the advertiser's), α + β = prior strength
Real-time vs batch
- Streaming (Flink): counters over the last hour, the user's last few ad clicks, budget state. Creative fatigue (an ad's CTR dropping after users have seen it a lot) only shows up in fresh counters.
- Batch (daily): long-window counters, interest embeddings, advertiser profiles.
High-cardinality IDs go into embedding tables. For the long tail, feature hashing maps IDs into a fixed number of buckets; collisions cost a little accuracy and save a lot of memory.
Modeling
Bad Solution: Historical CTR Per Ad
Approach
Predict pCTR as the ad's smoothed historical CTR. Rank by bid × CTR.
Challenges
Not personalized: every user gets the same prediction for an ad, so a game ad wins for users who never play games. New ads have no history. It's a useful feature and a sanity check, not a model.
Good Solution: Logistic Regression on Sparse Features
Approach
Logistic regression over hashed one-hot features and hand-picked crosses (user age × ad vertical, query term × ad keyword), trained online with an algorithm like FTRL, which handles billions of sparse features and keeps the weight vector sparse. A popular step up is GBDT + LR: train gradient-boosted trees on dense features, use the leaf each example lands in as extra sparse features for the LR. Ads systems ran on models like these for years.
Challenges
LR is fast, calibrated by construction (log loss, linear in the logit) and easy to update online. But every useful interaction has to be crossed by hand, and the number of possible crosses explodes. It can't use sequences (the last 20 things the user clicked) or content embeddings well.
Great Solution: Deep Multi-Task CTR and CVR Model
Approach
A deep model built around embeddings and learned feature interactions:
- Embeddings for every sparse feature, plus a bottom MLP for dense features.
- Feature interaction layer: DLRM-style pairwise dot products between embeddings, DCN-v2 cross layers, or DeepFM's factorization-machine component. These learn the crosses LR needed by hand.
- User behavior attention: attention over the user's recent ad clicks and organic engagements, with the candidate ad as the query. Deep Interest Network came out of e-commerce ads for exactly this reason.
- Multi-task heads for pCTR, pCVR, and often negative feedback (P(hide)). The CVR head has a selection-bias problem: conversions only happen after clicks, so a CVR model trained on clicked impressions never sees the unclicked ones it will be asked to score. The fix, from ESMM, is to model pCTCVR = pCTR × pCVR and train it on all impressions, so the CVR tower is learned across the whole impression space.
Challenges
Embedding tables reach hundreds of GB to TBs, so training needs model-parallel embeddings (TorchRec, or a parameter-server design) and data-parallel dense layers. Inference must fit 300 candidates in a few tens of milliseconds, so we compute the user side once, batch candidates on GPUs and quantize where calibration allows. Deep models are less calibrated out of the box than LR, which the next section deals with.
Calibration
Log loss makes the model roughly calibrated, but several things break that:
- Negative downsampling inflates predictions. If negatives were kept at rate w (say 0.1), the raw prediction q overstates the true probability. Correct it with
p = q / (q + (1 − q) / w). - Distribution shift: the model was trained on last week; this hour's CTR is different.
- Model capacity and regularization distort probabilities, especially for rare segments.
So we add a calibration layer after the model:
- Platt scaling (a logistic regression on the model's logit) fixes a global over- or under-prediction.
- Isotonic regression fits a monotonic piecewise mapping, which can fix calibration that's off in different directions at different prediction values.
- Per-segment calibration: fit the calibrator per placement, country or vertical, because a model can be calibrated overall and 15% off for video ads in Brazil.
The calibrators are tiny, retrained every hour or so on the latest data, and monitored with the calibration ratio (Σ predicted / Σ observed) per segment.
From Predictions to the Auction
With calibrated pCTR and pCVR, we compute each ad's effective bid (expected value per impression):
- CPC:
bid × pCTR - CPA:
bid × pCTR × pCVR - With autobidding, advertisers set a target ("$20 per install"), and the system bids
target × pCTR × pCVR × pacing_multiplier, where the pacing multiplier spreads the budget across the day.
Add the quality bonus and subtract the user cost, then rank by total score. Pricing in a generalized second-price (GSP) auction charges each winner the minimum it would have needed to keep its position. For CPC:
price_per_click_i = (score_{i+1} − quality_i + user_cost_i) / pCTR_i # roughly: next score / my pCTR
Some platforms use VCG-style pricing instead, which charges each winner the value it displaces from others. Either way, every term is a prediction, which is why the predictions have to be calibrated. A reserve price sets a floor so ads below it don't show.
Training
Loss. Log loss per head (binary cross-entropy), summed with weights. The CTCVR loss is computed on all impressions, the CTR loss on all impressions, and there's no separate CVR loss on clicked-only data.
Negative downsampling. Keep all clicks and ~5–10% of non-click impressions for the CTR head. This cuts training data by about 10× with almost no loss in accuracy, as long as the correction above is applied.
Delayed conversions. Covered in the deep dives; the short version is that we either wait, or model the delay.
Cadence. Ads models are updated very frequently:
- Incremental training every hour (or continuously), starting from the previous weights, on the newest data. New ad IDs get embeddings as soon as they've had impressions.
- Full retrain every week or two on a longer window, to try new architectures and to correct drift accumulated by incremental updates.
- Calibrators refit every hour.
Scale. 40 billion impressions a day, downsampled to roughly 4 billion training examples, each with hundreds of sparse features. A day's training on a GPU cluster with sharded embeddings has to finish in well under a day, and incremental hourly updates in minutes.
Evaluation
Offline Metrics
- Normalized entropy (NE): log loss divided by the entropy of the background CTR. NE < 1 means the model beats "predict the average CTR for everyone"; lower is better. It's sensitive to calibration, which is why ads teams prefer it to AUC.
- AUC: how well the model orders impressions. Useful but blind to calibration.
- Calibration ratio overall and per segment. A new model with better NE but a calibration ratio of 1.12 in one country is not shippable as is.
- Offline auction replay: rerun logged auctions with the new predictions and estimate revenue and advertiser value. It's approximate, because the logged data only has outcomes for the ads that actually won.
Always split by time: train on days 1–7, test on day 8.
Online Metrics and A/B Testing
- Revenue: revenue per thousand impressions (RPM) or per user.
- Advertiser value: conversions per dollar, cost per acquisition, return on ad spend. Revenue that comes from overcharging advertisers isn't a win; it comes back as lower bids.
- User experience: ad hide and report rate, session time, organic engagement. More ads or worse ads can raise revenue this week and lower usage next quarter.
- Calibration in production.
A/B tests in ads have a special problem: budget interference. If the treatment model spends an advertiser's budget faster, the control arm has less budget left, so control looks worse for reasons that have nothing to do with its model. The standard fix is budget-split testing: give each arm its own slice of every campaign's budget, so the arms don't compete for the same money.
Serving
A latency budget for 100 ms at p99:
| Step | Budget |
|---|---|
| Targeting and budget filter (~10M → ~5,000) | ~15 ms |
| User features and user tower | ~10 ms |
| Light ranker over ~5,000 ads (dot products) | ~10 ms |
| Fetch ad and cross features for ~300 | ~15 ms |
| Heavy model on ~300 (GPU, batched) | ~25 ms |
| Calibration, auction, pricing | ~5 ms |
| Network, logging, slack | the rest |
Ad tower embeddings for all live ads are precomputed and refreshed as ads are created and models update. The heavy model runs online, because the user, context and budget state change every request. Batch prediction has little role in ads beyond precomputing ad embeddings and candidate pools per audience segment.
Every prediction, every eligible ad's score and the auction outcome are logged. That log is the training data, the input to the calibrators, and the record advertisers' invoices are reconciled against.
Potential Deep Dives
1) How do we keep predictions calibrated?
Bad Solution: Trust the Model Output
Approach
Use the raw model output in the auction.
Challenges
With 10% negative downsampling, predictions are off by up to ~10× for low-CTR ads. Even without downsampling, a deep model drifts out of calibration between retrains, and every drift is a pricing error for every advertiser.
Good Solution: Downsampling Correction Plus Global Calibration
Approach
Apply the closed-form downsampling correction, then fit a global isotonic or Platt calibrator hourly on the most recent labeled data.
Challenges
Fixes the overall level, but not the segments. A model can over-predict video placements by 15% and under-predict feed placements by 10%, average out to 1.0, and misprice both.
Great Solution: Per-Segment Calibration With Monitoring
Approach
Fit calibrators per major segment (placement × country, or placement × vertical), with a hierarchical fallback to the parent segment when a segment has too little data. Monitor the calibration ratio per segment in near real time, alert when it leaves [0.95, 1.05], and block any model push that breaks it in a canary. Also feed the calibrator recent features that capture shift, like hour-level CTR for the placement.
Challenges
More calibrators to fit and monitor, and fine segments are noisy. Isotonic calibrators on thin segments overfit, so cap the number of segments and require a minimum number of clicks per segment.
2) How do we learn from conversions that arrive days later?
If a model trains on clicks from the last hour and counts every click without a conversion as a negative, it treats "not converted yet" as "won't convert." Predictions come out too low, especially for advertisers with long purchase cycles.
Bad Solution: Treat Pending as Negative
Approach
Train on fresh data with whatever labels have arrived.
Challenges
Systematic under-prediction of CVR, worst for products people think about before buying. Under-predicted CVR means under-bidding for those advertisers, so they lose auctions they should win.
Good Solution: Wait Out the Window
Approach
Only train the CVR head on clicks older than the attribution window (say 7 days).
Challenges
Labels are complete, but the model is always a week stale. New campaigns get no learned conversion signal for a week, which is a bad first experience for a new advertiser.
Great Solution: Train Fresh and Correct for the Delay
Approach
Train on fresh data, but account for the delay. Two common approaches:
- Fake negatives with correction: emit each click immediately as a negative, then emit a positive copy when the conversion arrives. Weight the examples (importance weighting) so the model's expected output matches the true conversion rate.
- Model the delay explicitly: a second model predicts the distribution of time-to-conversion (for example exponential or a learned per-vertical curve). An unconverted click from 2 hours ago is treated as "probably negative, but 30% of this vertical's conversions take longer than 2 hours," and contributes to the loss accordingly.
Challenges
Both add complexity and their own assumptions (a delay model per vertical can be wrong for a new type of product). Many teams combine a fresh, delay-corrected model with a periodic retrain on complete labels to catch drift.
3) How do new ads and new advertisers get a fair start?
A new ad has no ID embedding, no counters and no history with any user. If the model predicts low CTR for it, it never wins, so it never gets data.
- Content features: creative image and text embeddings put the new ad near similar ads, and advertiser-level and vertical-level counters give it a prior.
- Hierarchical smoothing: the ad's smoothed CTR starts at its campaign's or advertiser's CTR and moves towards its own as impressions accumulate.
- Exploration: during a learning phase, add an uncertainty bonus to the new ad's score (an upper-confidence-bound style boost that shrinks as impressions grow), within a small exploration budget. The platform pays for it in slightly lower short-term revenue; the advertiser gets a fair read on their ad.
- Communicate it: advertising products typically tell advertisers that a new campaign is "learning" for its first few days. It's an honest reflection of the ML.
4) How do we balance revenue against user experience?
The highest-bidding ad is not always the best one to show. An ad users hide costs the platform in session time and future ad engagement, and those costs aren't in the bid.
- User cost term: train heads for P(hide), P(report), and predicted organic engagement lost. Convert them to dollars with a weight tuned by long-term experiments, and subtract from the score.
- Quality and landing page: a prediction of whether the click will bounce in a second (a bad landing page) lowers the score.
- Ad load: how many ads per feed and where is itself a model and an experiment. Fewer, better ads can earn more over time than more, worse ones.
- Long-term holdouts: some user-experience costs only show up over months. A small holdout with a lower ad load measures them.
Interviewers want to hear that you know the auction isn't purely about money. A quality term is how platforms keep users engaged and advertisers' cost per result down, since better-targeted ads get more conversions for the same spend.
5) How do we monitor and ship models safely when money is on the line?
- Shadow scoring: a new model scores live traffic without affecting auctions, so we can compare its calibration and score distribution before it takes over.
- Canary with spend caps: route a small share of traffic, with alerts on calibration ratio, RPM and spend rate per advertiser.
- Feature monitoring: null rates, counter freshness, and the gap between serving and training features. A frozen counter (Flink job stalled) can make every ad look like it did an hour ago.
- Fast rollback: every incremental update is a checkpoint, and rolling back is one config change.
- Advertiser-facing anomalies: a sudden change in an advertiser's cost per result is often the first sign of a model problem, and it's what they'll complain about.
What is Expected at Each Level?
Mid-level
You should frame the problem as CTR prediction with log loss, propose logistic regression or GBDT as a baseline with sensible user, ad and context features, and explain ranking by bid × pCTR. With prompting, you should mention class imbalance and negative downsampling, and evaluate with AUC and log loss on a time-based split.
Senior
You should explain why calibration matters in an auction and how to get it (downsampling correction, isotonic or Platt, per-segment), design a deep multi-task CTR/CVR model and the funnel in front of it, and handle delayed conversions with at least the wait-window approach. Expect to discuss counting features and leakage, hourly incremental training, NE vs AUC, and a latency budget. You should bring up the quality or user-cost term yourself.
Staff+
You should connect the models to the marketplace: how predictions flow into autobidding and GSP prices, how miscalibration turns into mispricing, budget-split A/B tests and why ordinary tests are biased, delayed-feedback modeling, and long-term user cost vs short-term revenue. Expect to discuss exploration budgets for new advertisers, privacy-limited conversion data, safe rollout of models that move money, and the organizational question of who sets the quality weights.