KatInterview

Two-Tier API Rate Limiter with a Sliding Window

Data Structure DesignModel answer
MediumModel answerData Structure Designrate-limitingconcurrencysliding-window

Last updated

Design a thread-safe rate limiter that enforces both a per-endpoint quota and a shared global quota using a rolling time window.

Two-Tier API Rate Limiter with a Sliding Window

Your team operates an API gateway that needs to control traffic at two levels simultaneously: no single endpoint should be hammered beyond its own capacity, and the entire service should not receive more requests than it can handle overall.

Implement a RateLimiter class with the following interface:

class RateLimiter:
    def __init__(self, global_limit: int, endpoint_limits: dict[str, int], window_seconds: int):
        """
        global_limit     – maximum requests allowed across all endpoints combined,
                           within any rolling window of window_seconds.
        endpoint_limits  – per-path caps, e.g. {"/login": 10}.
        window_seconds   – width of the rolling window (positive integer).
        """

    def allow_request(self, endpoint: str) -> bool:
        """
        Return True if the request may proceed, False if it should be dropped.
        Must be safe to call from multiple threads concurrently.
        """

Behaviour rules

  1. Both limits must pass. A request to a configured endpoint is allowed only when it fits under that endpoint's cap and under the global cap. Exceeding either one causes rejection.
  2. Sliding window. At the moment a request arrives (time T), the relevant window is [T − window_seconds, T]. A request from exactly T − window_seconds is still inside the window.
  3. Rejected requests are not counted. Only admitted requests consume quota. A client retrying a rejected call does not dig itself into a deeper hole.
  4. Unknown endpoints are subject only to the global limit; they have no per-endpoint cap.
  5. Memory must stay bounded. Do not retain timestamps that have scrolled outside every relevant window.
  6. Thread safety. Concurrent calls to allow_request must never produce a race condition that lets more requests through than either limit allows.

Example

global_limit    = 100
endpoint_limits = {"/login": 10}
window_seconds  = 10

A call to allow_request("/login") at time t = 5 is allowed when:

  • the number of admitted /login requests in the interval [-5, 5] is fewer than 10, and
  • the number of admitted requests across all endpoints in that same interval is fewer than 100.

Constraints

  • window_seconds is a positive integer.
  • global_limit and any endpoint limit may be 0 (every request is rejected).
  • The implementation must handle high concurrency with minimal lock contention.
  • You may use standard library modules (threading, collections, time).

Hints

Hint 1

A sliding-window log stores the actual timestamps of admitted requests in a deque. After pruning entries older than `now − window`, the length of the deque is the exact request count for the current window — no arithmetic required.

Hint 2

You need two locks: one per endpoint and one global. Always acquire them in the same order (endpoint first, then global) on every code path. A consistent acquisition order makes deadlock structurally impossible.

Hint 3

Do a cheap pre-check under just the endpoint lock before you ever touch the global lock. If the endpoint is already at its limit you can reject immediately, sparing the shared global lock from the extra contention that comes from hot, throttled endpoints.