Ad serving platform with experiment assignment and tracking
System DesignModel answerLast updated
Build a system that delivers targeted ads with low latency, tracks engagement events, and supports deterministic A/B test assignment and analysis.
You're designing a platform that serves advertisements to users and supports running controlled experiments on ranking logic and creative variations.
What the system does
When a user opens an app or webpage, the client requests an ad for a specific slot (e.g., a banner at the top of the screen). Your system selects an appropriate ad from available inventory and returns metadata the client uses to display it. Users may then see the ad (impression) or interact with it (click), and those events must be captured for reporting and billing.
What you need to support
Core functionality
- Store and manage ad campaigns and their associated creatives (images, videos, etc.)
- Target ads based on attributes like geography, device type, app section, and optionally user interests
- Choose which ad to show for each incoming request
- Record impressions (ad was displayed) and clicks (user interacted)
- Enforce at least one delivery rule: budget limits with spend pacing, per-user frequency caps to avoid showing the same ad too often, or deduplication of events
Experimentation
- Run tests that modify selection algorithms or swap in different creatives
- Assign users to experiment groups in a stable, repeatable way
- Capture which experiments and variants each user saw
- Compute metrics like click-through rate per variant for analysis
Performance and reliability
- Respond to ad requests in tens of milliseconds (p99 target around 50 ms for the decision, not including asset download from CDN)
- Handle high request volume (assume millions to tens of millions of requests per day, with peak traffic 5–10× the average)
- Stay available even when parts of the system fail
- Clarify which data must be real-time versus eventually consistent (e.g., dashboards can lag by minutes, but budget enforcement needs to be current within seconds)
What to cover in your design
- Architecture overview: main services and how they interact
- Data modeling: how you store campaigns, targeting rules, and event logs; which databases or storage systems you choose and why
- Request flow: step-by-step path from client request to ad selection to response, including any caching strategies
- Event pipeline: how impression and click events flow through the system, get deduplicated, and land in reporting stores
- Experiment infrastructure: how assignment works, how you log exposures, how metrics are computed, and what safety mechanisms (guardrails) you'd include
- Trade-offs and failure handling: key decisions you made, what breaks under load or partial failure, and how you'd mitigate it
Assume you're not building a real-time bidding exchange with external demand partners—keep the scope to an internal ad server with a known set of campaigns.
Hints
Hint 1
Start by estimating request and event volumes in queries per second and daily storage to anchor your choices
Hint 2
Keep the ad catalog (campaigns and targeting rules) small enough to fit in memory on each server—this is the key to hitting latency goals
Hint 3
Use deterministic hashing on a stable user identifier for experiment assignment so the same user always sees the same variant without requiring a lookup
Hint 4
Separate real-time enforcement (frequency caps, budget checks) from batch analytics (billing reconciliation, final experiment reports) to balance accuracy and speed
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The central challenge is balancing low latency (ad selection must happen in milliseconds) with high accuracy (events must be deduplicated, budgets enforced, and experiments correctly attributed). The solution relies on in-memory serving, asynchronous event processing, and deterministic experiment assignment.
1. Scope and scale estimates
Before designing, pin down the numbers:
- Request rate: 100M requests/day ≈ 1,200 QPS average. Peak traffic (evenings, big events) can hit 10× average, so design for 12–15K QPS sustained with burst capacity to 50K.
- Event volume: Assume 70% of requests result in an ad being shown (70M impressions/day). With a 1% click-through rate, that's 700K clicks/day. At 500 bytes per event, raw logs are roughly 40 GB/day.
- Catalog size: Thousands of active campaigns, tens of thousands of creatives. This fits comfortably in a few GB of memory, which is crucial—it means every ad server can hold the entire eligible inventory locally.
- Latency tiers:
- Serving path: p99 < 50 ms for the decision (creative assets load separately from CDN)
- Spend and frequency updates: seconds (to prevent overspend or ad fatigue)
- Dashboards: minutes (acceptable lag for monitoring)
- Billing and final experiment analysis: daily batch processing (exact, deduplicated)
2. High-level architecture
┌─────────┐
│ Client │────GET /ad?placement=banner&country=US&device=ios&uid=...
└─────────┘
│
▼
┌──────────────────────────────────────────────────────────────┐
│ Load Balancer (multi-region, geoDNS) │
└──────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────┐
│ Ad Server Cluster (stateless, 100+ replicas) │
│ • In-memory ad index (placement → country → device → ads) │
│ • Experiment config (local, versioned) │
│ • Calls: frequency store (Redis), budget service (gRPC) │
└──────────────────────────────────────────────────────────────┘
│
│ (async logging)
▼
┌──────────────────────────────────────────────────────────────┐
│ Kafka (ad_requests, impressions, clicks topics) │
└──────────────────────────────────────────────────────────────┘
│
├──▶ Stream Processor (Flink)
│ • Deduplicate on impression_id
│ • Update frequency counters (Redis)
│ • Aggregate spend → Budget Service
│ • Emit minute-level metrics → OLAP (Druid/ClickHouse)
│
└──▶ Data Lake (S3, Parquet partitioned by date/hour)
→ Batch jobs (Spark daily): billing, experiment analysis
┌──────────────────────────────────────────────────────────────┐
│ Campaign Management API (CRUD on campaigns/creatives) │
│ Postgres (source of truth) → CDC → Index Builder │
│ → Versioned snapshot → Ad Servers pull every 30–60s │
└──────────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────────┐
│ Budget Service (tracks spend per campaign, enforces limits)│
│ Receives spend updates from stream processor │
└──────────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────────┐
│ CDN (serves creative images/videos, not in serving path) │
└──────────────────────────────────────────────────────────────┘
3. Data model
Postgres (source of truth for configuration):
campaigns: id, advertiser_id, status, start_date, end_date, daily_budget_usd, total_budget_usd, bid_cpm, priority, frequency_cap_per_user_per_daycreatives: id, campaign_id, format (banner/video), cdn_url, width, height, statustargeting_rules: campaign_id, dimension (country/device/placement/segment), values (array)experiments: id, layer_id, salt, traffic_percentage, status, start_date, end_date, primary_metric, guardrail_metricsexperiment_variants: experiment_id, variant_name, allocation_percentage, config_json (e.g.,{"ranker": "ctr_model_v2"}or{"creative_swap": 12345})
Derived serving state (in-memory on ad servers):
- Inverted index: nested map structure
{placement: {country: {device: [creative_ids]}}}for fast candidate retrieval. Rebuilt from Postgres via CDC and shipped as a versioned snapshot file. - Experiment config: list of active experiments with their layer, salt, bucket ranges, and variant configurations. Also versioned and pulled periodically.
Redis (real-time counters):
- Frequency caps:
freq:{uid}:{campaign_id}:{date}→ count, TTL 24 hours - Optionally: short-term user segment cache
Budget service state:
- Per-campaign spend tracking, updated from the event stream. Each ad server pulls a small "token allotment" for local pacing checks without a network call on every request.
Event storage:
- Kafka topics for raw events (retained 7 days)
- Data lake (S3 + Parquet) for long-term storage and batch processing
- OLAP database (Druid or ClickHouse) for minute-granularity dashboards
4. Serving path (request to response)
Each ad server handles a request in these steps:
-
Parse request (1–2 ms): extract placement, country, device, user ID, app version. Optionally look up user segments from a local cache or fast KV store (5 ms timeout).
-
Assign experiments (<1 ms): For each active experiment layer, compute
bucket = hash(uid + layer_salt) % 10000. If the bucket falls in an experiment's range, assign the user to a variant. This is purely local, no network call. Record assignments for logging. -
Retrieve candidates (1–2 ms): Query the in-memory index for creatives matching placement, country, device. Filter by campaign status, flight dates, and targeting rules (segments). Typically yields 10–100 candidates.
-
Apply delivery controls (5–10 ms):
- Frequency cap: Batch fetch
MGET freq:{uid}:{campaign_id}:{today}from Redis for all candidate campaigns. Drop any at or over their cap. - Budget check: Use local token allotment per campaign (refilled every few seconds by the budget service). Skip campaigns with zero tokens.
- Frequency cap: Batch fetch
-
Rank candidates (2–5 ms): Default scoring is
bid × predicted_CTR × pacing_multiplier. The ranking function is a pluggable strategy, selected by the experiment variant. For example, variant A uses a simple CTR model, variant B uses a neural ranker. -
Select and respond (1 ms): Pick the top-scoring ad. Generate a signed token encoding
{impression_id (UUID), campaign_id, creative_id, uid, timestamp, experiment_assignments}using HMAC. Return creative metadata and tracking URLs:{"ad_id": ..., "creative_url": "https://cdn/...", "impression_url": "/track/imp?token=...", "click_url": "/track/click?token=..."}. If no eligible ad, return 204 No Content. -
Async logging (non-blocking): Write the request, all candidates considered, scores, and final decision to Kafka topic
ad_requests.
Total latency budget: ~15–25 ms under normal conditions, well under the 50 ms p99 target.
5. Event pipeline
Impression and click tracking:
- Client fires a beacon to
/track/impor/track/clickwith the signed token. - Event collector verifies the HMAC, extracts fields, stamps server receive time, and writes to Kafka (
impressionsorclickstopic). If Kafka is down, buffer to local disk and replay.
Stream processing (Flink):
- Deduplicate impressions by
impression_idusing keyed state (TTL 24 hours). Clients retry, and some ad networks send duplicates. - Increment campaign spend (impression_count × CPM / 1000) and push aggregates to the budget service every few seconds.
- Increment frequency counters in Redis:
INCR freq:{uid}:{campaign_id}:{date}. - Emit per-minute aggregates (impressions, clicks, spend by campaign, placement, experiment variant) to the OLAP store for dashboards.
Batch processing (Spark, nightly):
- Read raw events from S3, deduplicate exactly, join impressions with clicks (with attribution window), compute final spend and CTR per campaign.
- Reconcile with streaming totals; alert if drift exceeds 1%.
- Compute experiment metrics: for each variant, calculate CTR, revenue, and guardrails (e.g., latency, fill rate). Run statistical tests (t-test or bootstrap confidence intervals).
6. Experiment design
Assignment:
- Use deterministic hashing:
hash(uid + layer_salt) % 10000maps each user to a bucket (0–9999). - Each experiment owns a range of buckets within a layer. Experiments in the same layer are mutually exclusive (e.g., two ranking experiments can't overlap). Experiments in different layers run concurrently (e.g., a ranking test and a creative test).
- Assignment happens on every request with no database lookup, ensuring consistency and speed.
Exposure logging:
- The signed impression token includes all experiment assignments. When the impression fires, the stream processor extracts these and writes to an
experiment_exposurestable. - Only log exposures when an ad is actually shown (not on every request) to avoid dilution from users who never saw an ad.
Metric computation:
- Primary metric: typically CTR (clicks / impressions) per variant.
- Guardrails: fill rate (requests → impressions), latency (p99), revenue (total spend).
- Compute daily in the batch pipeline. For faster iteration, stream processor can emit preliminary results every hour.
Safety mechanisms:
- Traffic ramping: Start experiments at 1% traffic, monitor for 24 hours, then ramp to 10%, 50%, 100%.
- Kill switch: Experiment config includes a status field. Setting it to "paused" stops new assignments within 30–60 seconds (next config refresh).
- Guardrail alerts: Automatically pause if fill rate drops >5% or p99 latency exceeds 100 ms.
7. Key trade-offs and failure modes
Trade-offs:
- In-memory index vs. database lookup: Holding the catalog in memory makes serving fast but means config changes take 30–60 seconds to propagate. For most ad systems, this staleness is acceptable. Critical changes (pause a campaign immediately) go through the budget service, which can block serving instantly.
- Optimistic frequency counting: Ad servers can increment Redis counters at serve time rather than waiting for the impression event. This closes the lag window (a user sees multiple impressions before the first event is processed) but risks slight overcounting if impressions don't fire. Acceptable trade-off for user experience.
- Eventual consistency in dashboards: Minute-level metrics from the stream processor are approximate (no deduplication across windows). Daily batch jobs provide the source of truth. This is standard in ad systems—operators understand the distinction.
Failure modes:
- Redis unavailable: Frequency cap checks fail open (serve ads anyway) or fail closed (skip campaigns requiring caps). Fail open is typical, with monitoring to detect and alert. Overspend risk is low because budget enforcement is separate.
- Budget service unavailable: Ad servers use stale token allotments for a few minutes. Campaigns may slightly overspend (by the allotment size × number of servers) until the service recovers. Mitigate by keeping allotments small (e.g., $10 per server per campaign).
- Kafka lag: Event processing delays by minutes. Frequency caps and spend tracking lag, risking overdelivery. Dashboards show stale data. Monitor consumer lag and scale stream processors. Critical budgets can have a secondary fast path (write-through to budget service).
- Index build fails: Ad servers continue using the last good snapshot. New campaigns don't serve until the build recovers. Alerts fire immediately on build failure.
Time and space complexity
- Serving path: O(C) candidate retrieval where C is the number of creatives matching targeting filters (typically 10–100), O(C) for frequency lookups (single batched Redis call), O(C log C) for ranking. Total: O(C log C), dominated by network I/O to Redis.
- Experiment assignment: O(L) where L is the number of layers (typically 3–5), each requiring one hash computation. Effectively O(1).
- Event deduplication: O(1) hash table lookup per event in Flink keyed state.
- Storage: ~40 GB/day raw events, compressed to ~10 GB in Parquet. Retained 90 days in the lake, 7 days in Kafka. Campaign and experiment config is <1 GB.
Example code structure (pseudocode)
class AdServer:
def serve_ad(self, request):
# 1. Assign experiments
assignments = []
for layer in self.experiment_config.layers:
bucket = hash(request.uid + layer.salt) % 10000
for exp in layer.experiments:
if exp.bucket_range.contains(bucket):
variant = exp.select_variant(bucket)
assignments.append((exp.id, variant.name))
break
# 2. Get candidates
candidates = self.index.lookup(request.placement, request.country, request.device)
candidates = [c for c in candidates if self.is_eligible(c, request)]
# 3. Frequency cap check
campaign_ids = [c.campaign_id for c in candidates]
freq_counts = self.redis.mget([f"freq:{request.uid}:{cid}:{today()}" for cid in campaign_ids])
candidates = [c for c, count in zip(candidates, freq_counts) if count < c.freq_cap]
# 4. Budget check
candidates = [c for c in candidates if self.budget_tokens[c.campaign_id] > 0]
# 5. Rank
ranker = self.get_ranker(assignments) # variant config may override ranker
scores = [(ranker.score(c, request), c) for c in candidates]
scores.sort(reverse=True)
if not scores:
return None # 204 No Content
_, selected = scores[0]
# 6. Generate response
impression_id = uuid4()
token = self.sign({
"impression_id": impression_id,
"campaign_id": selected.campaign_id,
"creative_id": selected.id,
"uid": request.uid,
"timestamp": now(),
"experiments": assignments
})
# 7. Async log
self.kafka.send("ad_requests", {
"impression_id": impression_id,
"request": request,
"candidates": candidates,
"scores": scores,
"selected": selected.id,
"experiments": assignments
})
return {
"ad_id": selected.id,
"creative_url": selected.cdn_url,
"impression_url": f"/track/imp?t={token}",
"click_url": f"/track/click?t={token}"
}
This design handles millions of requests per day with low latency, enforces delivery controls, and supports rigorous experimentation with deterministic assignment and accurate metric computation.