Real-Time Impression Frequency Control System
System DesignModel answerLast updated
Build a low-latency distributed system that enforces rolling-window impression limits across multiple dimensions and time horizons for an advertising platform.
You're building a real-time impression control system for an advertising platform. When the serving layer decides which advertisement to display, your system must enforce rules that prevent users from seeing the same content too frequently.
The Problem
Each advertisement can have multiple independent frequency rules. For instance:
- A user should see campaign X no more than 3 times per hour
- The same user should see campaign X no more than 8 times per day
- The same user should see campaign X no more than 15 times per week
These are rolling time windows measured backward from the current moment, not calendar boundaries. When a serving request arrives, it must satisfy every applicable rule to proceed.
What You Must Build
Your system needs at least two operations:
- Reserve — Answer whether showing this ad to this user right now would violate any rule, and if not, hold a slot
- Confirm — Record that the impression actually occurred after the ad was rendered
Design Expectations
Address each of these areas:
- How you model the rolling window problem — what data structure answers "how many times in the last N hours" efficiently
- Storage technology — what backs your hot path and why that choice fits your latency budget
- Request flows — how reserve and confirm move through your system, including error cases
- Handling duplicates and races — multiple concurrent reserve calls, retried confirm events
- Data lifecycle — how old counts expire, how reservations timeout
- Partitioning approach — how you distribute load while keeping related data together
- Observability — metrics that tell you both whether the system is healthy and whether it's enforcing rules correctly
Questions You Should Ask
Before designing, clarify:
- What happens if we occasionally let one extra impression through — is perfect accuracy required or is bounded error acceptable?
- How precise must the time windows be? Can a 24-hour window have a few minutes of slop?
- What user identifier do we receive? Stable logged-in ID, device fingerprint, cookie?
- If our system is down, should we block all ads (safe) or allow them through (available)?
- Is there a separate authoritative log of impressions we can reconcile against?
Scale Parameters
Use these numbers to ground your design:
- Request rate: ~2 million reserve calls per second at peak
- Latency target: p99 under 2 milliseconds for the reserve operation
- User scale: hundreds of millions of active users
- Campaign scale: thousands of active campaigns at any moment
- Event ordering: confirm events may arrive late or out of order
Hints
Hint 1
Think about what state actually needs to exist — you don't need every impression stored forever, just enough to answer the window queries
Hint 2
The consistency choice drives your storage and sharding decisions — strict correctness and best-effort availability have very different architectures
Hint 3
Reservations that never get confirmed need to expire, otherwise they permanently consume quota
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Scoping and Consistency Choice
First, I'd clarify the business tolerance for errors. Two failure modes exist:
- Over-delivery: showing K+1 or K+2 impressions when the cap is K
- Under-delivery: blocking valid impressions due to stale or incorrect counts
For most advertising use cases, bounded over-delivery (say, 5% excess) is acceptable, while under-delivery directly loses revenue. This allows us to choose eventual consistency with bounded drift rather than strict serializability, which buys us both lower latency and higher availability.
Decision: Target best-effort consistency with a bound — we'll tolerate occasional K+1 or K+2, but design to prevent systematic over-delivery.
2. Capacity Planning
Quick math to drive storage choices:
- 2M reserve requests/sec × 3 cap checks per request = 6M lookups/sec
- Hot user-campaign pairs: assume 10M active users × 100 campaigns they might see = 1B possible pairs, but sparse — maybe 100M pairs with any activity in a given hour
- Per pair, per window: need to track impression timestamps or counts
- Latency budget: 2ms p99 end-to-end means <1ms for storage access at p99
This rules out database round-trips and points toward in-memory stores.
3. Data Model: Rolling Window Counts
Challenge: "Last N hours" requires knowing impression times, but storing every timestamp per user-campaign pair doesn't scale.
Approach: Sliding Window with Buckets
Instead of exact timestamps, partition each window into small buckets:
- For a 1-hour cap, use 60 one-minute buckets
- For a 24-hour cap, use 24 one-hour buckets (or 144 ten-minute buckets for finer granularity)
Each bucket stores a count. To compute "impressions in last 1 hour," sum all buckets whose timestamp falls in the window.
Data structure per (user, campaign, window):
{
buckets: [(timestamp: 1640000000, count: 3), (timestamp: 1640000060, count: 5), ...],
pending_reservations: 2
}
Tradeoff: This approximates the rolling window with bucket-width granularity. A 1-minute bucket for a 1-hour window means up to 1 minute of "slop." For a 24-hour cap, this is negligible.
Why not exact timestamps? Storing every impression timestamp requires unbounded list growth and O(N) read complexity. Bucketing gives O(W/B) where W is window size and B is bucket size — constant for our purposes.
4. Storage: Redis with Lua
Choice: Redis Cluster
- Sub-millisecond p99 latency at millions of QPS
- Lua scripting for atomic read-modify-write operations
- Built-in TTL for automatic expiry
- Mature sharding via hash slots
Alternative considered: In-memory service (custom Go/Rust process). Pros: lower latency ceiling, no network hop. Cons: harder operational story (replication, resharding, durability). Redis gives us proven infrastructure.
5. API Design
Reserve API
POST /reserve
{
user_id: "u123",
campaign_id: "c456",
request_id: "req_789", // idempotency key
caps: [
{window_seconds: 3600, max_impressions: 3},
{window_seconds: 86400, max_impressions: 8}
]
}
Response:
{
allowed: true,
reservation_token: "res_abc",
expires_at: 1640000120
}
Confirm API
POST /confirm
{
reservation_token: "res_abc",
user_id: "u123",
campaign_id: "c456",
timestamp: 1640000100
}
Idempotency: request_id in reserve and reservation_token in confirm prevent double-counting from retries.
6. Reserve Flow (Read Path)
- Hash
user_idto determine Redis shard - Execute Lua script atomically:
- For each cap window, sum buckets in range
- Add pending_reservations to current count
- If total < limit for all windows: increment pending_reservations, return success
- Otherwise: return denied
- Write reservation metadata (token → user/campaign/expiry) with 60-second TTL
Lua pseudo-code:
for each window in caps:
current_count = sum(buckets in [now - window, now])
total = current_count + pending_reservations
if total >= window.max_impressions:
return {allowed: false}
pending_reservations += 1
return {allowed: true, token: generate_token()}
Atomicity: Lua scripts execute atomically in Redis, so no race between check and increment.
7. Confirm Flow (Write Path)
- Validate reservation token hasn't expired
- Execute Lua script:
- Determine which bucket the timestamp falls into
- Increment that bucket's count
- Decrement pending_reservations
- Set TTL on the bucket to (window_size + bucket_size)
Handling late events: If confirm arrives after reservation expired, still record the impression but don't decrement pending (it already expired). The count still matters for future reserve calls.
Out-of-order events: Buckets are indexed by impression timestamp (from the event), not arrival time, so late events land in the correct bucket.
8. Sharding Strategy
Partition by user_id: Hash user ID to Redis shard. This keeps all of a user's counters on one shard, making reserve operations local (no distributed transaction).
Hot keys: A celebrity user or bot might hammer one shard. Mitigation:
- Detect hot keys via Redis
MONITORor client-side tracking - Apply rate limiting upstream for suspicious patterns
- For legitimate high-volume users, consider splitting their state across sub-shards with a secondary hash on campaign_id
Resharding: Redis Cluster supports live slot migration. During migration, briefly serve both old and new shards (read from both, write to new).
9. Expiry and Cleanup
- Bucket TTL: Set to
window_size + bucket_width. After this time, the bucket can't affect any future window query. - Reservation TTL: 60 seconds. If no confirm arrives, pending_reservations automatically decrements via a separate cleanup job that scans for expired reservations (or use Redis keyspace notifications).
- Graceful degradation: If cleanup lags, pending_reservations might stay artificially high, causing under-delivery. Monitor this metric.
10. Failure Modes and Mitigations
| Failure | Impact | Mitigation |
|---|---|---|
| Redis shard down | Reserve calls fail for affected users | Fail open (allow impressions) with fallback flag; alert immediately |
| Network partition | Split-brain: two regions both allow impressions | Accept bounded over-delivery; reconcile later via impression log |
| Confirm lost | Pending reservation never releases | TTL expires reservation; worst case is K-1 effective cap until expiry |
| Clock skew | Buckets misaligned across servers | Use a central time service; tolerate small skew (part of bucket granularity) |
| Bad cap config | Cap of 0 or negative window | Validate caps at config time; fail reserve calls with invalid caps |
Fail-open policy: When the cap store is unreachable, serve ads. This prioritizes revenue over perfect frequency control. For regulated caps (e.g., alcohol ad limits), fail closed instead.
11. Monitoring and Alerting
Correctness metrics (compare against authoritative impression log):
- Over-delivery rate: Join impression log with cap configs; measure % of users who received >K impressions in any window
- Under-delivery rate: Identify reserve denials where user was actually under cap (requires logging denials)
System health metrics:
- Reserve latency (p50, p99, p999) per shard
- Reserve QPS and denial rate per campaign
- Pending reservations (should be low and stable)
- Redis memory utilization per shard
- Hot key detection (top 1% of user_ids by QPS)
Alerts:
- p99 latency > 2ms (investigate hot shards or GC pauses)
- Over-delivery rate > 5% for any campaign (consistency issue)
- Shard memory > 80% (scale vertically or reshard)
12. Multi-Region Considerations
If serving happens in multiple regions:
- Option A: Regional cap stores — each region enforces independently. Simple, low latency, but K becomes K-per-region (higher total).
- Option B: Global cap store — single Redis cluster, cross-region latency. Violates latency budget unless using edge caching.
- Recommendation: Regional stores with async reconciliation. If a user's global count approaches K, propagate stricter caps to other regions.
13. Extensions and Tradeoffs
- Multiple dimensions (user+advertiser, user+creative): Same design, just additional keys. Each dimension is independent.
- Strict consistency: Replace Redis with a consensus system (Raft-based KV store). Latency increases to ~5-10ms. Only do this for regulated caps.
- Rebuild from log: Periodically recompute counts from the authoritative impression log to correct drift. Run offline, swap in new cap store.
This design balances sub-millisecond latency with high availability and eventual consistency, accepting bounded over-delivery as a reasonable tradeoff for the scale and latency requirements of real-time ad serving.