Black Friday: 30% off every plan through November 30. See the prices
SysDesignPrep.com
System design interview question

Design an Ad Click Prediction System

The model that predicts whether a user clicks an ad: 150 M calibrated predictions a second inside a 100 ms auction, retrained every hour.

Last updated 2026-11-14. Difficulty: hard. Patterns: ml-systems, feature-store, calibration, stream-processing, low-latency. Reported at Meta, Google, Snap, Pinterest, LinkedIn, TikTok, Amazon.

Sit this question with an AI interviewer.

An AI mock is timed like the real round, out loud or typed, and ends with a debrief scored for your level. Practice with AI, in every pass, has no clock and the AI Mentor beside you. Or watch a sample interview first.

Or sit it in the style of Meta · Google · Snap · Pinterest, run as that company’s round is reported to go.

The short answer

How to design an Ad Click Prediction System in a system design interview, in five steps:

  1. Scope it. Predict a click probability for every candidate in an auction, log exactly what the model saw, label impressions with clicks that arrive later, build training data without leakage, fresh features online, their history offline, refresh the model continuously, keep predictions calibrated, ship and roll back models safely.
  2. Set the targets. Scoring latency: p99 < 30 ms for 300 ads; Throughput: 150 M scores/s at peak; Calibration: predicted ÷ observed 0.95 to 1.05; Freshness: model < 2 h · counters < 30 s.
  3. Do the numbers. Ad requests per second: ~230 k/s avg · ~500 k/s peak; Scores per second at peak: ~150 M/s; GPUs for scoring: ~300 (vs ~1,500 naive).
  4. Draw the design. Experiment platform, Model registry, Model monitor, Online feature store, Ad server, Scoring service, Trainer, Event collector, Event log.
  5. Go deep where it is hard.
    • Joining a click that arrives later → Event-time stream join, 10-minute window closed by the click watermark, plus a daily 24-hour rebuild.
    • Training rows without leakage → Logged inputs for production features; backfills by an as-of join on available time from a history with both timestamps.
    • Scoring 300 ads in 30 milliseconds → One request is one batch: user part once and broadcast, candidates in one GPU pass, ad tables on the GPU, user tables in host RAM.
    • Calibrated probabilities, not scores → A monotone map per segment (placement × country group × format), fitted every 30 minutes on recent labelled rows, versioned with the model.
    • Hourly, daily or continuous training → Hourly warm-start refresh with delta pushes, a weekly full retrain, and minute-fresh counters as features.
    • Shipping a new model safely → Offline replay, shadow on 10 % of requests, a 1 % canary with automatic guardrails, a budget-split A/B test, then a ramp with a holdback.
The Ad Click Prediction System design, as drawn at the end of the walkthrough: User app, Ad server (auction, 100 ms), Scoring service (one batch, user part once), Offline store (rows + history), Trainer (hourly warm start + weekly), Online feature store (KV), Event log (served · beacons), Feature pipelines (stream + batch), Event collector, Click aggregator (invalid traffic), Label joiner (10 min, event time), Model registry (versions + maps), Calibration fitter (30 min), Model monitor and Experiment platform.
The design at a glance. The architecture the walkthrough ends on. Watch it built step by stepOpen full size

Functional requirements

  • Predict a click probability for every candidate in an auction. About 300 ads per request, after the ad server’s pre-ranker, each with a pCTR for the slot it would fill, returned inside the auction’s deadline. The auction multiplies it by the bid and prices clicks from it, so it must be a probability, not just a good ordering.
  • Log exactly what the model saw. Every served ad carries the inputs and versions used to score it, so its training row can be rebuilt bit for bit and any prediction explained later. Logged once per request, not once per candidate.
  • Label impressions with clicks that arrive later. A click arrives seconds to hours after its impression, on another stream. Each impression becomes one example, clicked or not, after a defined wait, with clicks flagged as invalid traffic removed.
  • Build training data without leakage. Every feature in a row is the value serving could have read at that moment. That includes features added later and backfilled over past weeks, which is where leakage usually gets in.
  • Fresh features online, their history offline. Counters under 30 s old at millisecond latency for scoring, and every past value with its timestamps for training, both written from one definition per feature.
  • Refresh the model continuously. Thousands of new ads an hour and click rates that move within a day. Routine refreshes ship without a person approving each one; architecture and feature changes go through a full experiment.
  • Keep predictions calibrated. Predicted clicks equal observed clicks per placement, country and ad format, measured continuously, with a correction that does not wait for a retrain.
  • Ship and roll back models safely. Shadow, canary and an online A/B test for new models; automatic gates and a short canary for hourly refreshes; rollback in one step to a version that is still loaded.
  • Out of scope. Retrieval, targeting, the auction itself, budgets and pacing (the Ad Serving design), billing-grade click counting (the Ad Click Aggregator), the choice of network architecture, and conversion prediction beyond how it would reuse this pipeline.

Non-functional requirements

  • Scoring latency (p99 < 30 ms for 300 ads). The model’s share of a 100 ms auction. This drives the hardest trade-off in the design: model size and feature count against a fixed budget per request, at 150 M scores a second.
  • Throughput (150 M scores/s at peak). 500 k requests a second × 300 candidates. Capacity is counted in candidates scored, not requests, and GPUs are the largest cost in the design.
  • Calibration (predicted ÷ observed 0.95 to 1.05). Per placement, country group and ad format, because errors cancel in the global average. Prices and pacing are computed from predictions, so a 5 % bias is a 5 % mispricing.
  • Freshness (model < 2 h · counters < 30 s). New ads and campaigns move click rates by the hour. Minute-level freshness comes from features, hour-level from retraining; the model’s age is the time from an impression to a published model that learned from it.
  • Training and serving parity (replayed score = served ± 1e-4). Re-scoring a sample of served requests offline must reproduce the served raw score. It is the only check that covers the transform code as well as the stored values.
  • Label correctness (no invented negatives). A delayed or stalled click stream must delay labels, never turn real clicks into non-clicks, and invalid clicks never become positives. A bad hour of labels is a bad model an hour later.
  • Always a score (100 % of auctions scored). Degrade by scoring fewer candidates, then by falling back to the pre-ranker’s calibrated scores; never an empty slot because the model is slow. Fallback scores are marked and never trained on.
  • Privacy (consent honoured · deletion < 30 days). Personalised features only for users who allow ad personalisation. A deletion removes the user’s embedding row, online features and training rows, which is why rows are partitioned so they can be rewritten.

