Global and Per-Domain Fixed-Window Rate Limiter

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Design an in-process HTTP rate limiter (and its ASGI middleware integration) that enforces two independent epoch-aligned fixed-window quotas on every incoming request:

  1. Global quota: At most global_limit accepted requests within each global_window_sec-second bucket across all client domains combined.
  2. Per-domain quota: At most domain_limit accepted requests within each domain_window_sec-second bucket for any single client domain.

For a timestamp t (in seconds since the Unix epoch) and window duration w seconds, the active bucket index is int(t // w). A request is admitted only when both buckets have remaining capacity:

  • Admitted request: Atomically increment both the global counter and that domain's counter, returning [True, None] (or (True, None) from DualFixedWindowRateLimiter.is_allowed).
  • Rejected request: Increment neither counter (and short-circuit with HTTP 429 in middleware without calling downstream handlers). If the global bucket is full, return [False, "global"]; otherwise, if the domain bucket is full, return [False, "domain"] (so "global" takes precedence whenever both limits are simultaneously exhausted).
  • Lazy rollover & concurrency safety: Discard expired bucket counts lazily when the bucket index advances so idle domains do not leak memory, and synchronize state access safely across concurrent callers.

Implement DualFixedWindowRateLimiter (defaulting to 100 per 60s globally and 3 per 1s per domain, plus optional ASGI middleware helpers) together with the replay entrypoint tested by the judge:

def dual_fixed_window_rate_limiter(
    global_limit: int,
    global_window_sec: int,
    domain_limit: int,
    domain_window_sec: int,
    operations: List[str],
    arguments: List[List],
) -> List[List]:

Each entry i has operations[i] == "is_allowed" and arguments[i] equal to [domain, now] (or [domain], in which case now defaults to time.time()), returning [allowed, reason] for each call in order.

Examples

Example 1

Input:
  global_limit = 50, global_window_sec = 30
  domain_limit = 2,  domain_window_sec = 5
  operations = ["is_allowed", "is_allowed", "is_allowed", "is_allowed"]
  arguments  = [
      ["svc.alpha.io", 20.0],
      ["svc.alpha.io", 22.4],
      ["svc.alpha.io", 24.9],
      ["svc.alpha.io", 25.0],
  ]
Output: [[True, None], [True, None], [False, "domain"], [True, None]]

Timestamps 20.0, 22.4, and 24.9 all fall inside 5-second domain bucket int(t // 5) == 4 and 30-second global bucket 0. The first two calls succeed (2 / 2 domain quota used), the third at 24.9 is blocked with "domain" without consuming global quota, and 25.0 enters domain bucket 5, resetting the per-domain tally and succeeding.

Example 2

Input:
  global_limit = 3, global_window_sec = 10
  domain_limit = 2, domain_window_sec = 2
  operations = ["is_allowed", "is_allowed", "is_allowed", "is_allowed", "is_allowed"]
  arguments  = [
      ["tenant1.net", 4.0],
      ["tenant2.net", 4.5],
      ["tenant3.net", 5.2],
      ["tenant1.net", 9.8],
      ["tenant1.net", 10.0],
  ]
Output: [[True, None], [True, None], [True, None], [False, "global"], [True, None]]

Three distinct domains consume all 3 slots of global bucket int(t // 10) == 0 while staying well under their 2-per-2s domain caps. At 9.8, tenant1.net is in a fresh domain bucket (4) yet global bucket 0 is full, returning [False, "global"]. At 10.0, global bucket 1 begins and the call succeeds.

Constraints

  • global_limit >= 0 and domain_limit >= 0 (0 rejects every call immediately with the corresponding scope).
  • global_window_sec >= 1 and domain_window_sec >= 1 (non-positive window sizes in DualFixedWindowRateLimiter should raise ValueError).
  • 0 <= len(operations) == len(arguments) <= 10^4.
  • Explicit now values in a replay sequence are non-negative floats (int or float) in non-decreasing order; omitted now defaults to the system clock.
  • In HTTP middleware usage, missing or malformed Host headers should normalize safely (e.g., to "unknown") rather than crashing.

Step-by-step walkthrough

  1. Restate the problem and clarify edge rules

    Every incoming HTTP request must clear two independent fixed-window rate limits at the same time before reaching any FastAPI route handler:

    1. Global limit: At most global_limit (default 100) requests per global_window_sec (default 60 seconds) across all clients combined.
    2. Per-domain limit: At most domain_limit (default 3) requests per domain_window_sec (default 1 second) for any single client domain.

    Each fixed window is aligned to Unix epoch (t = 0), with bucket index window_id = int(now // window_size_seconds):

    Epoch time (sec):  0        1        2   ...  10       11       12  ...  60       61
    Domain windows:    |--id 0--|--id 1--|   ...  |--id10--|--id11--|   ...  |--id60--|
    Global windows:    |<----------------- global window id 0 ---------------->|<-- id 1 ...
    

    We need three pieces that fit cleanly together: - DualFixedWindowRateLimiter.is_allowed(domain, now=None): Returns (True, None) and increments both counters if permitted, or returns (False, "global") / (False, "domain") and increments neither counter if rejected. - RateLimitMiddleware + domain_from_host: Extracts the domain from the Host header, checks is_allowed, and immediately returns 429 Too Many Requests (naming which limit failed) when rejected. - dual_fixed_window_rate_limiter(...): The judge harness wrapper that replays operations and arguments and collects [allowed, reason] lists.

    Two boundary details are worth stating explicitly up front: - Tie-breaker when both limits are full: Check the global limit first and return "global", matching the order in the specification. - Monotonic timestamps: Fixed-window state tracks only the active window, assuming non-decreasing timestamps; in live traffic we guarantee this by reading time.time() inside the lock.

  2. Why logging every timestamp fails, and the lazy-counter idea

    A literal brute-force implementation appends every accepted (domain, timestamp) pair to a growing list, scanning the whole list on each request to count how many past requests share the current global_window_id and domain_window_id. That works as a small test oracle, but in production each check degrades to O(total_accepted_requests) time and the list grows without bound—violating the memory-leak requirement.

    Instead, notice that past windows never affect future decisions. For the global limit, we only need two values: global_window_id and global_count. Whenever a request arrives at time now, we compute int(now // global_window_sec); if it differs from global_window_id, the old window has ended, so we overwrite global_window_id and reset global_count = 0 on the spot. This technique—updating expired state only when the next request touches it rather than running background timers—is called a lazy reset.

    Even better, because epoch alignment gives every domain the exact same window boundaries, we do not need a separate window ID per domain! One shared domain_window_id governs a plain dictionary domain_counts = {domain: count}:

    At t = 24.9 (5-second domain_window_id = 4):
      domain_counts = {"svc.alpha.io": 2, "quiet.client.io": 1}
    
    First request at t = 25.0 (current_domain_id = 5 != 4):
      domain_window_id = 5
      domain_counts = {}      <-- resets active domains AND evicts idle domains at once!
    

    Replacing the dictionary reference at rollover evicts inactive domains automatically without background cleanup threads.

  3. Build the limiter state and lazy rollover

    Initializing both window IDs to None guarantees that the very first request—even at now = 0.0 (window_id = 0)—sees 0 != None and initializes clean counters. We also guard against non-positive window durations in __init__.

    class DualFixedWindowRateLimiter:
        def __init__(
            self,
            global_limit: int = 100,
            global_window_sec: int = 60,
            domain_limit: int = 3,
            domain_window_sec: int = 1,
        ):
            if global_window_sec <= 0 or domain_window_sec <= 0:
                raise ValueError("window durations must be positive")
    
            self.global_limit = global_limit
            self.global_window_sec = global_window_sec
            self.domain_limit = domain_limit
            self.domain_window_sec = domain_window_sec
    
            # Global window state: current epoch bucket int(now // global_window_sec) and accepted count.
            # Initialized to None so the very first request always initializes a fresh window.
            self.global_window_id: Optional[int] = None
            self.global_count: int = 0
    
            # Per-domain window state: because all domains share epoch-aligned boundaries,
            # one domain_window_id governs the entire domain_counts dict {domain_str: count_int}.
            self.domain_window_id: Optional[int] = None
            self.domain_counts: Dict[str, int] = {}
    
            # Mutex protecting clock reads, window rollovers, limit checks, and counter increments.
            self.lock = threading.Lock()
    
        def _roll_windows(self, now: float) -> None:
            """Lazily reset global and/or per-domain counters whenever their epoch window ID changes."""
            current_global_id = int(now // self.global_window_sec)
            if current_global_id != self.global_window_id:
                self.global_window_id = current_global_id
                self.global_count = 0
    
            current_domain_id = int(now // self.domain_window_sec)
            if current_domain_id != self.domain_window_id:
                self.domain_window_id = current_domain_id
                # Every entry in domain_counts belonged to the old window; replacing the dict
                # resets active domains and evicts idle domains in one O(1) reference swap.
                self.domain_counts = {}
    
  4. Make check-and-increment atomic in `is_allowed`

    Three ordering rules inside is_allowed prevent subtle bugs:

    1. Check both limits before incrementing either counter. If we incremented global_count first and then rejected the request on domain_limit, rejected bursts from one noisy client would silently drain global quota for everyone else!
    2. Hold one threading.Lock across the entire check-and-commit. Without a mutex (mutual-exclusion lock ensuring only one thread enters the block at a time), two threads could both read count = 2 under limit = 3 and both admit a request, letting 4 through. Because nothing inside with self.lock: uses await, threading.Lock never blocks an asyncio event loop across I/O while also protecting FastAPI's worker thread pool for synchronous def routes.
    3. Read time.time() inside the lock when now is None. If Thread A read 10.999 outside the lock, got preempted while Thread B read 11.001 and rolled to window 11, Thread A waking up next would see 10 != 11, roll the limiter backward to window 10, and wipe out Thread B's count!
        def is_allowed(self, domain: str, now: Optional[float] = None) -> Tuple[bool, Optional[str]]:
            """Atomically check both fixed-window limits and consume 1 unit of each if permitted."""
            with self.lock:
                # Phase 1: Read wall clock inside the lock so a delayed thread with an older
                # timestamp cannot arrive second and roll a newer window backward.
                if now is None:
                    now = time.time()
    
                # Phase 2: Advance any expired fixed windows before reading counts.
                self._roll_windows(now)
    
                # Phase 3: Check BOTH limits before mutating either counter.
                # If both limits are exhausted, global is checked first and reported as 'global'.
                if self.global_count >= self.global_limit:
                    return False, "global"
    
                current_domain_count = self.domain_counts.get(domain, 0)
                if current_domain_count >= self.domain_limit:
                    return False, "domain"
    
                # Phase 4: Both checks passed—commit increments to both counters together.
                self.global_count += 1
                self.domain_counts[domain] = current_domain_count + 1
                return True, None
    
  5. Parse `Host` headers and build the ASGI middleware

    FastAPI runs atop ASGI (Asynchronous Server Gateway Interface, Python's async web protocol where an app is async def app(scope, receive, send)). Writing RateLimitMiddleware directly against ASGI avoids third-party imports in standalone environments and plugs into FastAPI via app.add_middleware(RateLimitMiddleware, limiter=DualFixedWindowRateLimiter()).

    First, domain_from_host normalizes Host headers so "SVC.Alpha.io:443" and "svc.alpha.io" map to the same bucket "svc.alpha.io", preserves bracketed IPv6 hosts like "[::1]:8000" -> "[::1]", and maps missing or malformed headers (None, "", ":8000", "[]", "bad host", non-numeric ports) to "unknown". Then RateLimitMiddleware lets non-HTTP scopes (lifespan, websockets) pass through, calls is_allowed, and on rejection sends HTTP 429 with both a human-readable JSON detail message and an x-ratelimit-scope header—never invoking self.app.

    REJECT_MESSAGES: Dict[str, str] = {
        "global": "Global rate limit exceeded",
        "domain": "Domain rate limit exceeded",
    }
    
    
    def domain_from_host(host: Optional[str]) -> str:
        """Normalize an HTTP Host header to a lowercase hostname without port, or 'unknown' if invalid."""
        if host is None:
            return "unknown"
    
        cleaned = host.strip().lower()
        if not cleaned:
            return "unknown"
    
        # Handle bracketed IPv6 literals such as "[::1]" or "[::1]:8000".
        if cleaned.startswith("["):
            close_bracket = cleaned.find("]")
            if close_bracket <= 1:
                return "unknown"
            ipv6_host = cleaned[: close_bracket + 1]
            remainder = cleaned[close_bracket + 1 :]
            if remainder == "" or (remainder.startswith(":") and remainder[1:].isdigit()):
                return ipv6_host
            return "unknown"
    
        # Handle standard "hostname" or "hostname:port" headers; reject extra colons or bad characters.
        parts = cleaned.split(":")
        if len(parts) > 2:
            return "unknown"
        hostname = parts[0]
        if len(parts) == 2 and parts[1] != "" and not parts[1].isdigit():
            return "unknown"
        if not hostname or any(ch.isspace() or ch in "/?#@\\" for ch in hostname):
            return "unknown"
        return hostname
    
    
    class RateLimitMiddleware:
        """Pure ASGI rate-limiting middleware for FastAPI / Starlette applications."""
    
        def __init__(self, app: Any, limiter: DualFixedWindowRateLimiter):
            self.app = app
            self.limiter = limiter
    
        async def __call__(self, scope: Dict[str, Any], receive: Any, send: Any) -> None:
            # Let non-HTTP ASGI events (lifespan startup/shutdown, websockets) pass straight through.
            if scope.get("type") != "http":
                await self.app(scope, receive, send)
                return
    
            # Extract the raw Host header from ASGI's list of (lowercased_bytes_name, bytes_value) pairs.
            raw_host: Optional[str] = None
            for header_name, header_value in scope.get("headers", []):
                if header_name == b"host":
                    raw_host = header_value.decode("latin-1")
                    break
    
            domain_key = domain_from_host(raw_host)
            allowed, reason = self.limiter.is_allowed(domain_key)
            if allowed:
                await self.app(scope, receive, send)
                return
    
            # Short-circuit with HTTP 429 Too Many Requests without invoking downstream handlers.
            assert reason is not None
            payload_bytes = json.dumps({"detail": REJECT_MESSAGES[reason]}).encode("utf-8")
            response_headers = [
                (b"content-type", b"application/json"),
                (b"content-length", str(len(payload_bytes)).encode("ascii")),
                (b"x-ratelimit-scope", reason.encode("ascii")),
            ]
            await send({"type": "http.response.start", "status": 429, "headers": response_headers})
            await send({"type": "http.response.body", "body": payload_bytes})
    
  6. Wire up the judge replay function

    The judge passes the four configuration integers plus parallel operations and arguments lists, expecting [allowed, reason] for each "is_allowed" call (with now optional when len(args) == 1):

    def dual_fixed_window_rate_limiter(
        global_limit: int,
        global_window_sec: int,
        domain_limit: int,
        domain_window_sec: int,
        operations: List[str],
        arguments: List[List],
    ) -> List[List]:
        """Judge entrypoint: configure a limiter and replay a sequence of is_allowed operations."""
        limiter = DualFixedWindowRateLimiter(
            global_limit=global_limit,
            global_window_sec=global_window_sec,
            domain_limit=domain_limit,
            domain_window_sec=domain_window_sec,
        )
    
        # results: list of [allowed_bool, reason_or_none] pairs matching each operation call.
        results: List[List[Any]] = []
        for operation, args in zip(operations, arguments):
            if operation != "is_allowed":
                raise ValueError(f"unknown operation: {operation}")
            domain = args[0]
            now = args[1] if len(args) > 1 else None
            allowed, reason = limiter.is_allowed(domain, now)
            results.append([allowed, reason])
        return results
    
  7. Trace Example 1 step by step

    Let us trace Example 1 (global = 50 / 30s, domain = 2 / 5s, domain d = "svc.alpha.io"):

    Call  now    global (id, cnt)  domain (id, cnt[d])  Decision           State after call
    ----  -----  ----------------  -------------------  -----------------  ------------------------
     1    20.00  (0, 0 < 50)       (4, 0 < 2)           [True, None]       global=1, cnt[d]=1
     2    22.40  (0, 1 < 50)       (4, 1 < 2)           [True, None]       global=2, cnt[d]=2
     3    24.90  (0, 2 < 50)       (4, 2 >= 2 FULL!)    [False, "domain"]  global=2, cnt[d]=2 (unchanged!)
     4    25.00  (0, 2 < 50)       (5 != 4 -> reset)    [True, None]       global=3, cnt[d]=1
    

    Notice two crucial details: at t = 24.9 the rejected 3rd request leaves global_count at 2, and at t = 25.0 int(25.0 // 5) = 5 clears domain_counts while int(25.0 // 30) = 0 keeps accumulating within global window 0.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    import json
    import threading
    import time
    
    
    class DualFixedWindowRateLimiter:
        def __init__(
            self,
            global_limit: int = 100,
            global_window_sec: int = 60,
            domain_limit: int = 3,
            domain_window_sec: int = 1,
        ):
            if global_window_sec <= 0 or domain_window_sec <= 0:
                raise ValueError("window durations must be positive")
    
            self.global_limit = global_limit
            self.global_window_sec = global_window_sec
            self.domain_limit = domain_limit
            self.domain_window_sec = domain_window_sec
    
            # Global window state: current epoch bucket int(now // global_window_sec) and accepted count.
            # Initialized to None so the very first request always initializes a fresh window.
            self.global_window_id: Optional[int] = None
            self.global_count: int = 0
    
            # Per-domain window state: because all domains share epoch-aligned boundaries,
            # one domain_window_id governs the entire domain_counts dict {domain_str: count_int}.
            self.domain_window_id: Optional[int] = None
            self.domain_counts: Dict[str, int] = {}
    
            # Mutex protecting clock reads, window rollovers, limit checks, and counter increments.
            self.lock = threading.Lock()
    
        def _roll_windows(self, now: float) -> None:
            """Lazily reset global and/or per-domain counters whenever their epoch window ID changes."""
            current_global_id = int(now // self.global_window_sec)
            if current_global_id != self.global_window_id:
                self.global_window_id = current_global_id
                self.global_count = 0
    
            current_domain_id = int(now // self.domain_window_sec)
            if current_domain_id != self.domain_window_id:
                self.domain_window_id = current_domain_id
                # Every entry in domain_counts belonged to the old window; replacing the dict
                # resets active domains and evicts idle domains in one O(1) reference swap.
                self.domain_counts = {}
    
        def is_allowed(self, domain: str, now: Optional[float] = None) -> Tuple[bool, Optional[str]]:
            """Atomically check both fixed-window limits and consume 1 unit of each if permitted."""
            with self.lock:
                # Phase 1: Read wall clock inside the lock so a delayed thread with an older
                # timestamp cannot arrive second and roll a newer window backward.
                if now is None:
                    now = time.time()
    
                # Phase 2: Advance any expired fixed windows before reading counts.
                self._roll_windows(now)
    
                # Phase 3: Check BOTH limits before mutating either counter.
                # If both limits are exhausted, global is checked first and reported as 'global'.
                if self.global_count >= self.global_limit:
                    return False, "global"
    
                current_domain_count = self.domain_counts.get(domain, 0)
                if current_domain_count >= self.domain_limit:
                    return False, "domain"
    
                # Phase 4: Both checks passed—commit increments to both counters together.
                self.global_count += 1
                self.domain_counts[domain] = current_domain_count + 1
                return True, None
    
    
    REJECT_MESSAGES: Dict[str, str] = {
        "global": "Global rate limit exceeded",
        "domain": "Domain rate limit exceeded",
    }
    
    
    def domain_from_host(host: Optional[str]) -> str:
        """Normalize an HTTP Host header to a lowercase hostname without port, or 'unknown' if invalid."""
        if host is None:
            return "unknown"
    
        cleaned = host.strip().lower()
        if not cleaned:
            return "unknown"
    
        # Handle bracketed IPv6 literals such as "[::1]" or "[::1]:8000".
        if cleaned.startswith("["):
            close_bracket = cleaned.find("]")
            if close_bracket <= 1:
                return "unknown"
            ipv6_host = cleaned[: close_bracket + 1]
            remainder = cleaned[close_bracket + 1 :]
            if remainder == "" or (remainder.startswith(":") and remainder[1:].isdigit()):
                return ipv6_host
            return "unknown"
    
        # Handle standard "hostname" or "hostname:port" headers; reject extra colons or bad characters.
        parts = cleaned.split(":")
        if len(parts) > 2:
            return "unknown"
        hostname = parts[0]
        if len(parts) == 2 and parts[1] != "" and not parts[1].isdigit():
            return "unknown"
        if not hostname or any(ch.isspace() or ch in "/?#@\\" for ch in hostname):
            return "unknown"
        return hostname
    
    
    class RateLimitMiddleware:
        """Pure ASGI rate-limiting middleware for FastAPI / Starlette applications."""
    
        def __init__(self, app: Any, limiter: DualFixedWindowRateLimiter):
            self.app = app
            self.limiter = limiter
    
        async def __call__(self, scope: Dict[str, Any], receive: Any, send: Any) -> None:
            # Let non-HTTP ASGI events (lifespan startup/shutdown, websockets) pass straight through.
            if scope.get("type") != "http":
                await self.app(scope, receive, send)
                return
    
            # Extract the raw Host header from ASGI's list of (lowercased_bytes_name, bytes_value) pairs.
            raw_host: Optional[str] = None
            for header_name, header_value in scope.get("headers", []):
                if header_name == b"host":
                    raw_host = header_value.decode("latin-1")
                    break
    
            domain_key = domain_from_host(raw_host)
            allowed, reason = self.limiter.is_allowed(domain_key)
            if allowed:
                await self.app(scope, receive, send)
                return
    
            # Short-circuit with HTTP 429 Too Many Requests without invoking downstream handlers.
            assert reason is not None
            payload_bytes = json.dumps({"detail": REJECT_MESSAGES[reason]}).encode("utf-8")
            response_headers = [
                (b"content-type", b"application/json"),
                (b"content-length", str(len(payload_bytes)).encode("ascii")),
                (b"x-ratelimit-scope", reason.encode("ascii")),
            ]
            await send({"type": "http.response.start", "status": 429, "headers": response_headers})
            await send({"type": "http.response.body", "body": payload_bytes})
    
    
    def dual_fixed_window_rate_limiter(
        global_limit: int,
        global_window_sec: int,
        domain_limit: int,
        domain_window_sec: int,
        operations: List[str],
        arguments: List[List],
    ) -> List[List]:
        """Judge entrypoint: configure a limiter and replay a sequence of is_allowed operations."""
        limiter = DualFixedWindowRateLimiter(
            global_limit=global_limit,
            global_window_sec=global_window_sec,
            domain_limit=domain_limit,
            domain_window_sec=domain_window_sec,
        )
    
        # results: list of [allowed_bool, reason_or_none] pairs matching each operation call.
        results: List[List[Any]] = []
        for operation, args in zip(operations, arguments):
            if operation != "is_allowed":
                raise ValueError(f"unknown operation: {operation}")
            domain = args[0]
            now = args[1] if len(args) > 1 else None
            allowed, reason = limiter.is_allowed(domain, now)
            results.append([allowed, reason])
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture an event venue with two turnstiles in series: a main entrance capped at global_limit visitors per global_window_sec, and tenant gates capped at domain_limit visitors from the same Host domain per domain_window_sec. A fixed-window counter tracks each quota by pairing an epoch bucket index (int(now // window_sec)) with an integer count; as soon as the first visitor of the next bucket arrives, the guard notices the bucket index has changed and swaps in a clean counter sheet on the spot—a lazy reset requiring zero background timers. Crucially, both turnstiles advance together only after verifying that both have remaining room under one shared lock.

Appending every accepted timestamp to a growing history fails in production because recounting slows down linearly with traffic and idle domains leak memory without bound. Worse, incrementing global_count before checking domain_limit lets one noisy domain burn global capacity on rejected calls, while skipping a mutex (mutual-exclusion lock letting only one thread enter at a time) lets concurrent requests read the same count and overshoot a cap.

Let us trace Example 1 (50 / 30s global, 2 / 5s per domain) for "svc.alpha.io": - t = 20.0 and t = 22.4: Global bucket 0 and 5-second domain bucket 4 both have room, advancing (global_count, domain_count) through (1, 1) -> (2, 2) and returning [True, None] twice. - t = 24.9: Still inside domain bucket int(24.9 // 5) = 4, where domain_count == 2; rejected with [False, "domain"] while global_count stays 2. - t = 25.0: int(25.0 // 5) = 5 triggers a lazy rollover that swaps domain_counts to {} (evicting any quiet domains too!), while int(25.0 // 30) = 0 retains global_count = 2; both checks pass, updating to global_count = 3, domain_count = 1 and returning [True, None].

Complexity

  • is_allowed Time: O(1) amortized. Each call performs two integer floor divisions, one dictionary lookup, and at most two integer increments inside self.lock. When domain_window_id advances, discarding domain_counts reclaims at most one key per previously admitted call, costing O(1) amortized work per request.
  • Judge replay Time: O(M) amortized across M operations; Middleware Time: O(H) per HTTP request to scan H ASGI headers for b"host" before calling is_allowed.
  • Space: O(D), where D is the count of distinct domains with at least one admitted request inside the current domain_window_sec bucket (rejected calls never allocate keys).

Edge cases

  • Exact epoch boundaries: Because window_id = int(now // window_sec), t = 24.999 (id = 4) and t = 25.000 (id = 5) fall in separate 5-second windows even though they are 1 ms apart.
  • Simultaneous exhaustion of both caps: Checking global_count >= global_limit first deterministically returns "global", and neither counter changes on rejection.
  • Zero quotas (global_limit = 0 or domain_limit = 0): Every call fails >= 0 immediately with the matching reason without inserting dictionary keys.
  • Missing, mixed-case, ported, or malformed Host headers: domain_from_host normalizes "SVC.Alpha.io:8443" to "svc.alpha.io", preserves valid IPv6 brackets "[::1]:8000" -> "[::1]", and maps missing, blank, or malformed headers (None, ":8000", "[]", "bad host", non-numeric ports) to "unknown".
  • Concurrent wall-clock reads (now=None): Calling time.time() inside with self.lock: guarantees lock-ordered timestamps so a preempted thread cannot roll a newer bucket ID backward.

Common mistakes

  • Incrementing global_count before checking domain_limit (without rollback). One chatty client hitting its per-domain cap will silently drain global quota for all other domains.
  • Anchoring windows to a domain's first request instead of Unix epoch. Starting a 5-second timer at t = 22.4 would block t = 25.0, violating int(timestamp // window_sec) and requiring per-domain expiration tracking.
  • Holding threading.Lock across an await or skipping synchronization. Blocking across async I/O stalls the event loop, while omitting threading.Lock creates race conditions when synchronous route handlers execute on worker threads.
  • Forwarding rejected requests to await self.app(scope, receive, send). An ASGI (Asynchronous Server Gateway Interface) middleware must return immediately after sending the 429 start and body events.
  • Retaining (window_id, count) per domain forever. Without clearing expired keys, every distinct Host header ever observed stays in memory permanently.

Alternative approaches

  • FastAPI @app.middleware("http") wrapper: Concise for quick prototypes, though Starlette's BaseHTTPMiddleware adds extra task/stream framing per request compared with a pure ASGI middleware class.
  • asyncio.Lock for network-backed stores: When counters live in an async external store where checks await network I/O, use asyncio.Lock or push atomicity into the store itself so the event loop stays non-blocking.

Follow-up questions

  • Why can fixed windows admit double the configured burst right across bucket rollovers, and how would a sliding window or token bucket prevent it? Because a fixed bucket resets completely at exact multiples of window_sec, a client under a 2 / 5s cap can send 2 requests at t = 24.99 and 2 more at t = 25.00—admitting 4 requests inside 10 milliseconds (2x the configured rate). A sliding-window log keeps a per-key deque of accepted timestamps and evicts entries older than now - window_sec (exact enforcement, O(limit) memory per key), whereas a sliding-window counter approximates the trailing window with just two integers via prev_count * (1 - elapsed_in_curr / window_sec) + curr_count. A token bucket—holding up to burst_capacity tokens and refilling continuously at limit / window_sec tokens per second—caps instantaneous bursts explicitly; for dual limits, verify both the global and domain buckets hold >= 1.0 token before deducting 1.0 from each.
  • When traffic is served across multiple worker processes or container replicas, how would you coordinate dual-window counters atomically in Redis? Separate OS processes do not share Python memory, so in-process counters would multiply effective quotas by the replica count. Store window-keyed counters in Redis (rl:global:<global_window_id> and rl:domain:<domain>:<domain_window_id>) and run the check-and-increment inside a single Redis Lua script—a server-side script Redis executes atomically without interleaving other commands—that reads both keys, returns [0, reason] if either has reached its limit, and otherwise INCRs both keys while setting EXPIRE to the window length for automatic cleanup. Pair an async Redis client (redis.asyncio) with a short timeout (20–50 ms) and an explicit fail-open (admit on Redis timeout to protect uptime) or fail-closed policy.
  • How can you bound memory from one-off idle domains in a per-key rate limiter without causing tail-latency spikes on live requests? With epoch-aligned fixed windows, swapping self.domain_counts = {} on rollover already drops all idle domains at once; if a window ever held hundreds of thousands of keys, passing the retired dict reference onto a background queue lets a helper thread free it outside the request lock so garbage collection never stalls live callers. For per-key structures without shared rollover times (such as token buckets or sliding windows), keep active domains in an OrderedDict ordered by last access (LRU, Least Recently Used) and evict at most a tiny fixed budget (say k = 2 expired entries from the oldest tail) per is_allowed call, bounding memory to active tenants in strict O(1) worst-case time per request.

Follow-up questions

Similar questions

More Headway interview questions

All 11 Headway questions →