ML-Driven Budget Pacing System for Programmatic Advertising
Machine LearningModel answerLast updated
Design an end-to-end system that forecasts ad inventory and prices, dynamically paces campaign spend, and enforces hard budget caps across hundreds of thousands of concurrent campaigns.
Context
An advertising platform serves hundreds of thousands of active campaigns each day. Advertisers set a daily or lifetime budget and choose a bidding objective — for example, a target cost-per-acquisition (CPA), a target cost-per-click (CPC), or maximum reach. The platform participates in auctions on their behalf.
Without deliberate pacing, campaigns tend to exhaust their budgets in early-morning traffic surges when competition is low and inventory is cheap — but those impressions may be far less valuable than those available at peak hours. At the same time, pacing that is too conservative causes under-delivery, which means the advertiser does not get what they paid for.
Your task is to design a complete ML-based forecasting and budget pacing system that:
- smooths spend across the day relative to where the highest-value impressions are;
- adapts in near-real-time as actual spend diverges from the plan;
- provides a hard, deterministic guarantee that no advertiser is ever billed above their budget, regardless of model errors or infrastructure lag.
Scale
- 500,000 active campaigns per day
- 5 billion auction opportunities per day (~60,000 QPS average, 150,000 QPS peak)
- Pacing decisions must complete within 5 ms p99 on the live auction path
- Pacing parameters must refresh every 1–5 minutes based on live spend
What to Cover
Structure your answer around these five areas:
-
Architecture: How do the offline training pipeline, the near-real-time pacing control loop, and the live auction path relate to each other? What is the data flow and where does state live?
-
ML Formulation: How do you forecast 24-hour inventory supply and clearing-price distributions per audience segment? What features do you use, what model architecture, and what loss function? How does the forecast feed into a pacing controller — specifically, what optimization framework governs the bid multiplier or throttle probability?
-
Hard Budget Enforcement: Design a mechanism that makes budget overrun structurally impossible, independent of ML correctness. Walk through exactly how a campaign gets cut off when it approaches its limit.
-
Training Data and Delayed Feedback: Ad conversions can arrive minutes to days after the auction. How do you build training sets without leaking future information, and how do you handle labels that have not yet arrived at training time?
-
Experimentation and Monitoring: Pacing arms share the same auction marketplace, which breaks the standard A/B testing assumption of independent units. How do you run valid experiments? What metrics and drift signals do you monitor in production?
Hints
Hint 1
Start by separating concerns: ML controls *how* budget is spent (bid shaping), while a deterministic leasing layer controls *whether* a bid can proceed. These two paths should never share a code path at auction time.
Hint 2
For the pacing controller, think about the Lagrangian dual of a budget-constrained value-maximization problem. The optimal bid is proportional to value divided by (1 + λ), where λ is a per-campaign multiplier you update via gradient descent on the spend error.
Hint 3
Delayed conversion feedback means your training labels arrive after the fact. The standard fix is to close training partitions only after a fixed observation window has elapsed, and to use importance weighting or a survival model to handle examples whose label has not yet fully materialized.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scoping and Key Constraints
Before designing anything, fix the numbers and clarify the "zero overrun" contract.
At 60k QPS average and 500k campaigns, each ad server handles thousands of pacing lookups per second. Any pacing state lookup that crosses a network boundary would blow the 5 ms budget before scoring even starts. That immediately implies pacing state must live in local process memory on each ad server, refreshed by a push broadcast rather than pulled on demand.
The "zero overrun" guarantee usually means the advertiser is never billed above budget. The platform may physically win a handful of extra auctions during the milliseconds between a kill signal and propagation — but those impressions can be absorbed as platform cost. This framing matters: it means the hard constraint is on billing, not on auction wins.
500k campaigns × ~200 bytes of pacing state (multiplier, throttle probability, planned curve, version) is about 100 MB — comfortably fits in memory on any modern ad server. A full snapshot broadcast every 60 seconds is feasible.
2. Three-Loop Architecture
The system has three loops operating at different timescales.
Offline loop (hourly or daily): Forecasting models are trained on historical auction logs using point-in-time feature snapshots. They output 24-hour supply and price forecasts per audience segment in 15-minute buckets. These forecasts are converted into a planned spend curve for each campaign — essentially a target fraction of the budget per bucket, weighted by forecast inventory volume and expected impression value.
Nearline control loop (every 1–5 minutes): A stream-processing job (e.g., Flink) consumes the spend event stream from Kafka. Per campaign, it compares actual cumulative spend against the planned curve, computes the error, and updates the bid multiplier λ and throttle probability. It writes a versioned snapshot that is pushed to all ad servers.
Online auction path (< 5 ms): Campaign eligibility filtering runs first, then the deterministic budget gate (local lease check), then ML scoring (pCTR, pConv), then bid computation using the in-memory multiplier, then an optional throttle coin flip, then submission to the auction. The budget gate is entirely independent of ML — it is a fast memory read against a locally held lease.
Data flows one direction: offline informs nearline initial state; nearline pushes state updates to online; online emits spend events back to the nearline loop and to the billing ledger.
3. ML Formulation
Forecasting supply and price
Forecast targets per (segment, 15-min bucket):
- impression volume, as P10/P50/P90 quantiles
- clearing-price distribution, which gives a win-rate curve w(b) = P(win | bid b)
Features: hour-of-day and day-of-week cyclical encodings, lagged volumes (t−1h, t−24h, t−7d), segment attributes (geo, industry, job function), count and aggregate budget of competing campaigns, and recent clearing-price quantiles.
Start with gradient-boosted trees trained with pinball (quantile) loss for the volume quantiles and price percentiles. The quantile output is important because the pacing controller needs to know how uncertain the forecast is before committing budget. For datasets with strong multi-day seasonality or trend, upgrade to a sequence model like Temporal Fusion Transformer or DeepAR with a negative-binomial likelihood for count data.
Pacing as constrained optimization
The formal problem is: maximize Σ value_i · x_i subject to Σ cost_i · x_i ≤ B and x_i ∈ {0,1}. The Lagrangian relaxation of the budget constraint gives an optimal bid of bid = value / (1 + λ), where λ is a single per-campaign dual variable. This means one multiplier fully parameterizes the optimal policy — a clean result that drives the controller design.
The forecast sets λ₀ by solving this against the predicted price landscape. The nearline loop then corrects for forecast error using dual gradient descent:
λ ← max(0, λ + η · (actual_spend_rate − target_spend_rate) / target_spend_rate)
Clamp per-step changes (e.g., ±20%) to prevent instability during sudden traffic shifts. A PID controller with integral anti-windup is a practical alternative and is easier to tune for different campaign types.
For maximum-delivery campaigns where there is no value signal to shade bids on, use throttle probability p instead of a multiplier — randomly skip p fraction of auctions uniformly.
4. Deterministic Budget Enforcement
The budget gate must be structurally decoupled from ML. Here is the mechanism:
Budget leasing: Ad servers request a short-lived lease from a sharded, strongly consistent store (Redis Cluster keyed by campaign_id, or a purpose-built atomic counter). Each lease covers a small slice of remaining budget — roughly min(1% of remaining budget, 30 seconds of expected spend). An auction bid proceeds only if the server holds a lease large enough to cover the maximum possible charge. Leases count as committed spend from the moment they are granted, so outstanding leases are never ignored.
Kill switch: When committed_spend + outstanding_leases ≥ budget − ε, the ledger stops granting new leases and publishes a removal event to the eligibility index. All ad servers drop the campaign from consideration within one broadcast cycle — typically under 100 ms. This path has zero dependency on the nearline loop or any ML component.
Billing clamp: Conversion events or clicks that arrive late and would push spend past budget are recorded in the audit log but billed at min(charge, remaining_budget). This is what makes the guarantee hold even when attribution arrives days after the auction. All charge operations are idempotent on event_id to prevent double-billing on retries.
This three-part approach — lease, kill, clamp — means overrun is bounded by the size of outstanding leases, which are sized to be small and tracked as committed.
5. Training Data and Delayed Feedback
The core discipline is point-in-time correctness: training features must reflect only what was observable at the time of the auction, never recomputed from later data.
Implement this by logging the exact feature vector served at each auction, and joining labels to that snapshot rather than to the campaign's current state. Training partitions for a given day are only closed after an observation window W has elapsed (e.g., 1 hour for clicks, 7 days for post-click conversions).
For fresher models that cannot wait for the full window, two approaches handle not-yet-converted examples:
- Importance weighting (fake-negative correction): examples with elapsed time t < W are weighted by the probability they will eventually convert, estimated from the empirical conversion delay distribution. Unconverted examples are treated as negatives with downweighted loss.
- Survival modeling: model the joint probability of converting and the delay, then integrate out the unobserved delay at serving time.
Backtesting forecasting models uses rolling-origin evaluation — train on data up to time t, evaluate on t to t+24h, advance the origin — never a random split, which would leak future auction dynamics.
6. Experimentation and Monitoring
Experimentation: Standard user-level A/B splits violate the stable unit treatment value assumption (SUTVA) here because pacing arms bid against each other in the same auction. Shifting budget from a control campaign to a treatment campaign directly changes the control arm's win rate.
Practical fixes:
- Campaign-level randomization with budget matching: assign whole campaigns to arms, then match on budget size, objective type, and target segment overlap to reduce confounding.
- Time-based holdout: run control and treatment on alternating time windows (e.g., odd vs. even hours). Seasonal confounding is the main risk; mitigate with a pre-period baseline.
- Counterfactual logging (off-policy evaluation): log the counterfactual bid and outcome for all eligible campaigns regardless of which arm they are in, then use inverse propensity scoring to estimate arm performance without live traffic split.
Monitoring signals:
- Forecast quality: MAPE and P90 coverage vs. actuals per segment, tracked hourly
- Feature drift: PSI or KS test on clearing prices and volume — sudden shifts indicate auction market changes (competitors launching campaigns, time-zone effects)
- Controller saturation: fraction of campaigns with λ pinned at its lower or upper bound, which indicates the controller cannot correct fast enough
- Delivery quality: fraction of campaigns that exhaust budget before 6pm (over-pacing) and fraction that under-deliver by end of day
- Lease rejection rate: spikes indicate the budget store is under-provisioned or a latency regression in the grant path
Common mistakes to avoid: training on shuffled data without time-ordering (leaks future into past features); setting lease sizes too large (increases overrun bound); using a single global PID gain across all campaign sizes (small campaigns need tighter gains); and forgetting to account for outstanding leases when computing remaining budget, which causes a race condition that allows overrun.