ML System Design · Module 31 of 47 · 11 concepts · about 13 min

Design: Ad Click Prediction

A complete design for Kirana Kart's sponsored products, where brands pay per click to appear in search and on the home screen: predicting click probability, ranking ads in an auction, why calibration matters more here than anywhere, sparse high-cardinality features, training on billions of rows, budget pacing, and keeping ads from ruining the experience.

At work: Asked as 'design an ad click prediction system' or 'design ad ranking'. Ads fund much of the internet, and click prediction is among the most heavily engineered ML systems in existence.

Requirements

What it is

Clarify:

  • goal: ad revenue, while keeping the shopping experience good and giving advertisers fair results;
  • placement: up to two sponsored slots in search results and one in the home-screen row;
  • pricing: advertisers bid per click; a click is charged by a second-price rule (below);
  • scale: every search and home view is an ad opportunity, millions a day, each with dozens to hundreds of eligible ads;
  • latency: inside the search and home budgets (tens of milliseconds for ads);
  • constraints: advertiser budgets must not be overspent; relevance minimums so ads match the query.

Why it matters

Ads have three parties: users, advertisers and the platform.

  • Pure revenue maximisation shows irrelevant ads and drives users away.
  • Advertisers leave if their money buys poor clicks.
  • The design has to balance all three.

In the real world: Retail media (sponsored products on shopping and delivery apps) has become a major revenue source for e-commerce and quick-commerce companies.

Treating it as 'rank by bid'. The highest bidder's ad may never be clicked, which earns nothing and annoys users.

Framing: predicted click rate and the auction

What it is

The core ML task is predicting the probability of a click (pCTR) for each eligible ad in each context. The auction then ranks ads by expected value:

  • eCPM (expected revenue per thousand impressions) = bid × pCTR × 1,000;
  • show the top ads by eCPM, above a relevance or quality minimum;
  • second-price: a clicked ad pays just enough to have kept its position: the next ad's eCPM ÷ its own pCTR, never more than its bid.

Why it matters

Ranking by expected value rewards relevance: a cheaper ad that people click can beat an expensive one they ignore.

  • The predicted probability enters the price directly, so its level matters, not only its order.

In the real world: Google's search ads and most sponsored-listing systems rank by bid times predicted click rate (with quality adjustments), a design going back to the early 2000s.

Visual example

Computed

Four ads compete for 2 slots. Brand B wins the top slot with the lowest bid, because people click it most.

eCPM = bid × pCTR × 1,000; payment per click = next ad's eCPM ÷ (1,000 × own pCTR)
rankadvertiserbid ₹pCTReCPM ₹shown?pays per click ₹
1Brand B (biscuits)55%250Yes4
2Brand A (cooking oil)102%200Yes8
3Brand C (premium tea)200.8%160No—
4Brand D (detergent)81.5%120No—

Optimising only AUC for a click model. AUC ignores calibration; an ad model with excellent AUC and probabilities twice too high overcharges or mis-ranks across ads.

Practise it: Design an Ad Ranking System

Data and labels

What it is

The data is enormous and very imbalanced:

  • every ad impression logged with context, position and the auction's other candidates;
  • clicks joined to impressions (seconds later);
  • conversions (purchase of the advertised product) joined later, sometimes days later;
  • click rates of a few percent or less, so 95–99% of rows are negatives.

Why it matters

Volume makes negative sampling standard (module 7), which then requires recalibration.

  • Position strongly affects clicks; it must be logged and handled (module 7).
  • Conversions are rarer and delayed but closer to what advertisers value; predicting them (pCVR) is a second, related task.

In the real world: Large ad systems process billions of impressions a day and keep only a small, recorded fraction of non-clicked impressions for training.

Joining clicks to impressions with too short a window and missing late clicks, or with no deduplication and counting a double-tap as two clicks. Both shift the labels and the prices.

Practise it: Design Model Monitoring, Design a Search Ranking System

Features

What it is

Ad features are mostly sparse and high-cardinality:

  • IDs: user, ad, advertiser, product, query, store;
  • context: query text and category, page, position, time, device;
  • history: past click rates of this ad, this advertiser, this user on this category (with smoothing for rare ones);
  • crosses: query × ad category, user segment × advertiser;
  • embeddings of queries, products and users.

Handled with the hashing trick and learned embeddings (module 9).

Why it matters

Click behaviour depends on specific combinations: this kind of user, this query, this brand.

  • Memorising frequent combinations (crosses, IDs) and generalising to rare ones (embeddings) is exactly what modern click models are built to do.

In the real world: Kirana Kart's ad model hashes about 30 sparse feature groups and crosses into embedding tables, plus a dozen smoothed historical click rates.

Using an ad's raw historical click rate when it has only a few impressions. Two clicks in ten impressions is not a 20% click rate; smooth towards the category average.

