Build a Real-Time Ad Decision Service with Spend Controls
System DesignModel answerLast updated
Design a backend that picks one ad per page slot within a strict latency limit, logs views and clicks for billing, and keeps campaign spend within budget and spread across the day.
Problem
You are asked to design the serving backend for an advertising platform. Each time a web page or app screen with an ad slot loads, the client calls your service. Your service must choose an ad, return it quickly enough that the page is not slowed down, and record what was displayed and clicked so advertisers can be billed and budgets respected.
Assumptions
- Advertisers set up campaigns with targeting rules (such as location, device type, placement and audience segments), a bid, a daily budget and a run schedule. Campaign management tooling already exists. You are designing the serving side.
- Each ad request describes the slot (placement and size) and its context (site or app, device, coarse location, and a user or session ID when consent was given).
- The service returns at most one ad per slot, or no ad, within a tight latency budget because the page is waiting.
- Impressions and clicks are tracked for billing and reporting. Spend must not run far beyond a campaign's budget.
- External real-time bidding exchanges and training the click-prediction model are out of scope unless raised by the interviewer.
Questions you might ask first
- Is billing per impression, per click, or both?
- What is the latency budget, and what happens when it is missed?
- How many requests per second, active ads and advertisers?
- How strict is budget enforcement, and who absorbs a small overspend?
- Are frequency caps required?
Part 1: Selecting and returning an ad
Describe the APIs, data model and main components. Walk through the path from the arrival of a request to the response: finding eligible ads, ranking them, choosing a winner and its price, and returning the creative. Explain how campaign edits made by advertisers reach the serving machines.
Cover:
- Request and response APIs, including tracking links in the response
- Candidate retrieval from a targeting index, then filtering and ranking by expected value
- The auction and pricing rule, and a fallback when nothing qualifies
- Propagation of campaign changes and how stale serving data may be
Part 2: Tracking, budgets and pacing
Explain how impressions and clicks are captured, deduplicated and converted into spend. Describe how that spend is fed back so a campaign stops before overspending, and how a daily budget is spread across the day rather than used up in the first hour.
Cover:
- Durable event logging, signed tracking links and deduplication
- Real-time spend aggregation versus exact billing from the event log
- Budget enforcement across many servers, and the overspend you tolerate
- Pacing across the day
Hints
Hint 1
Split the system into two paths: a synchronous decision path that must finish in tens of milliseconds, and an asynchronous event path that can lag by seconds. Keep anything slow or heavy off the first path.
Hint 2
Ranking by bid alone is wrong. Think about expected revenue per impression (for example bid times predicted click probability for pay-per-click ads), and consider what price the winner should pay.
Hint 3
Budget counts will always be slightly stale when many servers serve in parallel. Design for bounded overspend: for example, give each server a small allowance of budget, and throttle serving probability so spend follows a target curve across the day.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and scale
Functional: accept an ad request, return at most one ad per slot, track impressions and clicks, enforce budgets, pace spend, and apply targeting.
Non-functional: the decision path is latency-critical (assume p99 under about 50 ms server-side, with the client timing out near 100-150 ms). Availability matters more than perfect accuracy: a failed ad call should degrade to "no ad" or a default ad, never a broken page. Assume around 100k requests per second at peak, a few million active ads, and an event stream roughly 1-2x the request rate (impressions plus a small fraction of clicks).
Assumed billing: cost per click (CPC) with optional per-impression (CPM) campaigns. Small overspend (about 1-2% of daily budget) is acceptable, and the platform absorbs it as "make-good" rather than charging the advertiser.
2. Architecture overview
Two paths:
- Decision path (synchronous): edge/load balancer, ad server fleet, in-memory targeting index and campaign state, feature lookups, ranking, response.
- Event path (asynchronous): tracking endpoints, a durable log (Kafka-style), stream processors for near-real-time spend, a batch job for exact billing, and a store feeding reports.
A third, control path, carries campaign changes from the management system to the servers.
3. Part 1: Decision path
API. GET /ad?placement=...&size=...&device=...&geo=...&uid=... returns:
{ "ad_id": "a123", "creative_url": "...", "impression_url": "https://t.example/i?tok=...", "click_url": "https://t.example/c?tok=..." }
The tokens are signed (HMAC) and encode ad ID, campaign ID, request ID, price charged and expiry. This stops forged clicks, lets the tracker be stateless, and carries the auction price so billing needs no lookup back into serving.
Data model (serving view). Campaign: id, advertiser, targeting rules, bid, daily budget, schedule, status. Creative: id, size, asset URL. These are held in memory on each ad server, so the request path makes no database call.
Retrieval. Build an inverted index from targeting attributes (placement, geo, device, segment) to campaign lists. A request intersects the posting lists for its attributes, reducing millions of ads to a few hundred candidates. Then filter: schedule active, budget not exhausted, creative matches slot size, frequency cap not hit (a per-user counter in a fast key-value store such as Redis, queried only for the survivors, in one batched call).
Ranking. Score by expected value per impression, for example bid × pCTR for CPC. The pCTR comes from a model served locally or by a low-latency feature service, with a default prior when features are missing. Keep the top few candidates.
Auction and price. A second-price (or generalized second-price) rule: the winner pays just enough to beat the runner-up's score. This encourages truthful bidding and is easy to explain. Enforce a reserve price. If nothing clears the reserve or no candidate survives filtering, return a fallback: a house ad, a lower-quality backfill, or an empty response that tells the client to collapse the slot.
Campaign change propagation. Edits go to the campaign database, which emits change events to a log. Each ad server subscribes (or polls snapshots) and applies updates to its in-memory index, typically within seconds. Pausing a campaign is treated as higher priority than a bid edit. Staleness of a few seconds is acceptable; the rare impression served after a pause is covered by the budget and billing checks downstream. New servers boot from a periodic full snapshot plus the log tail.
Latency tactics: in-memory indexes, batched feature lookups, a hard per-stage time budget (for example 5 ms retrieval, 10 ms features, 10 ms ranking), early cutoff returning the best result so far, and caching of the user's segments.
4. Part 2: Tracking, budgets, pacing
Event capture. The impression beacon and click redirect hit a lightweight tracker. It verifies the signature and expiry, writes the event to the durable log (partitioned by campaign ID), and, for clicks, responds with a 302 to the advertiser's landing page. Writing to the log before acknowledging avoids losing billable events.
Deduplication. Each token has a unique request ID. Dedup on (request_id, event_type) using a short-TTL set in the stream processor and again in the batch job. This handles browser retries, double-clicks and bots replaying a link. Filter obviously invalid traffic (known bot ranges, impossible click-to-impression gaps) before billing.
Two levels of spend accounting.
- Near-real-time: a stream processor aggregates spend per campaign in a sliding window and writes counters to a fast store. Servers use these for budget decisions. These numbers are approximate and a few seconds behind.
- Exact billing: a batch or reconciliation job recomputes spend from the full deduplicated log, and its result is what the advertiser is invoiced for and what reports show. The two reconcile; drift is corrected.
Budget enforcement across many servers. Because counters lag, servers can collectively overshoot. Common solutions:
- Budget slices: a central allocator hands each server a small lease of budget (say 1% of remaining). The server spends against its lease and requests more when low. The worst-case overspend is bounded by the leases outstanding.
- Soft-stop threshold: begin throttling when spend reaches, for example, 95% of budget, to reduce the tail risk.
- Charge against the price in the token, not a re-computed one, so accounting matches the auction.
Pacing. Without pacing, a high-bidding campaign drains its budget in the morning. Define a target spend curve (flat, or shaped by the historical traffic profile). Every minute, compare actual spend to the target and adjust a serving probability for the campaign: if ahead of plan, lower it; if behind, raise it (capped at 1). The candidate passes through a random gate with that probability before auction. This is a simple feedback controller; add smoothing to avoid oscillation.
5. Failure handling
- Feature or frequency-cap store slow or down: use defaults and skip the cap rather than block; accept slight over-delivery.
- Event pipeline lag: the log buffers; budgets run on slightly stale counts, so rely on leases and the soft stop.
- Tracker down: clients retry with the same token; dedup makes this safe.
- Bad config push: version snapshots, canary a subset of servers, and allow rollback.
- Multi-region: serve from the nearest region, replicate campaign data to all, and keep budget allocation in a home region with regional leases.
6. Observability
Track fill rate, p50/p99 per stage, timeout rate, spend versus plan per campaign, pipeline lag, dedup rate, and the gap between real-time and billed spend. Alert on sudden fill-rate drops.
7. Trade-offs and common mistakes
- Ranking by raw bid instead of expected value, which lowers revenue and user relevance.
- Calling a database in the request path, which breaks latency.
- Treating the real-time counter as the billing source of truth.
- Ignoring duplicate and fraudulent clicks.
- Demanding exact budget enforcement, which would require global locking and hurt latency; a bounded, stated overspend is the pragmatic choice.
- Forgetting a fallback, so the page waits or errors when no ad qualifies.