Design: ads click-through prediction
A sparse-embedding DNN, trained continuously on impression logs, predicts calibrated pCTR and pCVR; the auction ranks ads by bid × pCTR × pCVR (eCPM). Calibration is mandatory because predictions set prices, not just order.
Fundamentals you'll use
How it works
- Scale: ~1M ad requests/s at peak within ~100 ms, so ~150M predictions/s.
- Keep every positive and a fraction of negatives, then recalibrate outputs before the auction.
- Train incrementally every ~hour: weekly instead of daily retraining cost Facebook ~1% NE.
- The worst failure is miscalibration: prices go wrong while AUC stays flat, so offline ranking metrics never warn.
- Track NE and Σ predicted / Σ actual (~1.0) per advertiser, placement and country; gate every push on them.
Check yourself
Answer to mark it learned; your answers aren't scored.
A candidate model beats production on AUC and NE offline. Its pCVR calibration ratio (Σ predicted / Σ actual) is 1.0 overall but 1.2 for the furniture vertical. The push is due today. Your call?
Go deeper
Full explanation
Requirements
Functional: for each ad request (a feed slot, a search results page), choose and price ads from the eligible campaigns; support bids per click (CPC), per conversion (CPA) and per impression; respect targeting, budgets and frequency caps. Non-functional: ~100 ms server budget per request and ~1M ad requests/s at peak (assumed); predictions calibrated within a few percent overall and per segment; a new ad servable at launch; models refreshed within hours.
Questions I'd ask:
- Which bid types: CPC, CPA, value (ROAS)? Each needs another prediction.
- Which auction: second-price, VCG or first-price? Prices are computed from the predictions.
- Where do conversions come from (pixel, app SDK, server API), how late, and under which attribution window?
- Which signals do privacy rules and consent restrict (ATT, GDPR)?
- How many ads survive targeting per request?
The highest-cost failure is miscalibration: a pCVR that runs 20% high on one segment wins auctions it shouldn't, and when it is the runner-up it inflates the price the winner pays. AUC doesn't move at all, so offline ranking metrics never warn you.
High-level design
- Retrieval: targeting, budget and frequency filters plus a two-tower model narrow millions of live ads to ~1,000.
- Light ranker trims to ~150.
- Heavy ranker: a DLRM-style network (Neural networks & backpropagation): embedding tables for sparse IDs (user, ad, advertiser, placement) and their crosses, an MLP over dense counters, explicit feature interactions, and heads for pCTR and pCVR.
- Calibration per head and segment undoes negative downsampling and corrects drift (Class imbalance & calibration).
- Auction: rank by expected value per impression,
eCPM = 1000 × bid × pCTR × pCVRfor conversion bids (bid × pCTRfor CPC), plus a quality term from predicted negative feedback; price by second-price or VCG rules. Pacing scales bids so budgets last the day. - Learning loop: impressions, clicks and late conversions join in streaming into training rows (Queues vs streams (Kafka)); the model trains incrementally every hour or so from the last checkpoint, and no push ships without a calibration check.
Code Undo negative downsampling, then run a second-price auction
import numpy as np
W_NEG = 0.025 # share of negatives kept in training (He et al. 2014 found 0.025 best)
def recalibrate(p: np.ndarray, w: float = W_NEG) -> np.ndarray:
# Training saw 1/w more positives per negative than reality: map back
return p / (p + (1 - p) / w)
def auction(bids: np.ndarray, p_ctr: np.ndarray, p_cvr: np.ndarray, pacing: np.ndarray):
"""bids: $ per conversion; pacing: 0-1 multipliers from each campaign's budget controller."""
ecpm = 1000 * bids * pacing * p_ctr * p_cvr # expected $ per 1,000 impressions
first, second = np.argsort(-ecpm)[:2]
# Second price: the winner pays the runner-up's eCPM, never more than its own
return first, ecpm[second] / 1000 # $ charged for this impression
raw_ctr = ctr_head(features) # ~29x too high at a true 1% CTR
p_ctr = isotonic_ctr(recalibrate(raw_ctr)) # then a per-segment isotonic layer, refit hourly
p_cvr = isotonic_cvr(cvr_head(features))
winner, price = auction(bids, p_ctr, p_cvr, pacing)Real example
A user scrolls to a feed ad slot. Retrieval returns 1,200 eligible ads (~20 ms); the light ranker keeps 150 (~10 ms); the heavy ranker scores them in one batch (~30 ms) and calibration adjusts each head. Top two: running shoes bidding $20 per purchase, with pCTR 1.5% and pCVR 4%, so eCPM = 1000 × 20 × 0.015 × 0.04 = $12; a streaming app bidding $0.80 per click with pCTR 1.2%, so eCPM = $9.60. The shoes win and, billed per impression at the second price, pay $9.60 CPM. Now suppose the shoes' pCTR were 2× too high (truly 0.75%): their true eCPM is $6, the app should have won, and the shoe advertiser pays $9.60 for impressions worth $6 to it. Total ~80 ms.
Trade-offs +4 · −4
+ You gain
- Ranking by bid × pCTR × pCVR puts advertiser value and user response into one number that is comparable across bid types.
- Embeddings plus explicit crosses learn from billions of sparse IDs and generalize to pairs never seen together.
- Hourly incremental training keeps up with new creatives and shifting demand.
- Negative downsampling cuts training rows by an order of magnitude or more, with a closed-form correction.
− You pay
- Calibration is a hard dependency: any model, sampling or feature change can silently move prices.
- TB-scale embedding tables need sharded training and serving infrastructure.
- Delayed conversions force a trade-off between complete labels and fresh models.
- Logs only cover ads that won; new ads need an exploration budget to escape cold start (Exploration: multi-armed bandits).
Use it when
Auction-priced inventory with many advertisers, outcomes measured as clicks or conversions, and predictions that directly set both who wins and what they pay.
Avoid it when
Fixed-price sponsorships or direct-sold placements, a small inventory where contextual rules suffice, or no conversion tracking to train pCVR from.
Numbers to know 5
- Scoring: 1M ad requests/s at peak (assumed) × 150 heavy-ranked ads = 150M predictions/s, each with pCTR and pCVR heads.
- Training rows: 10B impressions/day × 1% CTR = 100M positives, plus 2.5% of 9.9B negatives ≈ 250M → ~350M rows/day (assumed volumes).
- Recalibration: true CTR 1%, w = 0.025 → the model sees 0.01 / (0.01 + 0.99 × 0.025) ≈ 29%; q = p / (p + (1 − p)/w) maps it back.
- Embeddings: 5B hashed rows × 64 dims × 2 bytes (fp16) ≈ 640 GB → sharded across hosts for training and serving.
- Facebook, 2014: trees + LR beat either alone by >3% NE; weekly instead of daily retraining cost ~1% NE; training on 10% of data cost ~1% NE.
Common pitfalls 4
- Changing the negative sampling rate without refitting calibration: predictions shift by up to ~30×, and auction prices with them. Gate every push on calibration per segment.
- Judging models on AUC alone: it is blind to calibration. Use NE and calibration per segment, on a time window after training.
- Treating unconverted clicks as final negatives: pCVR runs low for long purchase cycles, and those advertisers quietly under-deliver.
- Online training without data guards: a broken click pipeline feeds all negatives, and within an hour the model predicts ~0 CTR and ads stop serving.
Interview questions 3
Answer out loud first, then reveal.
If we only need to rank ads, why does calibration matter?Show answer
Because we don't only rank: we multiply predictions by bids from different advertisers and compute prices from them. If one advertiser's pCTR runs 2× high, it wins auctions a better ad should have won, and when it is the runner-up it raises the price the winner pays. AUC is invariant to that error, so I track normalized entropy and the calibration ratio per advertiser, placement and bid type, with an isotonic layer refit hourly. Every model push is gated on calibration staying near 1.0 per segment, not only on a better NE.
Conversions arrive up to 7 days after the click. How do you keep pCVR fresh?Show answer
I don't wait 7 days. Every click becomes a training row immediately, labeled negative; when the conversion arrives, the same row is re-emitted as a positive, and the loss uses importance weights that correct for the fake negatives. That keeps the model hours fresh instead of a week stale. The cost is variance and pipeline complexity, so I check calibration on matured cohorts and by vertical: travel and furniture convert late, and a biased pCVR would starve exactly those advertisers. For brand-new campaigns, I lean on pCTR and advertiser-level priors until conversions accumulate.
How do you A/B test a new pCTR model in a live auction?Show answer
A plain user split is biased here: both arms spend from the same campaign budgets, so if the treatment model spends faster it starves control, and the arms interfere. I'd use a budget-split design: split users and each campaign's budget into two isolated markets, each served by its own model, then compare revenue, advertiser ROI and user metrics. I watch advertiser outcomes, not just platform revenue: a model that raises revenue by miscalibrating upward is borrowing against advertiser trust. And I ramp slowly, because advertisers' automated bidding reacts to price changes over days.
Deep dive 5
The auction and why calibration is mandatory
A feed ranker compares items with each other; an auction multiplies predictions by money from different advertisers and turns them into prices. If pCTR doubles for everyone, the order is unchanged but every price computed from it is wrong; if it doubles for one advertiser, they win auctions they shouldn't. Facebook's 2014 ads paper makes the point: when a model over-predicts by 2× and a 0.5 multiplier fixes it, normalized entropy (NE) improves while AUC stays the same. So track NE and calibration (Σ predicted / Σ actual, target ~1.0) per advertiser, placement, country and bid type, plus reliability curves, and fix it with an isotonic or Platt layer refit hourly. Add a quality term (predicted hides and reports) so a high bid can't buy a bad user experience.
Model: sparse features, crosses and embeddings
Most of the signal sits in high-cardinality IDs and their combinations: user × ad category, advertiser × placement, query × creative. Wide & Deep (Google Play, 2016) pairs a linear model over hand-picked crosses, which memorizes, with a DNN over embeddings, which generalizes to unseen pairs. DLRM (Meta, 2019) generalizes the pattern: one embedding table per sparse feature, a bottom MLP for dense features, dot products between all pairs of embeddings, and a top MLP; DCN-v2 learns crosses explicitly. Hash rare IDs into fixed buckets. Embedding tables dominate memory (hundreds of GB to TBs), so they are sharded model-parallel while MLPs train data-parallel. For pCVR, train on all impressions with pCTR × pCVR as the target (ESMM), not only on clicks, or the model never sees the unclicked traffic it serves.
Massive logs: downsampling and recalibration
With CTR around 1%, 99% of rows are negatives that each teach little. Keep every positive and a fraction w of negatives: in Facebook's experiments, w = 0.025 gave the best NE, and training on a uniform 10% of the data cost only ~1% NE. Downsampling inflates the model's outputs, so map them back before the auction with q = p / (p + (1 − p) / w): at w = 0.025, a true 1% CTR shows up as ~29% in training. Alternatively, weight the kept negatives by 1/w and skip the correction. Evaluate with NE (log loss divided by the entropy of the background CTR) on the hours after the training window, never on a random split (Precision, recall, F1, ROC-AUC). Conversion data needs the same treatment, with even rarer positives.
Delayed conversions
Clicks land within minutes; purchases land hours or days later, inside attribution windows such as 7-day click / 1-day view. Waiting for every window to close keeps the model a week stale. Three options. Wait a short window and accept bias: Facebook's online joiner labels an impression negative after a tuned wait, trading label coverage against memory. Train on every row immediately as a fake negative, re-emit it as a positive when the conversion arrives, and correct the loss with importance weights (Twitter, RecSys 2019). Or model the delay explicitly, as Chapelle did at Criteo with an exponential delay distribution. I'd use the second and check calibration on matured cohorts, because long-purchase-cycle advertisers (travel, furniture) are the ones a biased pCVR starves.
Freshness, pacing and latency
New creatives launch every hour and interests shift, so staleness costs money: Facebook measured ~1% NE lost by retraining weekly instead of daily. Train incrementally from the last checkpoint every ~hour, retrain fully every week or so, and gate every push on NE, calibration and the label distribution; otherwise a broken click stream teaches the model that CTR is ~0 within one cycle (Monitoring models in production). Pacing spends each budget smoothly across the day: a feedback controller compares actual spend with the target curve and adjusts a bid multiplier or, as LinkedIn described in 2014, the probability of entering auctions. Latency (~100 ms, assumed): retrieval 20 ms, features 15, light ranker 10, heavy ranker 30, calibration and auction 5, network and headroom 20.