Practise it: Design a Demand Forecasting Platform, Design a Predictive Maintenance System, Design a Real-Time Fraud Detection System, Design an ML Feature Store

The model

What it is

Click models have evolved through a well-known ladder:

  • logistic regression on hashed sparse features and crosses: fast, calibrated, still a strong baseline;
  • boosted trees feeding logistic regression (Facebook, 2014): trees discover feature combinations;
  • deep CTR models: Wide & Deep, DeepFM, Deep & Cross Network: embeddings for sparse IDs plus layers that learn interactions automatically;
  • multi-task models predicting click and conversion together, since conversion is rarer.

Why it matters

The data (billions of rows, huge ID spaces, valuable interactions) is where deep models clearly beat trees.

  • Small gains in log loss translate directly into revenue at this scale.
  • Simpler models remain useful as baselines and fallbacks.

In the real world: Google's Wide & Deep (2016) and Deep & Cross (2017), and Huawei's DeepFM (2017), are standard references; most large ad systems use descendants of them.

import torch, torch.nn as nn

class DeepCTR(nn.Module):
    """Embeddings for sparse features, plus a linear 'wide' part for memorisation."""
    def __init__(self, n_buckets: int, n_fields: int, dim: int = 16):
        super().__init__()
        self.emb = nn.Embedding(n_buckets, dim)          # hashed ids and crosses share one table
        self.wide = nn.Embedding(n_buckets, 1)
        self.deep = nn.Sequential(nn.Linear(n_fields * dim, 256), nn.ReLU(), nn.Linear(256, 1))
    def forward(self, ids):                              # ids: (batch, n_fields) hashed bucket ids
        e = self.emb(ids).flatten(1)
        return torch.sigmoid(self.wide(ids).sum(1) + self.deep(e))

Jumping to the newest deep architecture without a calibrated logistic-regression baseline. The baseline tells you what the deep model is worth, and it is the fallback when the deep model misbehaves.

Calibration is a requirement here

What it is

Because the predicted probability sets rankings and prices:

  • after negative sampling, correct the probabilities (module 7);
  • then calibrate on recent, unsampled data (isotonic or Platt, module 12), often per segment (placement, device);
  • monitor predicted ÷ actual click rate continuously; it should stay close to 1.

Why it matters

Miscalibration costs money on both sides.

  • Too-high pCTR inflates eCPM and second prices: advertisers are overcharged relative to value and eventually cut spending.
  • Too-low pCTR under-prices ads and loses revenue.
  • Mixed calibration across segments (good on phones, bad on web) distorts which ads win.

In the real world: Ad teams commonly track 'calibration ratio' (predicted clicks over actual clicks) per placement as a primary health metric, alongside log loss.

Visual example

Computed

True click rate 2%. A model trained on sampled negatives predicts 6% for everything. Log loss rises, and every price is three times too high.

1,000 impressions, 20 clicks
modelpredicted ratelog losspredicted ÷ actual clicks
Calibrated2%0.0981.0
Not corrected for sampling6%0.11693.0

Recalibrating once at training time. Click rates change by hour and season; calibration must be checked and refreshed continually.

Practise it: Design an Ad Ranking System

Training and serving

What it is

Scale and freshness drive both:

  • training: on very large data with sharded embedding tables (module 15); frequent incremental updates (several times a day) because ad inventory and click rates change fast; periodic full retrains;
  • serving: retrieve eligible ads (targeting, budget left, relevance to the query), score them with the click model in one batch, run the auction, apply pacing;
  • pacing: slow an advertiser's participation so the daily budget lasts all day rather than running out by 10 a.m.

Why it matters

New ads appear constantly and need predictions from their first impression.

  • Incremental updates keep the model current; full retrains reset accumulated drift.
  • Pacing protects advertisers from spending their budget on the morning's traffic alone, which improves their results and keeps them advertising.

In the real world: Kirana Kart updates its ad click model every four hours from the latest clicks and retrains fully each week; a pacing controller adjusts each campaign's participation rate every few minutes.

Visual example

Ads

Score, auction, pace, then show.

Serving sponsored products for one search

  1. Eligible adsMatch the query; budget left
  2. ScorepCTRClick model, one batch
  3. Quality floorDrop irrelevant ads
  4. AuctionBid × pCTR; second price
  5. PacingSpread budget over the day
  6. Show and logUp to two slots

Spending a whole daily budget in the first hours. The advertiser gets no evening traffic, which is often when grocery orders peak.

Practise it: Design an ML Training Pipeline, Design Feature Monitoring, Diagnose Training-Serving Skew, Design a Model Serving Platform, Design an ML Feature Store

Evaluation

What it is

