KatInterview

Per-User Impression Limits Over a Sliding Time Window

System DesignModel answer
MediumModel answerSystem Designsystem-designrate-limitingsliding-window

Last 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:

  1. Requirements and scale assumptions: what you would clarify up front and which numbers you would assume (users, request rate, latency budget, longest window).
  2. Read path: how the "can this ad be shown?" decision is made.
  3. Write path: how an impression is recorded after it is served.
  4. Data models: how limit definitions and per-user impression history are stored.
  5. Correctness under load: how you prevent users from exceeding their limits when many requests arrive at once.
  6. 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.