Per-User Impression Limits Over a Sliding Time Window
System DesignModel answerLast updated
Design a low-latency service that decides whether an ad may be shown to a user, enforcing "at most N impressions in the last W" caps across ad, group and campaign scopes.
You are building a service for an ad platform that limits how often a single user sees the same advertising content. Every limit is expressed as: a user may be shown at most N impressions within the most recent W units of time. The window slides with the clock; it is not tied to calendar days or hours.
A limit can be attached to different levels of the ad hierarchy: an individual ad (creative), an ad group, a campaign, or possibly an advertiser. One impression counts toward every level it belongs to.
When an ad request arrives for a user, the platform has a set of candidate ads and needs to know which of them are still allowed. After an ad is actually displayed, the system must record that fact so that later decisions take it into account.
Design this service. Your answer should cover:
- Requirements and scale assumptions: what you would clarify up front and which numbers you would assume (users, request rate, latency budget, longest window).
- Read path: how the "can this ad be shown?" decision is made.
- Write path: how an impression is recorded after it is served.
- Data models: how limit definitions and per-user impression history are stored.
- Correctness under load: how you prevent users from exceeding their limits when many requests arrive at once.
- Distributed-systems concerns: race conditions, duplicate or retried events, component failures, and retention or cleanup of old data.
State your trade-offs explicitly (for example, exact versus approximate counting, and what happens when the data store is unavailable).
Hints
Hint 1
Key the impression history by user, so one lookup gives you everything needed to evaluate all candidates and all scopes for that user in a single read.
Hint 2
There is a gap between choosing an ad and receiving confirmation that it was displayed. Think about a short-lived 'pending' record that is checked and written atomically with the cap check.
Hint 3
Retries and at-least-once delivery will produce duplicate events. Give every impression a unique ID and make the write a no-op if that ID already exists.
Hint 4
Decide in advance what to do when the store is slow or down, and whether the answer differs for strict contractual limits versus soft ones.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify requirements
- Scopes: ad, ad group, campaign, maybe advertiser. A single impression counts toward all of them.
- Limit shape:
Nimpressions per rolling windowW. Typically N is 1 to 10 and W ranges from an hour to 30 days (assume 30 days is the maximum). - Correctness bar: a rare overshoot by one is usually acceptable, but systematic over-delivery is not because it breaks advertiser contracts and billing. Wrongly blocking an ad (undershoot) loses revenue but is the safer error.
- What counts as an impression: a client-confirmed render, not merely a selection by the ad server.
Assumed scale
| Quantity | Estimate |
|---|---|
| Active users | 200M |
| Peak ad requests | 50K/s, about 20 candidates each, so about 1M limit evaluations/s |
| Peak impressions | about 30K/s |
| Latency | limit check p99 under 10 ms inside a roughly 100 ms ad decision |
| History per user | up to about 200 events over 30 days |
| Event size | about 32 bytes |
| Total | 200M x 200 x 32 B, roughly 1.3 TB worst case, much less in practice |
This fits in a sharded in-memory store.
2. APIs
CheckCaps(user_id, candidates[{ad_id, group_id, campaign_id}], request_id)
-> [{ad_id, allowed, reason}]
Reserve(user_id, request_id, selected_ads[], ttl)
-> reservation_ids
RecordImpression(impression_id, user_id, ad_id, group_id, campaign_id, server_ts)
// idempotent on impression_id
Batching all candidates for one user into one call turns about 1M evaluations/s into about 50K store reads/s.
3. Data model
Limit definitions (low write rate, need auditing and versions) live in a relational database:
cap(cap_id, scope_type, scope_id, max_impressions, window_seconds,
enforcement ENUM(strict, best_effort), status, version, updated_at)
They are compiled into a versioned snapshot keyed by scope_id and pushed to every cap-service node. The hot path never queries the database for configuration.
Impression history is keyed by user:
key: fc:{user_id}
value: {
events: sorted list of (ts, ad_id, group_id, campaign_id, impression_id_hash),
pending: list of (reservation_id, ts, ids..., expires_at)
}
The count for a limit is the number of events matching the scope with ts > now - W, plus matching pending reservations. Because N is small the list is short and the count is exact.
Fallback for large N or long W: keep bucketed counters per (user, scope), for example hourly buckets across 30 days. The bucket at the trailing edge only partly overlaps the window. Counting it fully is conservative (never over-serves); interpolating it reduces undershoot. This trades exactness for bounded memory.
4. Architecture
Ad Server -> Cap Service (stateless, config in memory)
| one read per user
v
Sharded KV (Redis/Aerospike), sharded by user_id,
primary + replicas, persisted
^
Client beacon -> Collector -> Kafka (keyed by user_id)
|-> Cap writer consumers -> KV (atomic append)
|-> Billing / analytics / cold storage
Read path: the ad server sends the candidates. The cap service fetches fc:{user_id}, drops expired entries in memory, evaluates every limit that applies to each candidate's ad, group and campaign, and returns eligibility. The auction then runs only over eligible ads.
Write path: the collector receives the beacon and stamps a server timestamp (never trust client clocks for window math). It publishes to Kafka partitioned by user, which preserves per-user order. A consumer runs an atomic script on the user's key. Kafka is the durable source of truth, so the KV can be rebuilt by replay.
The atomic write script:
if impression_id_hash in events: return # dedupe
remove matching pending reservation
append event; drop events older than now - max_W
set key TTL = max_W
5. Deep dives
Races and in-flight impressions. Two gaps exist: beacon lag (an ad was chosen but its impression has not arrived) and concurrent requests (two devices, or several slots in one ad break).
The fix is an atomic check-and-reserve. After the auction, Reserve runs a single-key script (Redis Lua or compare-and-set on a version) that re-checks limits including pending reservations and then inserts the reservations. All of a user's state sits in one key on one shard, so no distributed lock is needed. Reservations expire after about 5 minutes if no impression arrives, releasing inventory for ads that never rendered. Within a multi-slot response, the service counts the ads it is selecting against the limits so it never places two copies of a 1-per-hour ad in the same break.
Duplicates. Clients retry beacons and Kafka delivers at least once. The impression ID is minted at selection time and stored with the event, so the write is a no-op on repeats. Dedupe lives exactly as long as the data, so no separate dedupe store is needed. Reserve is idempotent on request_id.
Failures.
- Shard slow or down: use the
enforcementflag.best_effortfails open (serve, log for reconciliation).strictfails closed (drop capped candidates and let uncapped ads fill the slot). Use tight timeouts (about 5 ms) and a circuit breaker so the decision never exceeds its budget. - Failover with replica lag: recent writes can be lost, causing small overshoot. Replaying the last few minutes of Kafka for the affected partitions repairs state.
- Consumer lag: looks like beacon lag, which reservations absorb. Alert if lag exceeds the reservation TTL.
Multi-region. Pin each user's state to a home region and route checks there, accepting a small latency cost for cross-region travelers. The alternative, per-region state with asynchronous merging, is faster but allows overshoot of up to roughly N per extra region, so reserve it for best-effort limits.
Retention. Trim on every write, set the key TTL to the longest window, and archive raw events to cold storage for billing and audits. Limit definition changes are versioned; a shortened window takes effect immediately because the history is raw events.
6. Trade-offs and common mistakes
- Exact list versus bucketed counters: exact and simple for small N, bounded memory for large N.
- Fail open versus closed: revenue versus contract risk.
- Strong versus eventual consistency: single-key atomicity gives strong behavior where it matters at no coordination cost.
Common mistakes: counting only confirmed impressions and ignoring in-flight ones; keying by ad rather than user (forcing many reads per request); trusting client timestamps; using calendar windows; doing read-then-write without atomicity; and having no dedupe on retried events.