LearnSystem design

Ads click-through prediction and auction ranking

Predict the probability that a user clicks or converts on an ad, and use it to rank ads in a second-price-style auction.

ML engineering8 parts

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.

  1. RequirementsPredict the probability that a user clicks or converts on an ad, and use it to rank ads in a second-price-style auction.
  2. Estimates100k ad requests/s; ~10⁶ active ads; p99 budget 50–100 ms; base CTR ~1%.
  3. API
  4. Data model
  5. 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.
  6. Deep dives
  7. Trade-offscalibration is mandatory (prices depend on probabilities); freshness vs stability; privacy constraints on features; advertiser value vs user experience.
  8. 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

  1. Retrieval by targeting and embeddings.

  2. Fetch features for the candidates.

  3. Dot product / small model to top ~100.

  4. CTR and CVR models on the ~100 survivors.

  5. Calibration, auction and pacing.

  6. Network and tail headroom.

The ~80 ms p99 budget is split across retrieval, feature fetch, ranking, calibration and auction, with ~30 ms left for network and tail headroom.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
  • 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

Request-path funnel for ad rankingA request enters the funnel and is narrowed from about 1,000 candidates to about 100, then scored by the heavy CTR and CVR model. Calibration, eCPM, pacing and the auction turn those scores into a ranked set of ads.Ad requestpage or feed slotRetrieval~1,000 candidatesLight rankertop ~100Heavy rankerCTR and CVRCalibrationper segmenteCPMbid × pCTR (× pCVR for CPA) ×1000 + qualityPacingbudget controllerAuctionsecond-priceRanked adsauction_idpCTR, pCVR1234InputFunnelScoringAuction
  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.

The request path moves an ad request through retrieval, light and heavy ranking, calibration, eCPM, pacing and a second-price auction before returning ranked ads.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1RetrievalThe ad request enters; retrieval selects ~1,000 eligible ads.
2RankingThe light ranker keeps top ~100; the heavy ranker scores CTR and CVR.
3Calibration and eCPMCalibration gives pCTR and pCVR; eCPM combines bid, probabilities and quality.
4Pacing and auctionPacing adjusts participation; the auction ranks by eCPM and returns ranked ads.

Source: This page's text

Boxes
BoxGroupDetail
Ad requestInputpage or feed slot
RetrievalFunnel~1,000 candidates
Light rankerFunneltop ~100
Heavy rankerFunnelCTR and CVR
CalibrationScoringper segment
eCPMScoringbid × pCTR (× pCVR for CPA) × 1000 + quality
PacingScoringbudget controller
AuctionAuctionsecond-price
Ranked adsAuctionauction_id

Source: This page's text

CalculatorNegative-sampling correction and CPC eCPM

Corrected pCTR = Raw score q ÷ (Raw score q + (1 − Raw score q) ÷ Negative sampling rate w)

CPC eCPM = Bid × Corrected pCTR × 1000

Worked cases
CaseRaw score qNegative sampling rate wBidCorrected pCTRCPC eCPM
Worked case0.090.110.979%9.79
See how the raw score q of a negative-downsampled model maps back to the true pCTR, and how bid and pCTR combine into a CPC eCPM.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
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 state

Deep 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.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.