Back-of-envelope estimates

  • Ad requests per second: ~230 k/s avg · ~500 k/s peak. 20 B requests/day ÷ 86,400 ≈ 231 k/s. The evening peak is about twice the average, ~460 k/s; size for 500 k/s.
  • Scores per second at peak: ~150 M/s. 500 k requests/s × 300 candidates = 150 M predictions/s. Requests are not the unit of work here, candidates are: every candidate the ad server adds raises the model’s cost linearly.
  • GPUs for scoring: ~300 (vs ~1,500 naive). Run whole for each candidate, a GPU scores ~100 k candidates/s: 1,500 GPUs. The part over the user’s last 1,000 events is ~80 % of that work and identical for all 300 candidates. Computed once, a request costs 0.8 + 300 × 0.2 ≈ 61 units instead of 300, ~5× less, so ~500 k/s per GPU and 150 M ÷ 500 k = 300 GPUs before headroom. This one split is worth 1,200 GPUs.
  • Embedding tables: ~128 GB served · ~512 GB in training. ~2 B rows (≈1.75 B user-side ids, ≈250 M ad-side ids and hashed crosses) × 64 dims. In fp32 for training 2 B × 64 × 4 B = 512 GB; quantised to int8 for serving 128 GB. More than one 80 GB GPU holds, so the ad-side tables (~16 GB) live on the GPU and the user-side ones (~112 GB) in host RAM, read once per request.
  • Impressions and clicks per day: 30 B impressions · 300 M clicks. 1.5 impressions per request (some fetches fill two slots, some none): 20 B × 1.5 = 30 B impressions/day, ~350 k/s on average and ~700 k/s at peak. At a 1 % click rate that is 300 M clicks/day: positives are 1 row in 100, which is why non-clicks are sampled.
  • Label joiner state at peak: ~420 GB. Each impression is held open until its 10-minute window closes: 700 k/s × 600 s = 420 M open impressions × ~1 KB (the served row) ≈ 420 GB, about 1.6 GB on each of 256 partitions. A 20-minute stall of the click stream adds ~840 GB, so the state lives on local SSD, not in memory.
  • Training rows per day: ~3.3 B rows · ~3.3 TB. Keep every click and 10 % of non-clicks with weight 10: 300 M + 0.1 × 29.7 B ≈ 3.27 B rows/day at ~1 KB ≈ 3.3 TB/day, or ~140 M rows for each hourly training run. Thirty days for the weekly full retrain is ~100 TB.
  • Hourly model update: ~7 GB instead of ~130 GB. In an hour about 100 M embedding rows change (the users and ads in that hour’s data) × 64 B = 6.4 GB, plus ~1 GB of dense layers: ~7 GB. Pushing the whole 130 GB model to ~120 hosts every hour would be ~16 TB/h of internal traffic; deltas are what make an hourly refresh cheap.

Components

  • Experiment platform (arms · budget split): The A/B Testing Platform design: assigns users to model arms by a hash in the ad server’s process and computes the online metrics. For model tests the arms also split each campaign’s budget by traffic share, and it keeps a long-running 1 % holdback on a frozen weekly model that measures what hourly freshness is worth.
  • Model registry (versions · maps · splits): Every model version with its lineage (training hours, feature schema, parent checkpoint, offline metrics), the calibration maps fitted for it, and which share of traffic each version serves: production, canary, shadow, holdback. Scorers watch it and swap versions between requests; a rollback is one write that points production at a version still loaded in memory.
  • Model monitor (calibration · skew · guardrails): Independent of the trainer and the fitter: compares predicted with observed clicks per segment every 10 minutes, tracks how far each calibration map bends from the identity, watches the label rate and feature distributions online against offline, and judges every canary. It can roll a version back or freeze publishing on its own, because the system that ships a model should not be the one that judges it.
  • Online feature store (KV · latest value · SSD): Latest feature values keyed by user id: profile, the last 1,000 interactions as ids, and per-advertiser counters, ~10 KB per user and ~15 TB for 1.5 B users, in an Aerospike or Bigtable class store with p99 reads under 5 ms. Also the source of the per-ad counter snapshot scorers pull every minute. It holds no history: “what was this value at 14:02 yesterday” is the offline store’s question.
  • User app (renders ads · beacons): Shows the ads the ad server picked, sends an impression beacon when an ad is on screen and a click through the tracker, both carrying the signed impression id. Beacons can arrive late from a phone that was offline, or twice after a retry; the impression id is what makes them joinable and easy to deduplicate.
  • Ad server (auction · 100 ms): The caller, as in the Ad Serving design: retrieves, filters and pre-ranks to ~300 candidates, calls the scorer with a 35 ms deadline, and runs the auction on bid × pCTR. Here it matters for two things: it sets how many candidates the model sees, which is the overload dial, and it writes the served record, including the inputs the scorer used, that every training row starts from.
  • Scoring service (GPU · user part once): Treats one request as one batch: reads the user’s features once, runs the part of the network over the user’s history once, then scores all 300 candidates in a single GPU pass and applies the calibration map. Ad-side tables (~16 GB) and dense layers sit in GPU memory, user-side tables (~112 GB, int8) in host RAM. Returns calibrated pCTRs and a log blob of exactly the inputs it used.
  • Trainer (hourly warm start · weekly full): Every hour, continues from the serving checkpoint on the last hour’s ~140 M rows and produces a candidate in ~25 minutes; every week, retrains from scratch on 30 days so architecture and feature changes land and slow drift is reset. Evaluates each candidate on the impressions just after its training data, never on a random split, and publishes only the rows that changed, ~7 GB.
  • Event collector (impression · click beacons): The HTTPS edge for impression and click beacons. Verifies the impression id’s signature, so a forged click cannot label a row, stamps the receive time next to the client’s event time, appends to the event log and only then answers. Duplicates are expected from phone retries and are resolved downstream by impression id.
  • Event log (Kafka · served · beacons): Topics for served records keyed by request id, impressions and clicks keyed by impression id, and invalid-traffic flags: ~1 GB/s at peak, kept 3 days so the joiner and the feature jobs can replay after an outage. Every downstream consumer reads event time from the records, never the time it happens to read them.
  • Feature pipelines (Flink + daily batch): Turns events into features: streaming jobs keep counters (an ad’s impressions and clicks per placement over 1 h and 1 d, a user’s clicks per advertiser over 30 d, recent interaction lists) under 30 s behind, and daily batch jobs compute slow features. Each value is written twice by the same code: to the online store as the latest value, and to the offline history with its event time and the time it became readable online.
  • Offline store (columnar · by hour · as-of): Training rows partitioned by hour, and the history of every feature value with event time and available time, as Parquet or Iceberg tables on object storage. Serves the trainers, as-of joins that backfill a new feature exactly as serving would have seen it, the calibration fitter, the monitor, and a daily rebuild that relabels with a 24-hour window and late invalid-traffic verdicts.
  • Click aggregator (invalid traffic · billing): The Ad Click Aggregator design: deduplicates clicks for billing and flags invalid traffic (bots, click farms, accidental double taps), most within minutes and the rest in a nightly pass. Those flags matter to training as much as to billing: a model trained on bot clicks learns to predict bots, and an ad being click-bombed would look like a great ad.
  • Label joiner (by impression id · 10 min): A stream join that turns a served record, its impression, any click and any invalid-traffic flag into one training row, keyed by impression id. It waits 10 minutes of event time after the impression, closed by the click stream’s watermark rather than the wall clock, so a stalled click pipeline delays labels instead of inventing negatives. Emits every click and 10 % of non-clicks with their weights.
  • Calibration fitter (per segment · every 30 min): Fits a monotone map from raw score to click probability for each of ~4,000 segments (placement × country group × ad format) on the last 6 hours of labelled rows, undoing the negative sampling and adding back the ~2 % of clicks the 10-minute window misses. Thin segments fall back to their parent. A map belongs to one model version and is never applied to another.

