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:
- Global quota: At most
global_limitaccepted requests within eachglobal_window_sec-second bucket across all client domains combined. - Per-domain quota: At most
domain_limitaccepted requests within eachdomain_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)fromDualFixedWindowRateLimiter.is_allowed). - Rejected request: Increment neither counter (and short-circuit with HTTP
429in 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 >= 0anddomain_limit >= 0(0rejects every call immediately with the corresponding scope).global_window_sec >= 1anddomain_window_sec >= 1(non-positive window sizes inDualFixedWindowRateLimitershould raiseValueError).0 <= len(operations) == len(arguments) <= 10^4.- Explicit
nowvalues in a replay sequence are non-negative floats (intorfloat) in non-decreasing order; omittednowdefaults to the system clock. - In HTTP middleware usage, missing or malformed
Hostheaders should normalize safely (e.g., to"unknown") rather than crashing.
Step-by-step walkthrough
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:
- Global limit: At most
global_limit(default100) requests perglobal_window_sec(default60seconds) across all clients combined. - Per-domain limit: At most
domain_limit(default3) requests perdomain_window_sec(default1second) for any single client domain.
Each fixed window is aligned to Unix epoch (
t = 0), with bucket indexwindow_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 theHostheader, checksis_allowed, and immediately returns429 Too Many Requests(naming which limit failed) when rejected. -dual_fixed_window_rate_limiter(...): The judge harness wrapper that replaysoperationsandargumentsand 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 readingtime.time()inside the lock.- Global limit: At most
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 currentglobal_window_idanddomain_window_id. That works as a small test oracle, but in production each check degrades toO(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_idandglobal_count. Whenever a request arrives at timenow, we computeint(now // global_window_sec); if it differs fromglobal_window_id, the old window has ended, so we overwriteglobal_window_idand resetglobal_count = 0on 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_idgoverns a plain dictionarydomain_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.
Build the limiter state and lazy rollover
Initializing both window IDs to
Noneguarantees that the very first request—even atnow = 0.0(window_id = 0)—sees0 != Noneand 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 = {}Make check-and-increment atomic in `is_allowed`
Three ordering rules inside
is_allowedprevent subtle bugs:- Check both limits before incrementing either counter. If we incremented
global_countfirst and then rejected the request ondomain_limit, rejected bursts from one noisy client would silently drain global quota for everyone else! - Hold one
threading.Lockacross 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 readcount = 2underlimit = 3and both admit a request, letting 4 through. Because nothing insidewith self.lock:usesawait,threading.Locknever blocks anasyncioevent loop across I/O while also protecting FastAPI's worker thread pool for synchronousdefroutes. - Read
time.time()inside the lock whennow is None. If Thread A read10.999outside the lock, got preempted while Thread B read11.001and rolled to window11, Thread A waking up next would see10 != 11, roll the limiter backward to window10, 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- Check both limits before incrementing either counter. If we incremented
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)). WritingRateLimitMiddlewaredirectly against ASGI avoids third-party imports in standalone environments and plugs into FastAPI viaapp.add_middleware(RateLimitMiddleware, limiter=DualFixedWindowRateLimiter()).First,
domain_from_hostnormalizesHostheaders 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". ThenRateLimitMiddlewarelets non-HTTP scopes (lifespan, websockets) pass through, callsis_allowed, and on rejection sends HTTP429with both a human-readable JSON detail message and anx-ratelimit-scopeheader—never invokingself.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})Wire up the judge replay function
The judge passes the four configuration integers plus parallel
operationsandargumentslists, expecting[allowed, reason]for each"is_allowed"call (withnowoptional whenlen(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 resultsTrace Example 1 step by step
Let us trace Example 1 (
global = 50 / 30s,domain = 2 / 5s, domaind = "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]=1Notice two crucial details: at
t = 24.9the rejected 3rd request leavesglobal_countat2, and att = 25.0int(25.0 // 5) = 5clearsdomain_countswhileint(25.0 // 30) = 0keeps accumulating within global window0.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_allowedTime: O(1) amortized. Each call performs two integer floor divisions, one dictionary lookup, and at most two integer increments insideself.lock. Whendomain_window_idadvances, discardingdomain_countsreclaims at most one key per previously admitted call, costingO(1)amortized work per request.- Judge replay Time: O(M) amortized across
Moperations; Middleware Time: O(H) per HTTP request to scanHASGI headers forb"host"before callingis_allowed. - Space: O(D), where
Dis the count of distinct domains with at least one admitted request inside the currentdomain_window_secbucket (rejected calls never allocate keys).
Edge cases
- Exact epoch boundaries: Because
window_id = int(now // window_sec),t = 24.999(id = 4) andt = 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_limitfirst deterministically returns"global", and neither counter changes on rejection. - Zero quotas (
global_limit = 0ordomain_limit = 0): Every call fails>= 0immediately with the matching reason without inserting dictionary keys. - Missing, mixed-case, ported, or malformed
Hostheaders:domain_from_hostnormalizes"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): Callingtime.time()insidewith self.lock:guarantees lock-ordered timestamps so a preempted thread cannot roll a newer bucket ID backward.
Common mistakes
- Incrementing
global_countbefore checkingdomain_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.4would blockt = 25.0, violatingint(timestamp // window_sec)and requiring per-domain expiration tracking. - Holding
threading.Lockacross anawaitor skipping synchronization. Blocking across async I/O stalls the event loop, while omittingthreading.Lockcreates 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 the429start and body events. - Retaining
(window_id, count)per domain forever. Without clearing expired keys, every distinctHostheader ever observed stays in memory permanently.
Alternative approaches
- FastAPI
@app.middleware("http")wrapper: Concise for quick prototypes, though Starlette'sBaseHTTPMiddlewareadds extra task/stream framing per request compared with a pure ASGI middleware class. asyncio.Lockfor network-backed stores: When counters live in an async external store where checksawaitnetwork I/O, useasyncio.Lockor 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 a2 / 5scap can send 2 requests att = 24.99and 2 more att = 25.00—admitting 4 requests inside 10 milliseconds (2xthe configured rate). A sliding-window log keeps a per-keydequeof accepted timestamps and evicts entries older thannow - window_sec(exact enforcement,O(limit)memory per key), whereas a sliding-window counter approximates the trailing window with just two integers viaprev_count * (1 - elapsed_in_curr / window_sec) + curr_count. A token bucket—holding up toburst_capacitytokens and refilling continuously atlimit / window_sectokens per second—caps instantaneous bursts explicitly; for dual limits, verify both the global and domain buckets hold>= 1.0token before deducting1.0from 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>andrl: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 otherwiseINCRs both keys while settingEXPIREto 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 anOrderedDictordered by last access (LRU, Least Recently Used) and evict at most a tiny fixed budget (sayk = 2expired entries from the oldest tail) peris_allowedcall, bounding memory to active tenants in strictO(1)worst-case time per request.
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?
- When traffic is served across multiple worker processes or container replicas, how would you coordinate dual-window counters atomically in Redis?
- How can you bound memory from one-off idle domains in a per-key rate limiter without causing tail-latency spikes on live requests?
Similar questions
- Insurance Coverage Cache Reconciler
- Two-Tier Global and Route Rate Limiter
- Incomplete-Data Calls, AI Workflows, and Spec-Driven Engineering
- Course Run Statistics Simulator
- Short-Term Stay Search and Reservation Architecture
- Architecting an E-Commerce Cart with Concurrent Inventory Reservations
More Headway interview questions
- Insurance Coverage Cache Reconciler Medium
- Incomplete-Data Calls, AI Workflows, and Spec-Driven Engineering Medium
- Course Run Statistics Simulator Medium Pro
- Short-Term Stay Search and Reservation Architecture Medium Pro
- Architecting an E-Commerce Cart with Concurrent Inventory Reservations Medium Pro
- Driving Technical Alignment and Peer Mentorship on a Complex Project Medium Pro
- Alphabetical Letter Combinations from Keypad Digits Medium Pro
- Diagnosing API Overload Surges and Sizing Backend Capacity Medium Pro
- Checkpoint Journey Speed Violation Detector Hard Pro
- Two-Tier Global and Route Rate Limiter Medium Pro