Per-User Impression Limits for an Ad Serving Platform
System DesignModel answerLast updated
Design a low-latency service that stops an ad platform from showing a user the same ad or campaign more than an allowed number of times per time window, across regions.
Limit How Often a User Sees an Ad
You are building part of a large advertising platform. Advertisers want to control exposure, so the platform must guarantee that a single user is not shown the same ad (or campaign) more than an allowed number of times in a given period. Example rules:
- An ad may be shown to a given user at most 3 times per day.
- A campaign may be shown to a given user at most 10 times per week.
Design the system that enforces these limits.
What your design should cover
- How the ad server decides, in real time and before serving, whether a candidate ad is still allowed for this user.
- How impressions are recorded, counted and stored.
- How to support several scopes of limits: user + ad, user + campaign, user + advertiser, and household-level limits.
- How to handle high request volume, tight latency and eventual consistency across multiple regions.
- How to cope with impression events that are late, duplicated or out of order.
- Retention: expiring old counts, and the trade-off between accuracy and latency.
Assumptions you may use
- Very high ad-request QPS, with a budget of a few milliseconds per cap check (single-digit ms at p99), and a high-volume impression event stream.
- Multiple configurable limits per scope over hourly, daily, weekly or rolling windows.
- Reasonable accuracy is the goal. A small, bounded overshoot is acceptable by default, but a campaign may opt into stricter enforcement.
- The serving path must remain highly available, and the system runs in several regions.
State any clarifying questions you would ask (for example: calendar vs. rolling windows, strictness, single vs. multi-region, fail-open vs. fail-closed) and the assumptions you pick.
Hints
Hint 1
Separate the two paths: a read-heavy, latency-critical eligibility check at serve time and a write path that records impressions and updates counts. They have different SLAs and can use different tools.
Hint 2
Think about the counter key. It should encode the scope (user, ad, campaign, household) and the window bucket (for example day number), so expiry is just a TTL and old buckets never need cleanup logic.
Hint 3
Strictness is a spectrum. Reading counts from a fast store and incrementing after the impression gives a small overshoot; reserving a slot atomically at decision time gives a tighter bound at higher cost. Match the approach to the campaign's needs.
Hint 4
Make the write path idempotent by keying each impression on a unique event ID, so retries and duplicates do not double-count, and bucket by event time so late events land in the right window.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying assumptions
- Calendar-aligned windows (UTC day, ISO week) are the default; rolling windows are supported via sub-buckets.
- Default enforcement is "approximately exact": a small overshoot (a few impressions under concurrency or cross-region lag) is fine. A campaign can opt into strict mode.
- On counter-store failure, default to fail open for most campaigns (revenue and availability matter), with a per-campaign fail closed option for contractual or regulatory caps.
High-level architecture
Two separate paths:
- Decision path (read, synchronous). The ad server fetches candidate ads, then asks a frequency-cap service (or an in-process client library) which candidates are still eligible.
- Recording path (write, asynchronous). When an impression is confirmed (render or beacon), an event goes to a durable log (Kafka or similar). Consumers update counters and archive raw events.
Ad request -> candidate ads -> cap check (counter store) -> auction -> serve
|
Impression beacon -> event log -> stream processor -> counter store + cold storage
Data model
Cap rules live in a config store (relational DB plus a cached copy at the servers): rule_id, scope (user_ad | user_campaign | user_advertiser | household_campaign), limit, window_type (hourly | daily | weekly | rolling), window_size. Rules are attached to ads or campaigns, and several can apply to one ad at once.
Counters are keyed by scope plus window bucket:
fc:{scope}:{entity_ids}:{window}:{bucket} -> count
fc:ua:{user}:{ad}:d:20250114 -> 2
fc:uc:{user}:{campaign}:w:2025W03 -> 7
Because the bucket is part of the key, each key gets a TTL slightly longer than its window and expires on its own. For rolling windows, use small buckets (for example hourly for a 24h window) and sum the last N buckets on read.
A fast in-memory store (Redis, Aerospike, or a similar key-value store) holds counters. Raw impression events go to a log and then to columnar or object storage for audit, billing reconciliation and rebuilding counters.
Read path (low latency)
- Group a user's keys by shard and fetch them with one batched multi-get per request (pipelined). With 50 candidate ads and 3 rules each, this is still one or two round trips, not 150.
- Compare counts against limits and drop ineligible ads before the auction.
- Cache a user's counters in the request context, since the same user may appear in several slots of one page.
- Latency budget: about 1-2 ms network, plus sub-millisecond lookup. Co-locate the store with ad servers in each region.
Write path
- Each impression event has a unique
impression_id, user ID, ad, campaign, advertiser, household and event timestamp. - The stream processor does an idempotent increment: it first checks a dedupe set (
SETNX impression_idwith a TTL of a few hours, or a Bloom filter backed by exact checks) and only increments if the ID is new. Then it increments every applicable counter, such as user-ad-day, user-campaign-week and household-campaign-day. - The bucket comes from event time, not processing time, so a delayed event still hits the correct day. If the bucket is already expired, drop it from counters but keep it in cold storage.
- Out-of-order events are harmless because increments are commutative.
Consistency and strictness
| Mode | How | Overshoot | Cost |
|---|---|---|---|
| Relaxed (default) | Read counts, serve, increment asynchronously after the impression | Concurrency plus pipeline lag, typically a few extra impressions | Cheapest |
| Optimistic increment | Increment at decision time (a "pending" counter), decrement or expire if the impression never renders | Small | One extra write per served ad |
| Strict | Atomic check-and-increment (Lua script or conditional write) on a single authoritative shard for the user | Near zero | Higher latency, lower availability across regions |
Race conditions: two simultaneous requests for the same user can both see count = 2 with a cap of 3 and both serve. Atomic check-and-increment, or the pending-counter approach, closes this gap. For most campaigns, accept it.
Multi-region. Two options:
- Home-region routing: pin each user to a home region (by hashing the user ID) and route cap checks there. Accurate, but adds cross-region latency for roaming users.
- Local counters with async replication: each region counts locally and replicates deltas (CRDT-style G-counters, where each region increments its own slot and the total is the sum). Reads are local and fast, and overshoot is bounded by replication lag times the user's impression rate.
A common compromise: local counters for the default mode, home-region strict checks only for campaigns that opt in. Another option is splitting the cap into per-region budgets (for example 3 per day becomes 2 home plus 1 elsewhere) when strictness is needed.
Late, duplicate and missing data
- Duplicates: idempotency key per impression, as above. At-least-once delivery plus dedupe gives effectively-once counting.
- Late events: event-time bucketing, with a cutoff (for example 24-48h) after which events go only to cold storage.
- Lost events: undercounting causes overshoot. A periodic batch job recomputes counts from the raw log and corrects the store (a lambda-style reconciliation).
- Pipeline lag: monitor consumer lag. If lag is high, optionally tighten behavior by using decision-time increments.
Retention
- Counters: TTL equals window length plus a small buffer (daily keys about 25-48h, weekly keys about 8 days).
- Raw events: hot for days, then cold storage for months (billing, audits, model training).
- Dedupe keys: short TTL (hours).
Scale and failure handling
- Sizing example: 500M daily users with about 100 active counters each at roughly 50 bytes is about 2.5 TB in memory, so shard by
hash(user_id)across a cluster with replicas. Keeping all of a user's keys on one shard (hash on user ID, not on the full key) enables one-shot multi-gets. - Hot keys: household or very large-advertiser keys can be hot. Use local caching with short TTLs or split the counter into sub-counters and sum them.
- Outage: fail open by default using a cached last-known count or a conservative default, and alert. Fail closed for campaigns flagged as strict.
- Observability: track overshoot rate (served impressions beyond cap, computed offline from raw logs), p99 check latency, consumer lag, dedupe hit rate, and fail-open counts.
Common mistakes
- Using one counter with no window bucket, which forces manual resets and cleanup.
- Counting at serve time only, so impressions that never render still consume the cap.
- Not making increments idempotent, causing double counts on retries.
- Using processing time instead of event time for bucketing.
- Demanding global strict consistency everywhere, which hurts latency and availability for minimal business gain.
- Making N sequential lookups per candidate instead of one batched fetch.
Summary
Use a fast sharded key-value store of bucketed counters, a batched read on the serving path, an idempotent event-time stream pipeline for writes, relaxed consistency by default with opt-in strict modes, and reconciliation from the raw event log to keep drift small.