KatInterview

Per-User Rolling Quota Gate with Concurrent Access

Data Structure DesignModel answer
HardModel answerData Structure Designrate-limitersliding-windowdeque

Last updated

Design a thread-safe class that caps how many requests each user may make in any trailing time interval, avoiding the burst problem of fixed windows, with sub-linear cost per check.

Rolling Quota Gate

Build a RateLimiter class that enforces a per-user quota over a trailing time interval. A fixed-window counter is not acceptable, because it lets a user send a full quota just before a boundary and another full quota just after it. Your design must make sure that any interval of the configured length contains no more than the allowed number of accepted requests.

Interface

  • RateLimiter(capacity, window_size_seconds) creates a limiter that allows at most capacity accepted requests per user in any interval of window_size_seconds seconds.
  • allow(user_id) decides whether the current request from user_id is accepted. It returns True if so and False if the user is over quota.

Requirements

  • Quotas are tracked independently per user.
  • The class must be safe to call from many threads at once.
  • The cost of allow() must be better than O(N), where N is the number of requests currently inside the window.
  • You may use time.time() for the current time in seconds.
  • A request recorded exactly window_size_seconds ago no longer counts against the quota.

Example

# Up to 2 requests per 5 seconds
limiter = RateLimiter(2, 5)

limiter.allow(1)   # True
limiter.allow(1)   # True
limiter.allow(1)   # False  (quota used up)
# ...5 seconds go by...
limiter.allow(1)   # True

What to discuss

  • What do you store for each user, and why?
  • How do you discard outdated entries cheaply?
  • Which locking strategy do you pick, and what does it cost in contention?
  • Should rejected requests count toward the quota?
  • How would the design change if the service ran on many machines?

Provide the implementation, explain its complexity, and justify your concurrency approach.

Hints

Hint 1

Keep a time-ordered queue of timestamps per user. Because time only moves forward, the oldest entries are always at one end, so you never need to scan the whole collection.

Hint 2

Think about which requests should be recorded. If rejected calls were also stored, a client that keeps retrying would never recover. Record only accepted requests.

Hint 3

Evicting stale timestamps, checking the size and appending a new one form a check-then-act sequence. Protect it with a lock per user, and guard the creation of a user's entry with a short global lock. Read the clock while holding the user lock so stored timestamps stay in order.