Offline, then online with all three parties in view:

  • offline: log loss (or normalised entropy, log loss relative to always predicting the average rate), calibration ratio, AUC; slices by placement, device, new ads;
  • online: revenue per thousand opportunities, click-through, conversion rate for advertisers, cost per click;
  • user guardrails: organic engagement, search success, complaints, ad 'hide' rate;
  • advertiser guardrails: return on ad spend, budget delivery.

Why it matters

Revenue can rise at users' expense.

  • Showing more and worse ads lifts revenue this week and erodes searches and orders over months.
  • Long-term holdouts (users seeing fewer ads) measure that slow cost (module 17).

In the real world: Kirana Kart's ad experiments must not reduce organic basket additions per search; one revenue-winning model was rejected for exactly that.

Launching on revenue alone. A model that wins revenue by showing more irrelevant ads may lose more in organic sales than it earns.

Practise it: Design a Large-Scale Classification Platform, Design a Predictive Maintenance System, Design a Real-Time Anomaly Detection System, Design a Recommendation System, Diagnose Training-Serving Skew, Improve a Low-Recall Model, Design a Search Ranking System

Monitoring

What it is

Watch money and quality in near real time:

  • calibration ratio per placement, hourly;
  • revenue, cost per click and click-through per hour against normal;
  • budget pacing: campaigns over- or under-delivering;
  • click fraud signals: bursts of clicks from one device or network (module 28);
  • model freshness: time since last successful update.

Why it matters

Errors in ad systems cost money by the minute, so detection must be fast.

  • A calibration break overcharges every advertiser until fixed, and refunds are painful.
  • Click fraud inflates costs for advertisers and must be filtered from both billing and training data.

In the real world: Kirana Kart pauses incremental model updates automatically if the calibration ratio of the candidate update drifts outside 0.9–1.1 on held-out recent traffic.

Training on fraudulent clicks. The model learns that the fraudster's targets are popular and shows them more.

Practise it: Design Feature Monitoring, Design Model Monitoring

Interview questions: the ad click design

What it is

The questions interviewers ask about the ad click design, from the first screening call to the senior round. Cover the answer, say yours aloud, then compare.

Why it matters

Reading an idea and explaining it are different skills.

  • Each answer below is the two or three sentences an interviewer is listening for.
  • The reasoning behind each one is in the cards above. If an answer surprises you, go back to that card.

In the real world: Ad interviews go deep on calibration, sparse features and the auction; candidates who connect pCTR to price stand out.

Q: How are ads ranked?

By expected value, bid times predicted click rate (eCPM), above a quality or relevance floor, with second-price payments so a clicked ad pays just enough to keep its position.

Q: Why is calibration so important for ad models?

Predicted probabilities enter eCPM and prices directly, so miscalibration mis-ranks ads and over- or under-charges advertisers. Correct for negative sampling, calibrate on recent data, and monitor predicted over actual clicks.

Q: What model would you use?

A calibrated logistic regression on hashed sparse features and crosses as baseline, then a deep CTR model (Wide & Deep, DeepFM or DCN) with embeddings, possibly multi-task for click and conversion.

Q: What offline metric?

Log loss or normalised entropy, plus calibration ratio; AUC alone ignores calibration.

Q: How do you stop ads hurting the user experience?

Relevance floors, limits on ad slots, user guardrails such as organic engagement and hide rate in every experiment, and long-term holdouts.

Q: What is budget pacing?

Throttling an advertiser's participation so their daily budget is spread across the day, not spent on early traffic.

Ranking by bid alone, or never mentioning calibration.

Exercise: train and calibrate a click model

What it is

A short build that uses this module's ideas. Write it yourself before looking anything up; the checks at the end tell you whether it works.

Why it matters

An idea you have only read fades in a week.

  • Building it once, even in fifty lines, is what makes it yours.
  • Interviewers can tell the difference between someone who has read about a loop and someone who has debugged one.

In the real world: Click-model take-home tasks at ad companies are very close to this, and calibration is usually the part reviewers check first.

Your task. Train a click-prediction model on public ad data, show the effect of negative sampling on calibration, and fix it.

Steps

  1. Use the Criteo or Avazu click dataset (a sample of a few million rows is enough).
  2. Hash the categorical features into a fixed number of buckets.
  3. Train logistic regression on all rows; record log loss, AUC and predicted ÷ actual click rate on a later slice.
  4. Train again keeping only 10% of negatives; record the same three numbers.
  5. Apply the sampling correction, then isotonic calibration on a recent unsampled slice; record again.
  6. Simulate a four-ad auction using your model's pCTR and compute second prices before and after correction.

You are done when

  • The sampled model's AUC is similar but its calibration ratio is far above 1.
  • After correction and calibration the ratio is close to 1.
  • You can show how the auction's prices changed.

Stretch. Train a small DeepFM or Wide & Deep model with an open-source library and compare log loss.

Practise it: Diagnose Training-Serving Skew