User flows

  1. Score 300 ads inside one auction. The read path the auction waits on. The model sees 300 candidates but only one user, and the design exploits that: one feature read and one pass over the user’s history per request, then a single batched pass over the candidates.
    1. The app asks for ads; the ad server narrows the field to 300 candidates and looks up this user’s model arm. Retrieval, targeting, budgets and the pre-ranker cut ~5 k eligible ads to 300; that is the Ad Serving design and this one starts at its output. The arm is a hash of the user id against the experiment config, evaluated in process with no network call, and it names the model version this request will be scored with.
    2. The ad server calls the scorer with the user, the context, 300 ad ids and the slots, under a deadline. One call per request, not one per candidate: the request carries 300 ids, not 300 feature vectors, so the payload is a few KB. Position is a separate shallow part of the model, so each ad is scored once at a reference position and the slot factors are applied afterwards.
    3. The scorer reads the user’s features in one round trip and takes ad features from memory. About 10 KB per user (profile, last 1,000 interactions, per-advertiser counters) in one multi-get with a 6 ms cap, hedged to a second replica at the p95. Per-ad counters for all 10 M ads (~1 GB) are pulled as a versioned snapshot every minute, so a request touches the network once. A key that misses its cap takes the default value training uses, declared once in the feature registry.
    4. The scorer runs the user half of the network once, then all 300 candidates in one GPU pass. The user tower over 1,000 events is ~80 % of the compute per candidate; repeated 300 times it would need ~1,500 GPUs, computed once ~300. User-side embeddings (~200 ids) are gathered from host RAM once; ad-side embeddings for the 300 candidates are gathered on the GPU, where those tables live. A dynamic batcher may add 2 or 3 other requests to the same launch, waiting at most 2 ms.
    5. Raw scores go through the calibration map for each ad’s segment, then the slot factor. The map was loaded with this model version and is selected by placement, country group and ad format; it is monotone, so it never reorders ads within a segment, but it does correct one format against another. The raw score is kept as well, because calibration is refitted on raw scores.
    6. The scorer returns calibrated pCTRs, the versions used and a blob of the inputs it read. The blob (~1.1 KB: user features as read with their age, the ad snapshot version, the arm, model and map versions, the mode) is what makes a training row exact. Returning it to the caller means one record and one join key downstream, instead of a scorer log that has to be joined to a served log.
    7. The auction ranks on bid × pCTR, and the ad server writes the served record, blob included. Only winners get rows: they carry impression ids, slots, pCTR, raw score and price. If the scorer missed the deadline the record says mode "fallback", and the joiner drops those rows, because training on them would teach the model the fallback’s mistakes.
  2. An impression and a click become a row. The write path that feeds training. The click arrives seconds to minutes after the impression, on a different stream, so no row can be written until the system has waited long enough to call a non-click a non-click.
    1. The ad appears on screen and the app sends an impression beacon with the signed impression id. The collector checks the signature, appends to the event log and only then answers. Phones retry until they get an answer, so duplicates are normal; the impression id makes them harmless.
    2. The label joiner opens state for the impression and starts a 10-minute event-time timer. The served record arrived first, because it is written before the page renders, so the state already holds the row the model scored. A served ad that never reaches the screen is dropped after 30 minutes and never becomes a negative: the user did not see it.
    3. The feature pipelines count the impression into the ad’s and the user’s counters. Same event, different consumer. Each counter value goes to the online store and, with its event time and the time it became readable online, to the offline history. That second timestamp is what a backfill must use later to see only what serving could see.
    4. Forty seconds later the user taps the ad, and the click goes through the collector to the log. The click is keyed by the same impression id, so it lands on the same joiner partition as its impression. Writing the event before redirecting, and keeping that fast, is the Ad Click Aggregator’s problem; here what matters is that the click carries the id.
    5. The joiner marks the open impression as clicked; a second tap changes nothing. One impression is one example with label 0 or 1, however many taps. The row is not emitted yet: it waits for the window to close so that an invalid-traffic verdict can still reach it.
    6. An invalid-traffic flag that arrives inside the window removes the click. Most bot and click-farm verdicts arrive within minutes. Flags that arrive after the window are applied by the daily rebuild. Without this, an ad being click-bombed looks like a great ad, and the model learns to predict bots.
    7. When the click stream’s watermark passes the impression time plus 10 minutes, the row is emitted. Every click is kept; a non-click is kept with probability 10 % and weight 10, which cuts 30 B rows a day to ~3.3 B without losing a positive. The watermark is the minimum over every click partition in every region, so a lagging region holds windows open instead of closing them early.
    8. A daily batch run of the same join relabels yesterday with a 24-hour window and final verdicts. It feeds the weekly full retrain with exact labels and measures the completion factor per placement: clicks within 24 hours divided by clicks within 10 minutes, about 1.02. Calibration applies that factor, so the auction sees the true click probability even though the hourly model learned from a 10-minute label.
  3. A record evening: 150 M scores a second. The scale-breaking case. Doubling traffic doubles candidates scored, and GPUs cannot be added in minutes, so the scorer stays inside its deadline by doing less per request instead of failing requests.
    1. Requests climb to ~500 k a second; each is a batch of 300 candidates, 150 M scores a second. Capacity is candidates scored, so the router balances by outstanding candidates per GPU host rather than round robin. Every request costs about the same, but hosts differ in how much queued work they already hold.
    2. Each host packs several requests into one GPU launch, waiting no more than 2 ms to fill it. A launch with 3 requests (900 candidates) uses the GPU far better than three launches of 300, at the cost of up to 2 ms of waiting. The cap matters more than the batch size: an unbounded wait turns a busy evening into a latency incident.
    3. Feature reads grow with requests: 500 k multi-gets a second against the online store. About 5 GB/s of reads spread over shards by user id. A slow shard is hedged at the p95; a key that misses its cap is a missing value with the training default, flagged in the log blob, so the request still scores on time with slightly less information.
    4. Queueing inside the scorer passes its threshold, and every response starts reporting load. Queue time is the honest signal. GPU utilisation is high both when healthy and when overloaded, so it says nothing about whether the deadline is in danger.
    5. The ad server scores fewer candidates on low-value placements first: 300, then 200, then 100. The pre-ranker already sorted by expected value, so the dropped tail carries little of it: the cut to 200 removes a third of the work and a much smaller share of revenue, which a replay of logged auctions measures per placement before the ladder is set. The candidate count goes into the served record so trimmed auctions are visible in analysis.
    6. A host that stays slow is hedged: the request goes to a second host after the p95. Hedging costs extra GPU on ~5 % of requests and removes most of the tail a single slow host would add. A host whose queue stays long is taken out by its health check rather than left to absorb hedges.
    7. An auction whose scores miss the deadline runs on the pre-ranker’s scores and is marked. The fallback scores are calibrated to the same scale, so prices stay consistent with ranking. The served record says mode "fallback" and the joiner leaves those rows out of training; the share of fallback auctions is a paged metric, with an alert above 0.1 %.
  4. The click stream stalls for 20 minutes. The failure that quietly breaks an ML system. If anything treats “no click yet” as “no click”, an hour of training data says nobody clicks, the next model believes it, and prices fall across every auction.
    1. Clicks from one region stop reaching the event log, while served records and impressions keep flowing. A replication link between the region’s collectors and the log fails. Collectors buffer to disk and keep accepting, so nothing is lost yet, only late. The click partitions fed by that region stop advancing.
    2. The joiner’s click watermark stops at the last click it saw, so no window past that point closes. A joiner closing windows on the wall clock would now emit 20 minutes of impressions with almost no clicks: ~84 M sampled non-clicks and a handful of positives, a click rate near zero. Because windows close on the minimum watermark across regions, they simply wait.
    3. State grows instead: twenty more minutes of open impressions, ~840 GB, spilled to local SSD. The joiner is sized for an hour of stall on local NVMe. Past that it applies back-pressure and stops reading impressions rather than closing windows, and the event log’s 3-day retention holds what it has not read.
    4. The trainer finds the hour incomplete and does not publish; production keeps the previous model. An hour is ready only when the joiner’s output watermark has passed its end. A model one hour older costs a small fraction of a percent of revenue; a model trained on an hour with no clicks would underpredict every auction it touched.
    5. The calibration fitter holds its maps, and the monitor pages on the label rate and freezes publishing. A fitter refitting on the partial window would scale every prediction down. The monitor compares each segment’s click rate in emitted rows with the same hour last week: 0.1 % against 1 % on flat traffic is a pipeline fault, not users changing their minds. The freeze stops every automatic publish until a person lifts it.
    6. Clicks catch up; the watermark moves and windows close with correct labels, in order. Because windows are in event time, a row emitted during the catch-up is identical to the row that would have been emitted on time. Late is safe; wrong is not.
    7. The trainer processes the delayed hours in order, and publishing resumes once the monitor lifts the freeze. If a region’s clicks were lost for good, its impressions for that period are dropped from training, not labelled as non-clicks, and the daily rebuild records the gap. Losing an hour of one region’s rows costs almost nothing; inventing negatives costs a bad model.
  5. The hourly refresh ships itself. The background path that keeps the model fresh. Twenty-four releases a day cannot each get an A/B test, so a refresh is a chain of automatic gates, a short canary and a rollback that is one write.
    1. Once an hour’s rows are complete, the trainer continues from the serving checkpoint on that hour. One pass over ~140 M rows takes ~25 minutes. New ad ids get embedding rows initialised from their advertiser’s and creative’s rows, not random noise, so a new ad starts near its family. The parent checkpoint and the data hours are recorded as lineage.
    2. It evaluates the candidate on the impressions just after its data, against production on the same rows. Progressive validation: always the future, never a random split. Gates: normalised entropy no worse than production by more than 0.3 %, raw calibration within 0.9 to 1.1 before the map, mean prediction shift under 5 %, and no feature with a null rate outside its band.
    3. The calibration fitter fits maps for the new version on recent rows scored by it. A map belongs to one version: each model is wrong in its own way, and serving a new model with the previous version’s maps is a quiet way to misprice an hour. Version and maps are published as a pair or not at all.
    4. The registry records the version, and scorers pull the delta: changed rows and dense layers, ~7 GB. Hosts download from a regional mirror or from peers, apply the delta to a second copy of the changed rows, and switch a version pointer between requests. The previous version stays loaded for an hour, so a rollback costs nothing to execute.
    5. For 15 minutes, 5 % of requests run the new version while the monitor compares it with the rest. Guardrails: p99 latency and timeouts, mean pCTR against the 95 % on the old version (±3 %), revenue per thousand requests, click rate, and the first calibration ratio once 10-minute labels arrive. Fifteen minutes cannot measure a revenue lift; it can catch a broken push.
    6. The guardrails hold and the registry moves all traffic; one tripped guardrail would have reversed it with a single write. The monitor, not the trainer, makes the call, so a pipeline that builds a bad model cannot also approve it. Rollbacks are counted: more than a couple a day means the gates upstream are too loose.
    7. Meanwhile 1 % of users stay on last week’s frozen model, to measure what freshness buys and to catch drift. Each hourly step passes its own gate, but 168 small steps a week can add up to a slow drift that no gate sees. Comparing the hourly chain with a frozen model over days says how much an hour of freshness is worth in revenue, and whether the chain is quietly getting worse.

