Design a Video Ad Insertion Platform for Streaming
System DesignModel answerLast updated
Design a low-latency, fault-tolerant ad-insertion system for a live and on-demand video platform, covering decisioning, delivery, pacing, and measurement at scale.
Background
You are a senior engineer at a large video streaming platform serving both live events and on-demand content. The platform needs a dedicated ad-insertion system that can handle hundreds of millions of daily active users, real-time ad auctions, and live-stream spikes — all without ever stalling playback.
Task
Design the end-to-end ad-insertion platform for this service. Walk through your reasoning at each step: requirements gathering, API design, data model, architecture, and key technical deep dives.
Your design should address:
- Ad formats and delivery modes — pre-, mid-, and post-roll ads; live vs. VOD; server-side vs. client-side insertion; VAST/OMID support.
- Ad decision engine — how candidate ads are selected, ranked, and assembled into a break (pod) under 100 ms p99 latency at the edge.
- Targeting and personalization — geo, device, demographic, and contextual signals; user segment lookups; brand safety.
- Pacing and frequency control — budget pacing curves, frequency caps per user and per household, cross-device deduplication.
- Programmatic demand — how to integrate with real-time bidding (RTB) exchanges alongside direct-sold campaigns.
- Measurement — impression counting, quartile events (25/50/75/100%), clicks, and viewability.
- Live stream thundering herd — how to handle 10M concurrent viewers all hitting the same mid-roll break within a 2-second window.
- Fault tolerance and multi-region failover — what happens when a dependency is slow or unavailable.
- Privacy compliance — how to handle GDPR/CCPA consent signals and limit-ad-tracking flags.
- Experimentation — how to A/B test ad policies such as pod length, frequency caps, or auction logic.
Scale assumptions to work with
- 100M daily active users; roughly 2B ad requests per day (~23K average QPS, ~100K peak for VOD).
- Live spike scenario: 10M concurrent viewers reaching a mid-roll cue within ~2 seconds.
- Beacon volume: ~6 measurement events per impression, 500K+ events/s at peak.
- Target availability: 99.99%. The system must never block playback — fail open to a house ad or slate.
- Active-active multi-region deployment.
What is expected
Treat this as a real design conversation. State your assumptions, propose concrete numbers and data structures, acknowledge trade-offs, and explain why you made each choice. A strong answer covers the full breadth of the problem and dives deep on at least the latency budget, the live-spike handling, and the pacing mechanism.
Hints
Hint 1
Start by separating two distinct problems: the ad decision problem (which ad wins?) and the ad delivery problem (how does it reach the player seamlessly?). These have very different latency and throughput characteristics.
Hint 2
The live thundering herd is the hardest scaling challenge. Think about what changes if you group viewers into cohorts and run one auction per cohort rather than one per viewer — and what you can precompute in the SCTE-35 lead time before the break begins.
Hint 3
A global lock for frequency capping and budget pacing won't meet your latency target. Consider what consistency guarantees you actually need: is slight over-delivery acceptable, and if so, what distributed counter design lets you trade perfect accuracy for speed?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and Scale
Before drawing boxes, pin down what the system must do.
Functional scope
- Insert pre-, mid-, and post-roll ads into both live and VOD streams. Live breaks are triggered by SCTE-35 splice cues.
- Target ads by geography, device type, demographic segment, contextual content signals, and brand-safety category.
- Enforce budget pacing (spend along a target curve) and frequency caps (e.g., no more than 3 impressions per user per campaign per day).
- Fill ad pods: multiple ads per break with competitive separation, advertiser deduplication, and a hard duration constraint.
- Serve both guaranteed direct-sold line items and programmatic demand via RTB exchanges.
- Measure impressions, quartile completions (25/50/75/100%), clicks, and viewability (OMID).
- Support A/B experiments on ad policies.
Non-functional
- 100M DAU, ~2B requests/day, peak ~100K QPS for VOD.
- Live spike: 10M concurrent viewers hit a single mid-roll within ~2 s — this is the core design stress test.
- p99 decision latency ≤ 100 ms at the edge.
- 99.99% availability; the system must never block playback.
- Active-active multi-region.
- Full GDPR/CCPA/COPPA compliance: honor TCF/GPP consent strings and limit-ad-tracking signals.
2. API Design
Two primary decision surfaces:
POST /v1/ad-decision
Body: { session_id, device_id_hash, content_id, break_id,
break_type: pre|mid|post, max_duration_s, max_ads,
consent: { tcf, gpp, lat }, geo, device, experiment_ctx }
Response: { pod: [{ ad_id, creative_url, duration,
tracking: { imp, q1..q4, click },
omid: { vendor, script, params } }], ttl_s }
POST /v1/events # batched measurement beacons
Body: [{ imp_id, event, ts, signature }]
Each impression gets a signed imp_id (HMAC over decision ID + ad ID + timestamp). This makes beacon verification cheap and deduplication reliable — replayed or corrupted beacons are rejected without a database lookup.
For CSAI (client-side insertion) players, a GET /vast endpoint returns a VAST 4.x XML wrapper built from the same pod. VPAID is deprecated and incompatible with SSAI; prefer SIMID for interactive formats.
3. Core Architecture
Player / CSAI ┌─ Campaign Store (Postgres → in-mem snapshot)
│ ├─ Segment KV (Aerospike / Redis)
▼ ├─ Frequency-cap store (regional Redis, CRDT)
CDN Edge → Ad Decision Service (per region) ──────┤─ Pacing controller (throttle rates)
SSAI Stitcher (manifest rewrite) ├─ RTB Gateway (OpenRTB 2.6)
└─ Content Signals (brand-safety labels)
Beacons → Edge collectors → Kafka → Flink (dedup, IVT filter) → OLAP + billing
Delivery mode choice: Use server-side ad insertion (SSAI) for live and the majority of VOD. The stitcher rewrites HLS/DASH manifests to splice transcoded ad segments directly into the stream. Benefits: ad blockers cannot intercept, playback is seamless, and one decision result can be cached for a cohort of viewers. Use CSAI only where rich interactivity is needed, since it requires VAST round-trips and is blocked on ad networks.
4. Data Model (key entities)
- Campaign / Line Item: budget, flight, pacing curve, targeting expression (compiled to a bitset index), frequency cap, priority tier, CPM, brand-safety exclusion list.
- Creative: renditions transcoded to match stream ladders (360p → 4K), duration, VAST metadata, approval status.
- Content metadata: IAB categories, brand-safety labels from ML classifiers, break schedule, live cue timestamps.
- User profile: hashed identity → segment bitset, household cluster ID, consent state, TTL-bound.
- Frequency counters:
(household_id, campaign_id) → sliding-window countin regional Redis. - Event log: append-only impression and quartile records feeding billing and analytics.
5. Meeting the 100 ms Latency Budget
The decision service runs in every region, close to the edge. All hot data — campaigns, targeting indexes, creatives — is compiled into an in-memory snapshot refreshed every 30–60 seconds. No synchronous database calls are on the critical path.
| Step | Target |
|---|---|
| Network (player to edge) | ~10 ms |
| Segment + freq-cap lookup (parallel local KV) | ~10 ms |
| Candidate retrieval via inverted targeting index | ~10 ms |
| Ranking + pod packing | ~10 ms |
| RTB fan-out (hard timeout) | ≤ 60 ms |
Any dependency timing out degrades gracefully. Missing segment data → contextual-only targeting. RTB timeout → direct-sold or house ads. The system never waits.
6. Live Thundering Herd
10M viewers × 1 decision each within 2 seconds is ~5M QPS — impossible to serve naively. The fix is cohort-based pre-decisioning:
- SCTE-35 lead time: Live cues arrive 5–10 s before the break. Use that window to pre-run auctions.
- Cohort grouping: Cluster viewers by (segment × geo × consent). 10M viewers collapse to tens of thousands of distinct cohorts. Run one auction per cohort; apply per-user frequency filtering in a cheap post-pass.
- Cache at the stitcher: Pod decisions are cached per cohort at the SSAI stitcher.
- CDN pre-warm: Winning creative segments are pushed to CDN edge nodes before the break starts.
This converts a 5M QPS spike into a manageable pre-decisioning workload spread over 5–10 seconds.
7. Pacing and Frequency Capping
Pacing: A central pacing controller reads spend-to-date from the billing stream and publishes per-line-item throttle multipliers to all regions every few seconds (PID-style control). Each regional decision node applies the multiplier locally — no cross-region lock needed. Overspend tolerance of ~1–2% is accepted in exchange for avoiding a global serialization bottleneck. The controller reconciles after each billing flush.
Frequency capping: Cap at the household/identity-graph level using deterministic login IDs first, and probabilistic device clustering only where consent allows. Counters live in regional Redis as CRDT G-counters and replicate cross-region asynchronously. Increments happen on confirmed impression (beacon), not on decision. During replication lag, slight over-delivery is possible — state this explicitly as a deliberate trade-off (consistency vs. availability). Within a single session, maintain an in-memory seen-ad list so the same creative never repeats within a pod.
8. Ad Podding
Filling a break is a constrained bin-packing problem:
- Maximize revenue within
max_duration(e.g., 90 s from 15/30 s creatives). - Enforce competitive separation (no two auto brands), one ad per advertiser per pod, position premiums for first slot.
- A greedy fill by eCPM-per-second plus a small DP over durations works well — pods are small (≤ 6 ads), so this is fast.
- Unfilled time gets house ads or a slate. For live, the break duration is fixed by the content timeline, so every second must be filled.
9. RTB Integration
The RTB gateway emits OpenRTB 2.6 requests including the pod object, content object (category, rating), and consent strings. Personal data is stripped when consent is absent. Fan out to exchanges in parallel with a ~60 ms hard timeout and apply bid shading. Unified auction: programmatic bids compete with direct line items on eCPM, with guaranteed deals given priority. Programmatic creatives must be pre-transcoded (or just-in-time transcoded from a VAST URL) to match the stream ladder before they can be stitched.
10. Measurement
Beacons flow from players to edge collectors, into Kafka, and through a Flink pipeline that handles deduplication (by imp_id), invalid traffic filtering, and quartile attribution. Output goes to an OLAP store (Druid/ClickHouse) for real-time reporting and to the billing system. The signed imp_id scheme means deduplication is a cheap set-membership check rather than a full join.
11. Privacy
Honor TCF consent strings and GPP signals at the segment-lookup layer: if a user has not consented to personalization, suppress segment data and target contextually only. Respect lmt (limit-ad-tracking) flags on devices. Ensure cross-device identity clustering is gated on explicit consent. Purge user profiles on deletion requests within SLA. Log consent state alongside each impression for compliance audits.
12. Experimentation
Use an experiment context passed in the decision request to route sessions into treatment buckets. The decision service applies bucket-specific overrides (different pod policies, cap values, or auction weights) without code deploys. Metric collection is identical — Flink tags events with experiment ID. Guard rails (e.g., completion rate floor) auto-pause experiments that harm user experience.
Common Mistakes to Avoid
- Treating SSAI and CSAI as interchangeable — they have fundamentally different latency profiles, ad-blocker exposure, and interactivity support.
- Designing frequency caps with a global lock — it cannot meet the latency budget and is a single point of failure.
- Ignoring the SCTE-35 lead time — candidates who jump straight to serving 10M live decisions in 2 s miss the key insight.
- Proposing VPAID — it is deprecated and incompatible with SSAI; SIMID is the correct modern answer.
- Conflating the decision latency budget with the beacon processing latency — these are separate pipelines with separate requirements.