Rate Limiter
Requirements: limit requests per user/IP/API key (e.g. 100/min), low added latency (<1 ms), distributed across many API servers, informative 429 responses, configurable rules.
client -> API gateway / middleware --check--> Redis cluster (counters, Lua scripts)
| allowed ^
v | rules (cached locally, from config store)
backend services
Deep dives
- Algorithm: token bucket (bursty but bounded) or sliding window counter (accurate, cheap) — see Building Blocks.
- Atomicity: read-modify-write races across servers → do it in one Redis Lua script, or
INCRwithEXPIREfor fixed windows. - Placement: at the API gateway (centralized) or as a sidecar/library; client-side limits are only advisory.
- Scale & latency: shard counters by key; keep a small local token cache and sync periodically (allows slight overshoot) to avoid a Redis hop per request.
- Failure mode: if Redis is down, fail open (availability) or fail closed (protection) — decide per API.
- Headers:
X-RateLimit-Limit,X-RateLimit-Remaining,Retry-After.