Deep dives

Joining a click that arrives later

A click can arrive seconds or an hour after its impression. When do you decide an impression was not clicked, and what does that choice cost?

Every impression needs a label, and a non-click is only known by waiting. Assume, from our own logs, that about 90 % of clicks arrive within a minute of the impression, 98 % within 10 minutes and 99.5 % within an hour; the rest come back hours later from a tab left open. At 700 k impressions a second, each minute of waiting holds 42 M more rows open, and each minute is a minute later that the model learns.

The choice trades three things: freshness (how soon a row reaches the trainer), label accuracy (how many real clicks are recorded as non-clicks, called fake negatives) and state (how much is held while waiting). No single window suits every consumer: the hourly trainer wants rows fast, the weekly retrain and the calibration ratio want them exact. And whatever the window, it must close on evidence that the click stream has caught up, not on the wall clock.

  • Event-time stream join, 10-minute window closed by the click watermark, plus a daily 24-hour rebuild chosen
  • Batch join once a day in the warehouse situational: for the weekly full retrain, and for models whose value does not decay within a day
  • Emit every impression at once as a non-click, and a positive copy when the click comes situational: continuous training at minute freshness, with a loss that corrects for fake negatives, such as the one Twitter published in “Addressing Delayed Feedback for Continuous Training” (RecSys 2019)
  • Close windows on the wall clock rejected

