Design a Slot-Filling Ad Service with Frequency Caps
System DesignModel answerLast updated
Design a production HTTP API that assigns ads to page slots while enforcing per-user display limits correctly under concurrency and retries.
Design a Slot-Filling Ad Service with Frequency Caps
An upstream targeting system has already ranked and filtered a set of candidate ads for a given user. Your job is to build the service that takes those candidates and maps them onto the available page slots — top, sidebar, bottom, and so on — while respecting each ad's configured per-user display limit (a frequency cap). The assignment must be random among eligible ads, no ad may appear in more than one slot per response, and every successful response must increment the user's display counts so future calls respect the cap.
You are not being asked to write the assignment algorithm. You are being asked to design the API and the surrounding system that makes it production-ready.
Address each of the following:
- Protocol and endpoint shape — REST, gRPC, or something else? Why? How many endpoints, and what do the URLs look like?
- HTTP method choice — Which method drives an assignment, and what is your reasoning?
- Request and response schemas — What fields does each carry? How do you represent a slot that could not be filled?
- Per-user display-count storage — Where does this state live? What data structure and key scheme do you use? Does the store need a TTL?
- Concurrency correctness — A user can have several in-flight requests at the same time (multiple tabs, fast reloads). How do you prevent cap violations?
- Safe retries — Assignment mutates state. How do you let clients retry without double-counting an impression?
- Error taxonomy — What errors does the API surface, and how do clients distinguish a transport failure from a business-level outcome like "no eligible ad"?
- Reliability and observability — What does the service need to be trustworthy in production?
Constraints and assumptions
Treat these as defaults; flag anything you'd confirm with the interviewer:
- Candidate ads and their cap values are supplied in the request body by the caller. Your service does not fetch or rank them.
- Exceeding a frequency cap is a correctness bug, not a soft quality issue — billing and fraud systems depend on it.
- A single user may have multiple simultaneous in-flight requests at any moment.
- The service sits on a high-QPS internal ad-serving path; p99 latency on the state store matters.
- Both web frontends and backend services call this API.
Good clarifying questions to raise
- Over what window does the display limit apply — session, calendar day, lifetime? Does the answer imply a TTL on stored counts?
- If no eligible ad exists for a slot, should that slot be left empty or should the entire request fail?
- Who calls this API — trusted internal services, or untrusted external clients? That determines whether it is safe to accept cap values from the request body.
- Do downstream systems (billing, analytics) need a durable record of every impression, or is the in-memory count enough?
- What are the QPS and latency targets?
Hints
Hint 1
Start by classifying the core operation: does it read state, write state, or both? That classification drives your HTTP method choice, your idempotency story, and your storage strategy all at once.
Hint 2
Think carefully about what 'concurrent requests for the same user' actually means for a counter — a read followed by a separate write is not atomic. What primitives does your chosen store expose that let you collapse those two steps?
Hint 3
An idempotency key solves the retry problem, but where you store that key and for how long has its own trade-offs. Think through what happens if the service crashes after writing state but before sending the response.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer looks like
1. Protocol and endpoint shape
REST over HTTPS is the right default for this service. It is universally supported by web and backend clients, plays well with standard load balancers and API gateways, and maps cleanly onto the resource model here. gRPC would be worth considering if this were a pure service-to-service call with strict binary payload constraints, but for a mixed-client ad-serving path the operational overhead isn't justified.
One endpoint covers the use case:
POST /v1/users/{userId}/ad-assignments
Scoping the path under a user ID makes it natural to route, log, and rate-limit by user. Versioning at the path level (v1) lets you evolve the contract without a flag day.
2. HTTP method choice
POST, not GET. The operation is a side-effecting write: it consumes ad budget, increments display counters, and produces a one-time random result. GET must be safe and idempotent by the HTTP spec; this operation is neither. Using GET would also risk the assignment being triggered by prefetch, caching proxies, or log replay. POST with an explicit idempotency key (see §6) gives you the right semantics.
3. Request and response schemas
Request body (JSON):
{
"slots": ["top", "sidebar", "bottom"],
"candidateAds": [
{ "adId": "ad_123", "creativeUrl": "...", "displayLimit": 3 },
{ "adId": "ad_456", "creativeUrl": "...", "displayLimit": 5 }
],
"context": { "pageType": "search", "locale": "en-US" }
}
displayLimit is the per-user cap for that ad over the agreed window. context is forwarded to logging and analytics but not used in assignment logic.
Response body:
{
"assignmentId": "asgn_789xyz",
"assignments": {
"top": { "adId": "ad_123", "creativeUrl": "..." },
"sidebar": null,
"bottom": { "adId": "ad_456", "creativeUrl": "..." }
}
}
Every requested slot appears in the response — slots that could not be filled carry null rather than being silently omitted. This matters: a client that receives no key for sidebar cannot tell whether it was unfilled or whether the field was dropped by a serializer. Explicit nulls are unambiguous.
4. Per-user display-count storage
Redis is the right store for this workload. It supports atomic increment commands natively, has sub-millisecond p99 latency at scale, and TTL-per-key maps directly onto the cap window (e.g., EXPIRE a key at midnight for a daily cap). A relational database could enforce correctness with transactions, but the extra round-trip latency and connection overhead are hard to justify on a high-QPS serving path. DynamoDB or a similar document store is an acceptable alternative if you need multi-region replication, at the cost of more complex atomic update patterns.
Key scheme:
freq:{userId}:{adId}:{windowDate} → integer (current display count)
TTL is set to the end of the current cap window. On expiry Redis drops the key automatically, which resets the count without any background job.
5. Concurrency correctness
A naive read-check-increment sequence has a TOCTOU race: two concurrent requests for the same user can both read a count of 2 against a cap of 3, both decide the ad is eligible, both increment to 3 and 4 — violating the cap.
The fix is atomic conditional increment with Lua scripting in Redis:
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local cur = tonumber(redis.call("GET", key) or "0")
if cur >= limit then
return -1 -- cap exceeded, caller must skip this ad
end
return redis.call("INCR", key)
Because Lua scripts in Redis execute atomically (single-threaded eval), no two requests can interleave inside this block. The service runs the script for each candidate ad during the assignment loop, removing capped ads from the eligible set before sampling. If the eligible set is smaller than the number of slots, remaining slots get null.
An alternative is optimistic locking with WATCH/MULTI/EXEC, but it requires retries on contention; the Lua approach is simpler and avoids that retry loop under high concurrency.
6. Safe retries and idempotency
Clients must send an Idempotency-Key header (a UUID generated by the caller before the first attempt):
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
On receipt, the service checks a short-lived Redis key (idem:{idempotencyKey}). If found, it returns the cached response without touching counters. If not found, it runs the assignment, stores the result under that key with a TTL of ~24 hours, and returns the fresh response.
The tricky edge case is a crash between writing counters and writing the idempotency record. To handle this, write the idempotency record first (with a "pending" marker), then increment counters, then mark the record "complete" with the serialized response. A retry that finds a "pending" record can either wait briefly or treat it as a conflict and return 409.
7. Error taxonomy
| Scenario | HTTP status | Notes |
|---|---|---|
| Invalid schema / missing fields | 400 Bad Request | Return field-level errors |
| Missing or invalid auth | 401 Unauthorized | |
userId not authorized for caller | 403 Forbidden | |
| State store unavailable | 503 Service Unavailable | With Retry-After |
| No eligible ad for any slot | 200 OK | All slots are null; this is a valid business outcome, not an error |
| Duplicate idempotency key in flight | 409 Conflict |
"No eligible ad" is not a 4xx. It is a normal outcome the caller must handle. Returning a 4xx here would cause clients to log false alerts and makes the error surface misleading.
8. Reliability and observability
Metrics to emit per request: assignment latency (p50/p99), eligible-ad count after cap filtering, fill rate per slot, Redis operation latency, and idempotency cache hit rate.
Structured logging: every response should carry assignmentId, userId, slot fill outcomes, and which ads were skipped due to cap exhaustion. This makes debugging impression discrepancies tractable.
Durable impression events: emit a message to a stream (Kafka or Kinesis) for each filled slot. Downstream billing and fraud systems consume from the stream rather than querying the service, which decouples them from the serving path.
Graceful degradation: if Redis is unavailable, the service can fail open (serve ads without enforcing caps) or fail closed (return 503). For a system where cap violations are correctness bugs, fail closed is safer — document this explicitly and set a tight circuit-breaker threshold so transient Redis blips don't cause prolonged outages.
Common mistakes to avoid:
- Using
GETbecause "we're just reading page content" — the side effect makes this aPOST. - Silently omitting unfilled slots from the response object.
- Trusting a read-then-write counter pattern without atomic primitives.
- Conflating transport errors with business outcomes in the error codes.
- Forgetting the idempotency record TTL, which would allow the cache to grow unbounded.