FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Rate Limiting & Thundering Herd Defense

Token Bucket, Leaky Bucket, and Redis sliding-window rate limiting algorithms.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Build distributed rate limiting using Redis atomic scripts
  • ✓Protect downstream APIs from traffic spikes and abuse
Isometric Diagram LabSystem Design · 11 steps · 11 min

Token Bucket, Leaky Bucket & Sliding Window

Test distributed Redis rate limiters, burst smoothing, and 429 retry-after shedding.

Open Isometric Walkthrough
Full Technical Reference Document

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.

API Ingress Extracts Tenant & Route Key
Execute Atomic Redis Lua Limiter Script
Evaluate Burst Tokens or Sliding Counter
Return Quota Headers (Remaining / Reset)
Allow Downstream or Reject 429 + Retry-After
Conceptual teaching model synthesized from:redis-docs,owasp-api-security,sre-book

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 AlgorithmMemory Per Active KeyBurst HandlingBoundary Spike SafetyBest Fit
Fixed Window Counter1 integer (~48 bytes)Allows 2x boundary bursts across window rolloverWeakCoarse brute-force login throttles only
Sliding Window Log (ZSET)Stores timestamp member for every allowed hit (O(limit))Exact smooth cutoffPerfect (0% rollover spike)Strict low-volume limits (5 OTP emails / 15 min)
Sliding Window Counter2 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 rateStrong (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).

python
import redis.asyncio as aioredis
​
redis_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 TIME
TOKEN_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 then
tokens = capacity
last_ts = now
else
local elapsed = math.max(0, now - last_ts)
tokens = math.min(capacity, tokens + (elapsed * refill_per_sec))
last_ts = now
end
​
local allowed = 0
local retry_after = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
else
retry_after = math.ceil((cost - tokens) / refill_per_sec)
end
​
redis.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 downstream p99 queue latency rather than hardcoding static req/s guesses that become either too restrictive on cold starts or too loose during a database lock stall.

Failure modes and misconceptions

  1. Non-Atomic GET + SET or Multi-Step Non-Lua Pipelines: Issuing conditional limit decisions in Python between two Redis calls leaks N parallel requests cleanly past strict limits (race condition) on concurrent POST /redeem or POST /inference bursts. Always keep read-modify-write math inside one atomic Lua script.
  2. Omitting Retry-After & Jittered Client Backoff Guidance on 429: Returning plain 429 without Retry-After triggers naive SDK exponential retries synchronized at integer second boundaries—creating secondary Thundering Herd spikes every time buckets refill.
  3. Keying Public Rate Limits Only by Unverified X-Forwarded-For Header: Attackers bypass naive IP throttling trivially by rotating spoofed X-Forwarded-For: 10.0.0.x headers! Extract client IP strictly via trusted proxy right-most hops (trustedIPs), AND key authenticated routes by stable org_id / api_key_id + route group.
  4. Relying on Fixed Request Counts Without Concurrent In-Flight Caps (Semaphores): If one rogue tenant holds 50 simultaneous slow streaming LLM connections open (1 req/min rate 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).
Reflect before revealing the guide

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-For spoofing 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.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next