The answer: The joiner is a Flink-class job keyed by impression id, with RocksDB state on local SSD. The served record opens the state (it is written before the page renders); the impression beacon starts a 10-minute event-time timer; a click inside the window sets the label; an invalid-traffic flag inside the window removes it. Timers fire only when the watermark of every click partition, in every region, has passed impression time plus 10 minutes, so a stalled region holds rows rather than closing them. Every click is emitted and 10 % of non-clicks with weight 10, upserted by impression id so a replay rewrites the same row. A daily batch job runs the same join code with a 24-hour window and the nightly invalid-traffic verdicts, for the weekly retrain and to measure the completion factor (24-hour clicks ÷ 10-minute clicks, about 1.02 per placement) that calibration applies. Google described this problem at search-ads scale in its Photon paper (SIGMOD 2013), which joins queries and clicks across data centres exactly once, and Facebook’s 2014 click-prediction paper describes an online joiner with a waiting window for the same reason.

Why 10 minutes and not 1 or 60?

Because of the delay curve and what each extra minute buys. One minute catches ~90 % of clicks, so one positive in ten would be a fake negative, too large a bias to correct cleanly. Sixty minutes catches 99.5 %, but rows reach the trainer an hour later and the join state grows six-fold to ~2.5 TB. Ten minutes is the knee: ~98 % of clicks for ~420 GB of state, and the missing 2 % is a stable, measured factor. I would set it per placement from the measured curve, since a long video ad tends to be clicked later than a feed ad.

What happens to a click that arrives after its window closed?

In the hourly path it is lost: the row was already emitted as a non-click or sampled away. It goes to a late-click side output, and the daily rebuild labels that impression correctly for the weekly retrain. So the hourly model learns “clicked within 10 minutes”, about 2 % below the true rate, and the calibration layer multiplies by the measured completion factor so the auction still sees the true probability.

The joiner crashes and restarts. Do you get duplicate or different rows?

Neither. State and input offsets are checkpointed together, so a restart replays from the last checkpoint and rebuilds the same state. Windows close on event-time watermarks, so the replay makes the same decisions, and rows are upserted by impression id, so a row emitted before the crash is overwritten by an identical one. That is an exactly-once effect on top of at-least-once delivery.

How does this change for conversion prediction?

Conversions, such as a purchase or an install, arrive hours to days later, often through the advertiser’s own reporting. A window long enough to be accurate, say 7 days, would make the model a week old. That is where emitting at once with a delay-corrected loss earns its complexity, or a model that predicts the delay along with the conversion, as Criteo published in 2014 (“Modeling Delayed Feedback in Display Advertising”). The joiner itself barely changes: same key, longer state, kept on disk.

How would you know the joiner is healthy?

Three numbers per region. The join rate: the share of impressions that found their served record and of clicks that found their impression, both near 100 %; a drop means a key or clock problem. The click rate of emitted rows against the same hour last week. And the output watermark lag, how far behind real time the emitted rows are, which is the trainer’s real freshness.

Training rows without leakage

A teammate adds “clicks on this ad today” and offline AUC jumps from 0.78 to 0.80. Online, nothing. What happened, and how should the rows have been built?

The most predictive features in click prediction are counters built from the same click stream that supplies the labels: the ad’s click rate in the last hour, the user’s clicks on this advertiser in 30 days. A training job that rebuilds them by joining a daily table on the date gives each row the whole day’s count, including the label click itself and every click after it. The model learns to read the answer from a feature. Offline metrics jump; in production, where the feature only knows the past, the gain vanishes or turns negative.

Production features avoid this by being logged as served, as the Recommendation System design does. The hard case is the one logging cannot cover: a feature written today has no logged history, and the team wants to train on 30 days of it tomorrow. The key observation is that every feature value has two times: when the events it summarises happened, and when serving could first read it. A daily table about Monday lands at 03:00 on Tuesday, so a request at 01:00 on Tuesday saw Sunday’s table. Point in time means as of the second time, not the first.

  • Logged inputs for production features; backfills by an as-of join on available time from a history with both timestamps chosen
  • As-of join on event time rejected
  • Join daily snapshots by date rejected
  • Recompute features in the training job from raw events, with the streaming job’s code situational: for features computed from the event log alone, by running the streaming job in batch over archived events, as the Fraud Detection design does

