Frequency Capping at 500K QPS: Low-Latency Ad Eligibility
System DesignModel answerLast updated
Design a sharded, in-memory service that decides in under 10 ms whether a viewer has hit ad/campaign caps, with async impression counting and deliberate soft-cap tolerance.
Context
A streaming platform's ad stack must limit how often the same viewer is shown a given ad, campaign, or advertiser within time windows such as "at most 2 impressions per viewer per hour" and "at most 5 per viewer per day." The ad decision service (ADS) calls this component on every ad pod, before it runs its auction, and drops any candidate that is already capped. After an ad is actually played, the platform must record the impression so future checks see it.
Design this frequency-capping (FC) service end to end.
Functional Requirements
- Check: given a viewer (profile, device, or household identifier) and a batch of candidate ads with their ad/campaign/advertiser IDs, return which candidates are still eligible.
- Record: given a confirmed impression, apply it to every window that the relevant rules cover.
- Flexible rules: caps may be scoped to ad, campaign, or advertiser, at profile or household level, and applied over rolling 1h, rolling 24h, calendar-day (viewer's timezone), and possibly multi-day windows. Rules are configurable without redeploying the service.
Non-Functional Requirements
- Latency: check returns at
p99 < 10 ms; the whole FC call sits inside a tight ad-pod budget (assume ~5 ms of the budget). - Availability: 99.999% for the service; a degraded FC must never delay or break video playback — ads are the only thing at stake.
- Throughput: 500K QPS checks, each carrying ~20–50 candidates; ~50K QPS impressions.
- Consistency: soft caps are the default and a small amount of over-delivery (order 1%) is acceptable; a small set of contractually hard caps must never be exceeded by more than a negligible amount.
What to Cover
- API contract for check and record.
- Counting data structures and storage footprint estimates.
- Component architecture and read/write paths, including how the race between check and impression is closed.
- Sharding, hot keys, and multi-region layout.
- Failure policy: when to fail open, when to fail closed, and how consumers learn the system degraded.
Hints
Hint 1
Do the arithmetic first: 500K checks × 30 candidates is ~15M counter evaluations per second, so define one key per viewer that holds everything and is read in a single round trip.
Hint 2
Don't store one timestamp per impression. Bucketed ring counters (e.g. 5-minute buckets for the 1h window, 1-hour buckets for 24h) bound memory and the error costs at most one bucket of under-delivery.
Hint 3
The beacon from the client arrives after the ad is chosen, so two back-to-back pods can both pass the check. Close that gap with a short-TTL optimistic increment written at selection time, then reconciled by the real impression event.
Hint 4
Separate soft from hard caps in the failure policy: fail open with a degraded flag for soft caps, fail closed (filter the candidate) for hard ones, and never let either path block playback.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Frame the problem with numbers
Assume 100M daily viewers on the ad tier, each exposed to roughly 20–50 capped entities (ads, campaigns, advertisers) per day. Checks dominate: 500K QPS × ~30 candidates ≈ 15M counter evaluations per second, versus 50K QPS writes — a 10:1 read/write ratio. Windows: rolling 1h, rolling 24h, calendar day in the viewer's locale, optionally 7-day.
Semantics matter up front. Treat caps as soft by default (≈1% over-delivery tolerated) with an opt-in hard tier for a small set of contracts. FC is a dependency of ad decisioning only; if it is slow or down, ads should still serve and playback must never be affected.
2. API
CheckCandidates(viewer{user_id, device_id, household_id},
candidates[{ad_id, campaign_id, advertiser_id}], ts)
→ {eligible: [...], filtered: [{ad_id, rule_id, reason}], degraded: bool}
RecordImpression(impression_id, viewer, ad_id, campaign_id, advertiser_id, served_ts)
→ 202 Accepted (asynchronous; idempotent on impression_id)
Two details carry weight. The check is batched per ad pod, so the network round trip is amortized over dozens of candidates. The degraded flag propagates to ADS, billing analytics, and alerting so a fail-open window is visible rather than silent.
Rules are configuration, not request data: {rule_id, scope: ad|campaign|advertiser, level: profile|household, limit, window} lives in a rule service and is pushed to every FC instance and held in memory with a version number, so the hot path never reads rule storage.
3. Counting structure and footprint
| Option | Accuracy | Memory | Verdict |
|---|---|---|---|
| Timestamp log per impression | Exact | ~100B/entry, unbounded | Too expensive |
| Fixed window counter | Up to 2× cap at boundaries | Tiny | Only for calendar-day |
| Bucketed ring counters | Error ≤ one bucket, and biased to under-deliver | ~100B/entity | Primary choice |
| Count-Min Sketch | Overcounts, shared error | Very small | Analytics, not enforcement |
Store one record per viewer so a check is a single key read:
fc:{user_id}
c:{campaign_id} → packed ring: 12 × 5-min buckets (1h window)
+ 24 × 1-h buckets (24h window)
+ {local_date, day_count}
a:{ad_id}, v:{advertiser_id} → same shape
TTL 25h, refreshed on write
Each bucket is a uint16 addressed by floor(ts / bucket_size) mod N, with a base epoch so stale slots are recognized and lazily reset. A rolling count sums the buckets inside the window; to be safe we count the oldest bucket in full, which slightly under-delivers rather than over-delivers. The increment-and-rotate runs as a store-side atomic function (Redis Lua or equivalent) so concurrent writes to the same viewer don't corrupt the ring. Dedup uses a short-TTL set keyed by impression_id, making replays harmless.
Footprint: ~90B per entity, 30 entities ≈ 3KB/viewer, 100M actives ≈ 300GB, ~600GB with a replica. That fits in roughly 40–60 memory-optimized shards at ~25K reads/s each — comfortable headroom for peak spikes.
4. Architecture and paths
Client → ADS → gRPC Check (5ms budget, hedged) → FC (stateless, rules cached)
→ sharded in-memory counter store
Client playback start → beacon → Kafka (partitioned by user_id)
→ impression consumers → atomic increment
→ cross-region replication topic
Read path: ADS issues the check in parallel with other candidate-enrichment calls; FC does one key fetch, then evaluates all candidates × applicable rules in memory in microseconds. This is why per-viewer key co-location is non-negotiable.
Write path: the client fires an impression beacon when playback begins; Kafka partitioned by user_id preserves per-user order; consumers dedupe and apply increments atomically. Typical end-to-end lag is sub-second.
Closing the check/impression race: because the beacon trails selection, two consecutive pods can both pass before the first impression lands. On selection, ADS writes an optimistic pending increment directly to the store with a short TTL (~10s); the real beacon confirms and replaces it. This bounds double-serve within a pod sequence instead of waiting on the event pipeline.
5. Partitioning, hot keys, multi-region
- Sharding: consistent hash on
user_id(orhousehold_idwhen household rules apply) so all of a viewer's counters sit on one node and no check fans out. - Read scaling: replica reads; millisecond replica lag is dwarfed by beacon lag anyway.
- Hot keys: true per-viewer hot keys are rare — mostly shared devices, bots, and test accounts. Use a 1–2s local near-cache on those keys, rate-limit anomalous viewer IDs, and keep rules out of per-key storage entirely.
- Multi-region: assign each viewer a home region that holds authoritative counters; route geo-sticky. Replicate counters as CRDT G-counters (per-region slots merged by max) so a failover or roaming viewer converges without split-brain. The resulting over-delivery is bounded by replication lag (seconds) × the viewer's ad rate (one ad every few minutes) — irrelevant for soft caps.
6. Failure policy
| Failure | Response |
|---|---|
| FC timeout >5ms or shard unavailable | Fail open for soft caps, return all candidates with degraded=true; fall back to a session-local "recently served" list ADS already carries to avoid back-to-back repeats |
| Hard-cap campaigns during outage | Fail closed — filter them; other ads can fill the slot |
| Kafka/consumer lag | Checks still run but undercount; alert on lag, pending increments bridge the gap |
| Region partition | Serve locally from CRDT slots; accept bounded over-delivery; reconcile on heal |
Common mistakes: storing one timestamp per impression (memory blows up); a per-candidate network call instead of a batched single-key read; fetching rules on the hot path; forgetting that the check happens before the impression is confirmed; and a blanket fail-closed policy that silently collapses the ad fill rate during a routine shard blip.