Mental model
Rate Limiting bounds client request frequency and resource consumption across stateless API replicas to prevent abusive scraping, Denial-of-Service amplification (OWASP API4:2023 Unrestricted Resource Consumption), and noisy-neighbor tenant starvation, while isolating infrastructure health cleanly during traffic surges. Selecting the right algorithm—Token Bucket / GCRA for smooth burst-friendly API limits, Sliding Window Counter for predictable quota ceilings, or Dual RPM + TPM token buckets for variable-cost LLM endpoints—requires executing state updates atomically inside Redis Lua scripts so concurrent requests never bypass limits through non-atomic GET/INCR race conditions.
Theory
Naive "fixed minute bucket" counters suffer a famous boundary loophole: a client sending 100 requests at 12:00:59 and 100 requests at 12:01:01 hits 200 requests inside 2 seconds without tripping a 100 req/min cap!
| Rate-Limiting Algorithm | Memory Per Active Key | Burst Handling | Boundary Spike Safety | Best Fit |
|---|---|---|---|---|
| Fixed Window Counter | 1 integer (~48 bytes) | Allows 2x boundary bursts across window rollover | Weak | Coarse brute-force login throttles only |
Sliding Window Log (ZSET) | Stores timestamp member for every allowed hit (O(limit)) | Exact smooth cutoff | Perfect (0% rollover spike) | Strict low-volume limits (5 OTP emails / 15 min) |
| Sliding Window Counter | 2 integers (current + previous window weights) | Smooth interpolated boundary (~0.003% error) | Strong (O(1) RAM) | General high-QPS REST endpoints (10k req/s) |
| Token Bucket / GCRA (Leaky) | 1–2 numeric values (remaining tokens / Theoretical Arrival Time) | Controlled burst up to bucket capacity, steady refill rate | Strong (O(1) RAM) | Public AI inference APIs (RPM + TPM dual metering!) |
Atomic Redis Lua Token Bucket and AI Cost Weighting (cost > 1)
Executing GET -> check -> DECR across separate Redis round-trips allows 10 parallel requests arriving in the same millisecond to all read remaining=1 simultaneously and pass cleanly (TOCTOU race). Bundle refill math and deduction atomically inside a single-threaded Redis Lua script (EVALSHA) driven by Redis server TIME (avoiding cross-pod system clock skew across FastAPI containers!). Crucially for LLM APIs, where one 100,000-token RAG call costs 500x more GPU compute than a quick metadata lookup, pass variable cost (cost = estimated_input_tokens + max_tokens or request weight) into the Token Bucket rather than counting raw HTTP hits uniformly. Always also enforce strict rate-limit middleware order: reject over-limit traffic in Redis before hitting heavy database/auth joins, and fail-open vs fail-closed intentionally (typically fail-open + alert on Redis outage for non-security read paths, fail-closed on /login & expensive GPU routes).
pythonimport redis.asyncio as aioredisredis_client = aioredis.from_url("redis://redis:6379/0", decode_responses=True)# Atomic Redis Token Bucket Lua script supporting variable request/token cost & clock-skew-free TIMETOKEN_BUCKET_LUA = """local key = KEYS[1]local capacity = tonumber(ARGV[1])local refill_per_sec = tonumber(ARGV[2])local cost = tonumber(ARGV[3])local redis_time = redis.call("TIME")local now = tonumber(redis_time[1]) + (tonumber(redis_time[2]) / 1000000.0)local bucket = redis.call("HMGET", key, "tokens", "last_ts")local tokens = tonumber(bucket[1])local last_ts = tonumber(bucket[2])if not tokens thentokens = capacitylast_ts = nowelselocal elapsed = math.max(0, now - last_ts)tokens = math.min(capacity, tokens + (elapsed * refill_per_sec))last_ts = nowendlocal allowed = 0local retry_after = 0if tokens >= cost thentokens = tokens - costallowed = 1elseretry_after = math.ceil((cost - tokens) / refill_per_sec)endredis.call("HMSET", key, "tokens", tokens, "last_ts", last_ts)redis.call("EXPIRE", key, math.ceil(capacity / refill_per_sec) + 60)return {allowed, math.floor(tokens), retry_after}"""async def check_rate_limit(subject: str, capacity: int = 60, refill_per_sec: float = 1.0, cost: int = 1) -> tuple[bool, int, int]:allowed, remaining, retry_after = await redis_client.eval(TOKEN_BUCKET_LUA, 1, f"rl:tb:{subject}", capacity, refill_per_sec, cost)return bool(allowed), int(remaining), int(retry_after)
Expose standard headers on 200 and 429 Too Many Requests replies: Retry-After: <seconds>, RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset, so polite SDK clients pause deterministically rather than retrying in a tight loop and worsening the Thundering Herd!
Alternatives and trade-offs
- Centralized Atomic Redis Lua (
Token Bucket/GCRA): Exact cluster-wide tenant enforcement across dozens of FastAPI/Go replicas,O(1)memory per key, clean variable token-cost metering (TPM); adds one Redis sub-millisecond hop per gateway request (mitigable via Redis pipelining or local in-memory overflow short-circuit caches during extreme floods!). - Hierarchical Edge Proxy Limiting (Nginx
limit_req/ Cloudflare WAF) + App Quotas: Absorbs volumetric L7 DDoS floods cheaply in C/edge before hitting Redis or Python workers, paired cleanly with per-API-key Token Buckets inside the API Gateway for SaaS billing tiers. - Dynamic Adaptive Concurrency Limiting (
AIMD/ Vegas): Adjusts concurrency thresholds automatically based on measured downstreamp99queue latency rather than hardcoding staticreq/sguesses that become either too restrictive on cold starts or too loose during a database lock stall.
Failure modes and misconceptions
- Non-Atomic
GET+SETor Multi-Step Non-Lua Pipelines: Issuing conditional limit decisions in Python between two Redis calls leaksNparallel requests cleanly past strict limits (race condition) on concurrentPOST /redeemorPOST /inferencebursts. Always keep read-modify-write math inside one atomic Lua script. - Omitting
Retry-After& Jittered Client Backoff Guidance on429: Returning plain429withoutRetry-Aftertriggers naive SDK exponential retries synchronized at integer second boundaries—creating secondary Thundering Herd spikes every time buckets refill. - Keying Public Rate Limits Only by Unverified
X-Forwarded-ForHeader: Attackers bypass naive IP throttling trivially by rotating spoofedX-Forwarded-For: 10.0.0.xheaders! Extract client IP strictly via trusted proxy right-most hops (trustedIPs), AND key authenticated routes by stableorg_id/api_key_id+ route group. - Relying on Fixed Request Counts Without Concurrent In-Flight Caps (
Semaphores): If one rogue tenant holds50simultaneous slow streaming LLM connections open (1 req/minrate still looks low!), request-rate limiters miss connection exhaustion. Always pair RPM/TPM Token Buckets with a per-tenant max concurrent streams guard (Semaphore/ Redis active-stream lease).
Decision scenario
Your SaaS LLM API exposes both cheap metadata reads and expensive multi-second token generation streams across 20 FastAPI pods, facing bursty legitimate enterprise traffic alongside malicious brute-force probing on /login. Place Cloudflare/Traefik per-IP edge throttling in front of unauthenticated ingress, run an atomic Redis Lua Token Bucket keyed on (org_id, tier) enforcing both requests-per-minute (cost=1) and weighted estimated tokens (cost=max_tokens corrected cleanly post-stream via actual usage refund/debit!), track active concurrent streaming requests per org cleanly in Redis (<= 25 concurrent streams), return strict 429 + Retry-After + RateLimit-* headers, and keep brute-force /login thresholds fail-closed.
Learning outcomes
- Compare Fixed Window rollover spikes, Sliding Window Log memory overhead, Sliding Window Counters, and Token Bucket / GCRA behavior.
- Eliminate distributed concurrency races using atomic Redis
TIME-synchronized Lua scripts. - Enforce LLM-aware variable cost metering (TPM + concurrent streams) alongside classic request-rate caps.
- Protect downstream endpoints from brute-force
X-Forwarded-Forspoofing and aggressive un-jittered client retry storms.
Trade-offs
Distributed Redis Lua Token Buckets unify burst fairness, sub-millisecond cluster enforcement, and AI cost weighting cleanly across stateless microservices, at the modest cost of Redis round-trip latency and explicit fail-open vs. fail-closed policy planning.