The answer: Production training rows are built only from the inputs the scorer logged, and every transform (bucketing, hashing, crosses, defaults for missing values) lives inside the exported model graph, so training and serving run the same code on the same inputs. Every feature pipeline also writes each value to the offline store with event_time and available_at, the moment the online store could serve it. A new feature is backfilled by an as-of join on available_at ≤ request time, never on event time or on the date, and it is logged at serving from the day it ships, before any model uses it. After two weeks the backfilled values are compared with the logged ones for the same requests; a gap is the backfill’s skew and blocks the switch. Two checks run all the time: a replay that re-scores 0.01 % of served requests offline from the log and must match the served raw score to 1e-4, which catches transform skew; and per-feature null rates and distributions online against offline (population stability index), which catch a default or a unit that differs between the two paths.

Why is available time not just event time plus a constant?

Because pipeline lag varies. A streaming counter is usually 20 to 40 seconds behind but falls minutes behind during an incident; a daily table lands at 03:00 on a good day and 09:00 on a bad one. Serving saw whatever was there, lag included. Recording the real available time on every write captures that, and a backfill built from it reproduces the stale reads serving actually made, which is what the model has to cope with.

What other leaks are common in click prediction?

Session features computed at the end of the session, such as “ads clicked this session”, which include the session’s later clicks. Target encodings, such as an advertiser’s historical click rate, computed over a period that overlaps the training rows instead of ending before them. Random train and test splits, which put the same user-hour on both sides. And any feature whose pipeline reads the click stream with a shorter lag offline than online. The defence is the same for all of them: as of available time, and evaluation on a later period than training.

Why put the transforms inside the model graph?

Because the most common skew is not the stored value but what is done to it: a different bucket boundary, log instead of log1p, a missing value as 0 on one path and −1 on the other. If raw inputs are logged and every transform is part of the exported model, there is one implementation, and the replay check proves it. Transforms written twice, once in a SQL training pipeline and once in the serving code, drift apart within months.

The replay check fails for 0.3 % of requests. How do you find the cause?

Compare the failing rows feature by feature between the logged input and the training pipeline’s version of it; skew is almost always one feature. If the inputs match and the scores do not, the model artefacts differ, for example a quantisation step or a different version, which is why the tolerance is 1e-4 and not exact equality. Failures concentrated in one region or one scorer build point at deployment, not data.

Scoring 300 ads in 30 milliseconds

The auction gives you 30 ms to score 300 ads, 500 k times a second. How do you fit a big model into that?

The click model is a deep network over hundreds of sparse ids (user, ad, advertiser, placement, hashed crosses) and a sequence of the user’s last 1,000 interactions. Run whole for each candidate, a GPU scores about 100 k candidates a second, so 150 M a second needs ~1,500 GPUs, and the embedding tables alone are 128 GB, more than one GPU holds. The deadline is a p99, so the slowest feature read and the slowest host count, not the average.

The observation that shapes the answer: within one request the user and the context are the same for all 300 candidates. The expensive half of the network, the one over the user’s history, depends only on the user; only the part that crosses the user with each ad has to run 300 times. The same split decides where memory goes: user-side tables are read once per request, ad-side tables 300 times per request but they are small.

  • One request is one batch: user part once and broadcast, candidates in one GPU pass, ad tables on the GPU, user tables in host RAM chosen
  • Score each candidate as an independent example rejected
  • Two-tower dot product: precomputed ad vectors, one user vector situational: as the pre-ranker that cuts ~5 k eligible ads to 300, which is how the Ad Serving design uses it
  • Embedding tables sharded across separate parameter servers situational: once the tables outgrow host RAM even in int8, roughly ten times today’s size

The answer: The scorer receives one request with 300 ad ids and treats it as one batch. It reads the user’s ~10 KB of features in one multi-get (6 ms cap, hedged at the p95), looks up ~200 user-side ids in host RAM (int8, ~112 GB), and runs the user tower over the last 1,000 interactions once. The ad-side tables (~16 GB) and dense layers sit in GPU memory, so the 300 candidates gather their own embeddings on the GPU and go through the interaction and top layers in one pass. A dynamic batcher may pack 2 or 3 requests into one launch, waiting at most 2 ms. Position is a separate shallow tower, so each ad is scored once at a reference position and multiplied by a per-slot factor. The budget is 6 ms features, 2 ms lookups, 2 ms batching, 10 ms GPU, 1 ms calibration and response, and 9 ms of slack. Large ad platforms have described computing user-side parts once per request and reusing them across candidates; I would not quote their exact numbers.

A scorer host is slow. What does the auction see?

The ad server hedges: if a host has not answered by the scorer’s p95, about 18 ms, it sends the request to a second host and takes the first answer, which costs extra GPU on only ~5 % of requests. A host whose queue stays long is taken out by its health check. If both copies miss the deadline, the auction runs on the pre-ranker’s calibrated scores and the served record is marked as a fallback, so those rows never train the model.

Traffic doubles for an hour and you cannot add GPUs that fast.

Do less per request instead of failing requests. The scorer reports queue time on every response; above a threshold the ad server trims candidates on low-value placements first, 300 to 200 to 100. The tail of the pre-ranked list carries little expected value, so revenue falls far less than the work does. The candidate count goes into the served log, so analysis can tell trimmed auctions from normal ones.

Why int8 for the embeddings but not for the dense layers?

Embedding tables are 99 % of the bytes and each row is used rarely, so row-wise int8, with a scale and offset per row, loses very little and saves 4× over fp32. The dense layers are ~1 GB and touched by every prediction, so quantising them saves little memory and risks more accuracy. Whatever is quantised, the replay check compares served scores with the training-side model, so a quantisation error shows up as skew rather than as a mystery.

Why not run all of this on CPUs?

For a model this size, the interaction layers and the sequence tower are dense matrix work that GPUs do roughly ten times cheaper per score. CPUs fit the light models: the pre-ranker, the fallback, and small markets where a cheaper model is good enough. The user-table lookups do run on the CPU, which is why those tables live in host RAM next to the GPU.

