KatInterview

Build a Concurrent Multi-Constraint Rate Limiter

Data Structure DesignModel answer
HardModel answerData Structure Designconcurrencyrate-limitingsliding-window

Last updated

Design a thread-safe class that enforces several independent rate limits simultaneously, with atomic all-or-nothing permit acquisition and rollback on failure.

Concurrent Multi-Constraint Rate Limiter

A rate limiter controls how many requests a system allows over time. Your task is to build one that can enforce several rules at once — for example, "no more than 10 requests per second AND no more than 100 requests per minute" — in a multithreaded environment.

What to implement

A RateLimiter class with the following interface:

class RateLimiter:
    def add_rule(self, capacity: int, window_ms: int) -> int: ...
    def try_acquire(self) -> bool: ...
    def release(self) -> bool: ...

add_rule(capacity, window_ms) Register a new constraint: at most capacity requests are allowed within any rolling window_ms-millisecond period. Returns an identifier for the rule. Raises ValueError if either argument is not a positive integer.

try_acquire() Try to claim a permit. A permit is granted only when every registered rule has room. Returns True on success, False otherwise. Must be non-blocking — never wait for capacity to free up.

release() Call this when a request that was successfully acquired later fails (for example, the handler raises an exception). It returns the permit to the pool so that capacity is not wasted. Returns True if a permit was successfully returned, False if there was nothing to release.

Constraints

  • Between 1 and 10 rules may be active at any time.
  • Rules may be added dynamically after the limiter is already running.
  • try_acquire must be atomic across all rules: if any single rule cannot accommodate the request, no permits are consumed anywhere — not even in the rules that had room.
  • The implementation must be correct under high concurrency (many threads calling try_acquire simultaneously).

Usage example

limiter = RateLimiter()
limiter.add_rule(10, 1000)   # max 10 requests per second
limiter.add_rule(100, 60000) # max 100 requests per minute

if limiter.try_acquire():
    try:
        process_request()
    except Exception:
        limiter.release()  # failed — give the slot back

Edge cases to handle

  • release() is called when no permit is currently outstanding (e.g., called twice, or never acquired).
  • A rule is removed between the time a permit is acquired and the time release() is called.
  • Many threads attempt try_acquire at the exact same millisecond.
  • try_acquire is called when no rules have been registered yet.
  • A permit's window expires before release() is called — the refund should not push the count below zero.

What is expected

A working Python implementation with a brief explanation of:

  • the data structure chosen for each rule's window tracking
  • how atomicity is guaranteed across multiple rules
  • how release() correctly handles the edge cases above
  • time and space complexity

You do not need to handle distributed deployments, but be ready to discuss how you would extend the design to one.

Hints

Hint 1

A sliding window log — a deque of grant timestamps per rule — lets you count how many requests fall inside the current window just by discarding entries older than `now - window_ms`. Consider what that means for both checking and committing a permit.

Hint 2

Split `try_acquire` into two phases inside one critical section: first *read* every rule to see whether all of them have room, then — only if all pass — *write* the timestamp to every rule. This separates the decision from the side effect.

Hint 3

To make `release()` work correctly, record a small receipt at acquire time: the timestamp and the set of rule IDs that were charged. On release, look up that receipt and remove the timestamp only from rules that are still present and whose window has not yet expired.