Why Every Public API Needs a Rate Limiter
Without rate limiting, a single misconfigured retry loop, scraper, or DDoS spike can saturate database connection pools, exhaust downstream LLM/cloud quotas, and take down healthy tenants.
A Rate Limiter caps traffic per client IP, API key, or user ID before requests reach expensive upstream services.

Distributed Rate Limiter Architecture
1. Where Should the Rate Limiter Live?
| Placement | Pros | Cons | Best Fit |
|---|
| Client-Side | Zero server overhead | Easily bypassed / forged | Never rely on alone |
| Application Middleware | Aware of domain logic & user tiers | Couples infra rules to app code | Monoliths / custom rules |
| API Gateway / Reverse Proxy | Centralized across all microservices | Needs shared state (Redis) for clusters | Microservices (Envoy, Kong, Nginx) |
2. Core Rate Limiting Algorithms Compared
| Algorithm | Burst Tolerance | Memory Usage | Edge Boundary Accuracy | Common Users |
|---|
| Token Bucket | Allows short bursts | Very Low ($O(1)$) | Good | Amazon API Gateway, Stripe |
| Leaking Bucket | Smooth fixed outflow | Low | Good | Shopify, network traffic shaping |
| Fixed Window Counter | Can allow 2× burst at boundary | Very Low ($O(1)$) | Weak at window edges | Simple counters |
| Sliding Window Log | Strict accuracy | High (stores every timestamp) | Exact | Security / auth endpoints |
| Sliding Window Counter | Smooth + accurate | Very Low ($O(1)$) | ~99.99% accurate | Cloudflare, high-scale APIs |
How Token Bucket Works
- Each user gets a virtual bucket with capacity $B$ tokens.
- Tokens refill continuously at rate $R$ tokens/sec (capped at $B$).
- Incoming request consumes 1 token: if tokens $\ge 1$, allow; otherwise return HTTP
429 Too Many Requests.
3. Standard HTTP Rate Limit Response Headers
Always inform well-behaved clients how to back off cleanly:
http
HTTP/1.1 429 Too Many Requests
X-Ratelimit-Limit: 100
X-Ratelimit-Remaining: 0
X-Ratelimit-Reset: 1793450400
Retry-After: 42
4. Solving Distributed Race Conditions with Redis Lua
In a multi-node cluster, naive GET followed by SET in Redis suffers from a read-modify-write race condition: two concurrent requests read remaining = 1, both succeed, and violate the quota.
Executing the check-and-decrement inside a Redis Lua script guarantees single-threaded atomicity:
lua
-- token_bucket.lua
-- KEYS[1]: rate limit key (e.g., "rl:user:123")
-- ARGV[1]: capacity, ARGV[2]: refill_rate_per_sec, ARGV[3]: current_timestamp_sec
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local bucket = redis.call("HMGET", key, "tokens", "last_refill")
local tokens = tonumber(bucket[1])
local last_refill = tonumber(bucket[2])
if tokens == nil then
tokens = capacity
last_refill = now
else
local elapsed = math.max(0, now - last_refill)
tokens = math.min(capacity, tokens + elapsed * refill_rate)
last_refill = now
end
local allowed = 0
if tokens >= 1 then
tokens = tokens - 1
allowed = 1
end
redis.call("HMSET", key, "tokens", tokens, "last_refill", last_refill)
redis.call("EXPIRE", key, math.ceil(capacity / refill_rate) * 2)
return { allowed, math.floor(tokens) }
5. Production Hardening & Fail-Open vs Fail-Closed
- Fail-Open: If the Redis rate-limit cluster has an outage, log an alert and allow traffic through so a cache blip doesn't cause a total site outage.
- Local Caching of Rules: Keep throttle rules in memory on gateway nodes (refreshed asynchronously) rather than querying a SQL DB on every request.
- Multi-Data Center: Use sticky region routing for users or asynchronous gossip/CRDT counters when global sub-millisecond syncing isn't feasible.