How do 10 M ads’ features reach the GPU without 300 network reads?

Per-ad counters (impressions and clicks per placement over 1 hour and 1 day, ~100 B per ad, ~1 GB in all) are pulled as a versioned snapshot every minute and held on each host, and the ad-side embedding rows already sit in GPU memory. A request carries 300 ids, not 300 feature vectors, and the snapshot version goes into the log blob, so training reconstructs exactly what was used.

Calibrated probabilities, not scores

Your new model has a better AUC and loses 2 % of revenue in the A/B test. How is that possible, and how do you make sure the number multiplied by the bid is a probability?

AUC measures order only: whether clicked ads score above unclicked ones. The auction uses the number itself: value is bid × pCTR, and the price per click is divided by the winner’s pCTR. A model that ranks better but predicts 10 % high on video ads and 10 % low on image ads gives impressions to the wrong ads and charges the wrong prices. Several parts of this pipeline push predictions off on purpose or by necessity: keeping 10 % of non-clicks raises the apparent click rate about ninefold, the 10-minute window misses ~2 % of clicks, an hourly model learns from the last hour’s mix of traffic, and new ads are scored from sparse data.

So calibration is a layer of its own, with its own data, refresh cadence and monitor, rather than something hoped for from the loss. Log loss rewards calibration on the training distribution, and the serving distribution differs by sampling, by window and by hour of day. The layer must be monotone within a segment, so it never reorders ads that share one, and it must be fitted per model version, because each version is wrong in its own way.

  • A monotone map per segment (placement × country group × format), fitted every 30 minutes on recent labelled rows, versioned with the model chosen
  • Trust log loss: a model trained on it is calibrated rejected
  • One global Platt scaling, a logistic fit on the raw score situational: a small platform with a handful of placements, or as the fallback for segments too thin for their own map
  • Correction factors per advertiser rejected

The answer: After the model, the scorer applies an isotonic map, stored as ~20 knots on the logit, chosen by segment: ~40 placements × ~20 country groups × 5 formats, ~4,000 segments. The fitter runs every 30 minutes on the last 6 hours of joined rows scored by the serving version, undoing the 10 % negative sampling with the row weights and multiplying by each placement’s completion factor (~1.02) for clicks the 10-minute window misses. A segment with fewer than ~2,000 clicks in the window falls back to placement × format, then to placement. Maps are versioned with their model and published as a pair; a new model gets maps fitted on held-out rows before it serves any traffic. The monitor measures the calibration ratio, Σ predicted ÷ Σ observed clicks, per segment, on 10-minute labels scaled by the completion factor and confirmed the next day on 24-hour labels, with alerts outside 0.95 to 1.05. It separately tracks how far each map bends from the identity: a correction that grows week by week means the model is drifting and the map is hiding it. Google’s 2013 paper “Ad Click Prediction: a View from the Trenches” describes the same idea, a calibration layer on top of the model to correct systematic bias.

Why not refit the maps every minute?

Because a map fitted on a few minutes of data fits noise: a segment with 2,000 clicks in six hours has about 5 in a minute. Every 30 minutes over a 6-hour window balances freshness against variance. The fast-moving part of click rates, a new ad or a live event, is the job of the model and the counters; calibration corrects systematic bias, which moves slowly unless something breaks, and breakage is the monitor’s job.

A brand-new ad format launches. How is it calibrated on day one?

It has no segment of its own yet, so it falls back to its placement’s map, and the monitor tracks its ratio from the first hour. Until it has ~2,000 clicks it keeps the parent map, and the launch caps its share of auctions so a 20 % miscalibration costs little. Once it has data it gets its own map and its own line on the dashboard.

The maps reorder ads across segments. Is that a problem?

It is the point. Two ads in one auction can sit in different segments, a video and an image ad competing for the same slot, and if the model overpredicts video by 8 %, the map lowers video against image, which is exactly the correction that makes the auction fair. Within a segment the map is monotone, so the model’s ranking there is kept. What the map must not do is absorb a bias the model should learn, which is why its size is monitored.

How does calibration interact with exploration for new ads?

A new ad’s prediction rests on its advertiser and creative features and is less certain, and a map corrects the average of such ads, not each one. That is fine for pricing in aggregate but can starve a good new ad, which is why the Ad Serving design gives new ads a small exploration slice. Rows from those auctions carry their propensities, so the fitter and the trainer weight them correctly instead of treating explored impressions as ordinary ones.

Hourly, daily or continuous training

How often should the model be retrained, and why not just train it continuously on the click stream?

Click rates move fast: 10 M ads with thousands created every hour, campaigns launched in the morning, a live event that changes what people click for an evening. A model trained yesterday has never seen today’s new ad ids. Facebook’s 2014 click-prediction paper found prediction quality falling steadily as training data aged, which is why its pipeline retrained daily and updated part of the model online. But every refresh is a release that can misprice every auction, and the model is 128 GB.

Two things make frequent refresh affordable. Warm starting: an hourly job continues from the serving checkpoint on one hour of rows instead of retraining on 30 days. And deltas: in an hour only ~100 M of 2 B embedding rows change, so a refresh is ~7 GB, not 130 GB. What has to be designed is how many small, automatic releases stay safe, and how drift across hundreds of them is caught.

  • Hourly warm-start refresh with delta pushes, a weekly full retrain, and minute-fresh counters as features chosen
  • Daily full retrain situational: early on, or for a slower model such as conversion prediction, whose labels take days anyway
  • Continuous online training, syncing changed rows to serving every minute situational: when most value is in very new items, as ByteDance describes in its Monolith paper (2022), with strong data validation in front of the trainer
  • Retrain only when metrics degrade rejected

The answer: About 10 minutes after the hour ends, once the last of its 10-minute windows has closed, the trainer warm-starts from the serving checkpoint and makes one pass over that hour’s ~140 M rows, in ~25 minutes. New ids get embedding rows initialised from their advertiser’s and creative’s rows. It evaluates on the next 10 minutes of impressions against the production model on the same rows (progressive validation) and publishes only the changed rows and the dense layers. Weekly, a full retrain from scratch on 30 days (~100 TB) produces a new base that goes through shadow, canary and A/B like any new model, and the hourly chain then continues from it. Fast-moving signals live in features, not weights: ad and user counters are under 30 seconds old, so a new ad’s own click rate starts counting minutes after launch. A 1 % holdback on last week’s frozen model measures what the hourly chain is worth and whether it drifts.

