Contents
Constraints
- 100k ad requests/s
- ~10⁶ active ads
- p99 budget 50–100 ms
- base CTR ~1%
What to cover
Sketch your own design first. A complete answer has these parts; the notes say what each should settle.
- RequirementsPredict the probability that a user clicks or converts on an ad, and use it to rank ads in a second-price-style auction.
- Estimates100k ad requests/s; ~10⁶ active ads; p99 budget 50–100 ms; base CTR ~1%.
- API
- Data model
- ArchitectureRetrieval by targeting and embeddings → light ranker → heavy CTR/CVR model (wide-and-deep / DCN / two-tower plus cross features).; Expected value = bid × pCTR × pCVR, plus quality terms.; Calibration layer; budget pacing; delayed-conversion attribution.; Online learning or frequent retraining on fresh logs; negative downsampling with a correction.
- Deep dives
- Trade-offscalibration is mandatory (prices depend on probabilities); freshness vs stability; privacy constraints on features; advertiser value vs user experience.
- EvaluationOffline: log-loss, normalised entropy, calibration (predicted/observed ratio), AUC.; Online: revenue per mille, advertiser ROI, CTR.; Guardrails: ad load, user hides, latency.
Reference design
One way to answer it, part by part. Open a part once you have your own version of it.
Requirements
Functional: for each ad request (a page or feed slot with user and context), select eligible ads by targeting and budget, predict p(click) and p(conversion | click), rank by expected value to the advertiser plus quality, run a second-price-style auction, charge correctly, pace budgets, and report results to advertisers.
Non-functional: p99 50–100 ms end to end; ~100k requests/s; ~10⁶ active ads; predictions must be calibrated because prices and budgets depend on them; privacy (consent, limited cross-site tracking) shapes which features we may use.
Objectives (in tension): platform revenue, advertiser ROI (or advertisers leave), user experience (ad load, relevance, hides).
Assumptions to confirm: bidding types (CPC, CPM, target-CPA via autobidding), the conversion attribution window (e.g. 7-day click), whether conversions come via server-to-server postbacks, how many ad slots per request (~3), reserve prices, UK GDPR/PECR consent states.
Estimates
Stack · 6 layersp99 latency budget
Retrieval by targeting and embeddings.
Fetch features for the candidates.
Dot product / small model to top ~100.
CTR and CVR models on the ~100 survivors.
Calibration, auction and pacing.
Network and tail headroom.
- Requests: 100k/s, ~3 slots each → 300k impressions/s ≈ 26B/day; at ~1% CTR ≈ 260M clicks/day.
- Funnel per request: retrieval ~1,000 candidates → light ranker → top ~100 → heavy CTR/CVR model. Heavy scorings = 100k × 100 = 10M/s; light scorings 100M/s (dot products, cheap).
- Heavy model cost: ~1 MFLOP dense compute per candidate → 10 TFLOP/s overall, modest; the real constraints are embedding-table lookups (tables of 10–100 GB sharded across hosts) and batching within the latency budget.
- Training data: keep all clicks and ~10% of non-clicks: 260M + 2.6B ≈ 2.9B rows/day. With negatives sampled at rate w, correct predictions by p = q / (q + (1 − q)/w); at w = 0.1 a raw q of 0.09 maps back to p ≈ 0.0098.
- Baseline for normalised entropy: at p = 1%, entropy = −(0.01 ln 0.01 + 0.99 ln 0.99) ≈ 0.056 nats; a model with log-loss 0.050 has NE ≈ 0.89 (11% better than predicting the base rate).
- Latency budget (p99 ~80 ms): retrieval 10 ms, feature fetch 10 ms, light ranker 5 ms, heavy ranker 20 ms, calibration, auction and pacing 3 ms, network and tail headroom ~30 ms.
API
POST /v1/ad_request
{request_id, user: {id_hash?, consent: {personalised_ads: true}}, context: {placement,
page_category, device, geo_region, time}, slots: 3}
→ {ads: [{slot, ad_id, creative_id, charge_model: "cpc", price, tracking: {impression_url,
click_url}}], auction_id}
Events: impression, click (with auction_id, ad_id, position)
Conversions: POST /v1/conversions {click_id | aggregated report, event, value, ts}
Advertiser API: campaigns, ad groups, bids (CPC/CPM/target CPA), budgets, targeting, creatives
Prices and pCTR/pCVR used for each auction are logged with the auction id so billing and model training both refer to the same decision.
Data model
- Campaign / AdGroup / Ad: bid type and amount, daily and lifetime budget, targeting, schedule, creative ids, creative embeddings, policy status.
- BudgetState: spend so far today, pacing multiplier or participation probability, last update (in a fast store, updated every few seconds).
- UserFeatures (consent-aware): interest embeddings, recent engagement aggregates, demographics where permitted; contextual-only features when consent is absent.
- AuctionLog: auction_id, request context, candidates with pCTR, pCVR, eCPM, winner, price, reserve, model versions.
- Impression / Click / Conversion: linked by ids; conversion carries attribution window and delay.
- TrainingExample: impression features snapshot + click label; click + conversion label available after the attribution window, with an “observed so far” flag for delayed-feedback modelling.
Architecture
Flow · 4 stepsRequest-path funnel for ad ranking
- Retrieval The ad request enters; retrieval selects ~1,000 eligible ads.
- Ranking The light ranker keeps top ~100; the heavy ranker scores CTR and CVR.
- Calibration and eCPM Calibration gives pCTR and pCVR; eCPM combines bid, probabilities and quality.
- Pacing and auction Pacing adjusts participation; the auction ranks by eCPM and returns ranked ads.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Retrieval | The ad request enters; retrieval selects ~1,000 eligible ads. |
| 2 | Ranking | The light ranker keeps top ~100; the heavy ranker scores CTR and CVR. |
| 3 | Calibration and eCPM | Calibration gives pCTR and pCVR; eCPM combines bid, probabilities and quality. |
| 4 | Pacing and auction | Pacing adjusts participation; the auction ranks by eCPM and returns ranked ads. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Ad request | Input | page or feed slot |
| Retrieval | Funnel | ~1,000 candidates |
| Light ranker | Funnel | top ~100 |
| Heavy ranker | Funnel | CTR and CVR |
| Calibration | Scoring | per segment |
| eCPM | Scoring | bid × pCTR (× pCVR for CPA) × 1000 + quality |
| Pacing | Scoring | budget controller |
| Auction | Auction | second-price |
| Ranked ads | Auction | auction_id |
Source: This page's text
CalculatorNegative-sampling correction and CPC eCPM
- Corrected pCTR
- 0.979%
- CPC eCPM
- 9.79
Corrected pCTR = Raw score q ÷ (Raw score q + (1 − Raw score q) ÷ Negative sampling rate w) = 0.979%
CPC eCPM = Bid × Corrected pCTR × 1000 = 9.79
| Case | Raw score q | Negative sampling rate w | Bid | Corrected pCTR | CPC eCPM |
|---|---|---|---|---|---|
| Worked case | 0.09 | 0.1 | 1 | 0.979% | 9.79 |
Ad request ─► Ad server
├─ Retrieval: targeting index (inverted on geo/interest/placement) + two-tower
│ embedding ANN ─► ~1,000 eligible ads (budget and frequency-cap filters)
├─ Light ranker: dot product / small model ─► top ~100
├─ Heavy ranker: CTR and CVR models (wide-and-deep / DCN-style cross network
│ on user, ad and context features, two-tower embeddings as inputs)
├─ Calibration layer (per segment) ─► pCTR, pCVR
├─ eCPM = bid × pCTR (× pCVR for CPA) × 1000 + quality terms
├─ Pacing: participation probability / bid multiplier from budget controller
└─ Auction: rank by eCPM, reserve price, generalised second price
(winner pays the minimum needed to keep its position)
Event pipeline: impressions, clicks, conversions ─► Kafka ─► joins with delays
─► online learning (minutes) or frequent retraining (hours) ─► validation ─► deploy
Budget controller (PID per campaign) reads spend stream, writes pacing stateDeep dives
Why calibration is mandatory. Ranking by eCPM compares pCTR across advertisers, and the second-price charge depends on the ratio of the runner-up’s eCPM to the winner’s pCTR. A model that is 20% over-confident for one advertiser makes them win too often and pay the wrong price. Calibrate after negative-sampling correction (isotonic or per-segment Platt), and monitor predicted/observed ratios per advertiser, placement and new ads.
Delayed conversions. Conversions arrive hours to days after clicks. Training only on “converted so far” labels biases pCVR down for recent data; options are waiting out the window (stale), or delayed-feedback models that estimate the probability a conversion is still to come. Privacy limits (no cross-site identifiers) mean some conversions arrive only as aggregates, used for calibration rather than per-example labels.
Budget pacing. Without pacing, budgets drain in the morning. A controller adjusts participation probability or bid multipliers so spend tracks the target curve through the day.
New ads. Cold-start ads get content-based predictions and a small exploration bonus until they have impressions.
Trade-offs
- Calibration is mandatory (prices depend on probabilities): a slightly better AUC with worse calibration is a worse model here.
- Freshness vs stability: online learning picks up new ads and trends within minutes but can drift or overreact to bursts of fraud or bot clicks; hourly retraining with validation gates is steadier. Use online updates for the last layers with guardrails, full retrains on a schedule.
- Privacy constraints on features: consent, the loss of third-party identifiers and on-device restrictions remove powerful features; invest in contextual signals, first-party data, and aggregated or modelled conversions, and measure the revenue cost.
- Advertiser value vs user experience: more ads and lower quality thresholds raise short-term revenue but increase hides and reduce engagement, which shrinks future inventory; use quality terms and an ad-load budget tested in long experiments.
- Model capacity vs latency: bigger cross networks help, but only on the ~100 survivors of the light ranker.
Evaluation
- Offline: log-loss and normalised entropy (vs base-rate entropy), calibration (predicted/observed ratio overall and per advertiser, placement and pCTR bucket), AUC; evaluated on the next day’s data, never a random split; replay-based auction simulation to estimate revenue impact.
- Online: A/B on revenue per mille (RPM), advertiser ROI (conversions per spend, cost per acquisition vs target), CTR; advertiser-side experiments where possible.
- Guardrails: ad load, user hides and “not relevant” feedback, latency p99, budget delivery accuracy (under- and over-spend), click-fraud rate.
- Monitoring: calibration drift by segment, feature freshness, conversion-delay distribution, spend pacing errors; automatic rollback when calibration leaves a ±5% band.
What a strong design shows
- Ranks by expected value (bid × pCTR × pCVR plus quality) in a second-price auction and explains why calibration determines prices.
- Uses a retrieval → light ranker → heavy ranker funnel sized to 100k requests/s and the latency budget.
- Corrects for negative downsampling with the right formula and evaluates with normalised entropy and calibration, not AUC alone.
- Handles delayed conversions, privacy limits and budget pacing.
- Balances revenue against advertiser ROI and user experience with explicit guardrails.