How do you know hourly is worth it over daily?

Measure it instead of assuming it. The 1 % holdback on a frozen weekly model gives the decay curve directly: normalised entropy and revenue per thousand requests against the hourly chain, by the frozen model’s age. If the gap at 24 hours is a tiny fraction of revenue, daily is enough and the hourly machinery is not worth its risk. At this platform’s scale even a fraction of a percent is a lot of money, which is usually why hourly wins.

Someone runs a click-bombing attack on one ad. What does the hourly model learn?

Ideally nothing, because the click aggregator flags the bot clicks and the joiner drops them inside the window. If the flags are late, the hour’s rows show a wild click rate for one ad and placement. A validation step before training compares each ad’s and segment’s click rate with its recent history and quarantines outliers, and the evaluation gate catches a candidate whose predictions shift. The daily rebuild corrects the labels for the weekly retrain.

What does warm starting cost you?

Path dependence. A warm-started model is the sum of every hour’s updates and can drift slowly: rows for users who stopped appearing never update, optimiser state goes stale, one bad hour leaves a trace. The weekly full retrain resets that. At each weekly switch the fresh model is compared with the hourly chain; if the fresh one is not at least as good, something in the chain went wrong.

How does a 7 GB delta reach 120 hosts without disturbing scoring?

Each host downloads it in the background from a regional mirror or from peers, writes the changed rows and dense layers into a second copy of just those parts, and switches a version pointer between requests. The cost is memory headroom for a second copy of the changed part, not of the whole model. The previous version stays addressable for an hour, so the registry can roll back with one write.

Shipping a new model safely

A new architecture beats production by 1 % normalised entropy offline. Take me from there to 100 % of traffic.

Offline wins in click prediction often shrink or vanish online: the offline set is what the old model chose to show, prices react to the new predictions, pacing and budgets react to prices, and a feature that looked fine in a backfill may be skewed at serving. And unlike a feed change, a bad model here is a billing incident, because every auction it touches is priced from its numbers.

So each stage of a rollout answers a question the previous one could not, at the lowest cost that answers it. Offline evaluation asks whether it predicts better on logged data; shadow asks whether it behaves the same on live inputs; a canary asks whether it is safe to let it decide; the A/B test asks whether it is better for revenue, advertisers and users. Routine hourly refreshes are a different case: they change weights, not behaviour, and cannot each wait for an A/B test.

  • Offline replay, shadow on 10 % of requests, a 1 % canary with automatic guardrails, a budget-split A/B test, then a ramp with a holdback chosen
  • Straight to an A/B test rejected
  • Offline metrics only rejected
  • Interleaving both models within one request situational: for ranking-only changes in organic feeds or search, never for a model that prices auctions

The answer: Offline: normalised entropy, calibration and AUC per segment on two weeks of rows from a later period than training, plus a replay of logged auctions to estimate revenue per thousand requests. Shadow: the new model scores 10 % of live requests after the auction already has its answer, with outputs logged and never used, for 2 to 3 days; that checks p99 latency on real inputs, the prediction distribution, calibration as labels arrive, and the replay check against its own training pipeline. Canary: 1 % of requests for a day, with guardrails that roll back automatically within minutes: p99 latency and timeouts, mean pCTR against control, calibration ratio within 0.95 to 1.05, revenue per thousand requests, click rate, and cost per click for large advertisers. A/B: 5 % for 1 to 2 weeks with each campaign’s budget split between arms (the Ad Serving design explains why), judged on revenue, advertiser value (conversions per dollar, which keeps budgets coming) and user signals such as ad hides and session time. Then a ramp to 100 %, keeping a 1 % holdback for a few weeks to watch long-term effects. Hourly refreshes skip shadow and the A/B test: they pass offline gates, then a 15-minute canary on 5 % with the same guardrails.

Shadow scoring costs GPUs. Is it worth it?

On a slice, yes, which is why it is 10 % of requests: about 30 extra GPUs for three days is cheap next to a pricing incident. Shadow is the only stage that tests the model on exactly the live inputs with nothing at stake, and it is where feature skew, a slow new layer, or maps fitted for the wrong version show up. Running it after the auction has its answer means it can never slow a real request.

Which guardrail fires most often, and is it usually real?

Mean pCTR against control, because any feature or calibration mistake moves it at once, long before revenue can be measured. It is noisy on a small canary, so it uses a band, say ±3 %, and a minimum duration before it trips. A real problem is a sustained shift that the calibration ratio confirms once labels arrive 10 to 20 minutes later; a blip that reverses is not.

The A/B shows +1.5 % revenue and −2 % advertiser conversions per dollar. Ship it?

Not as it is. More revenue with worse results per dollar usually means the model raised prices or sent impressions where they convert less, and advertisers adjust: they lower bids or move budget elsewhere, so the gain decays over weeks. I would find the segments that lose advertiser value and check whether calibration shifted there, and if the trade-off is real, decide it explicitly with the business rather than let a short test decide it.

Why do hourly refreshes skip the A/B test?

Because they change weights, not the design: same architecture, same features, one more hour of data. Their risks are a bad hour of data or a broken push, which offline gates and a 15-minute canary catch. An A/B test per hour would never finish, since revenue needs days to measure. The holdback on a frozen weekly model is the long-run check that the hourly chain as a whole is helping.

The theory behind it

  • Feature stores and serving machine learning models: The infrastructure behind production machine learning: offline and online feature stores, training-serving skew, point-in-time correct training data, real-time features from streams, model serving with latency budgets, batching, shadow and canary deployments, and monitoring drift.
  • Windowing, event time and watermarks: Aggregating streams correctly: event time versus processing time, tumbling, sliding and session windows, late and out-of-order events, watermarks and allowed lateness, triggers and updates, state size, and stream joins.
  • Ad serving and real-time auctions: How an ad system picks and serves an ad in under 100 ms: targeting and candidate retrieval, click prediction, auctions and pricing, budgets and pacing, frequency caps, impression and click tracking, fraud filtering and billing-grade counting.

Related

Sit this question with an AI interviewerOr watch a sample interviewStart an AI mockPractice with AI