Software Architecture
High-Throughput Rate Limiting: Token Bucket and Sliding Window Counter Algorithms in Redis
Rate limiting is an indispensable architectural defense mechanism for high-traffic enterprise APIs. Without robust throttling, downstream databases and internal services are vulnerable to catastrophic cascading failures from aggressive scraping, accidental infinite client retry loops, and brute-force credential stuffing. Implementing scalable distributed rate limiting requires selecting algorithms that balance computational accuracy with minimal memory overhead, executed atomically via Redis Lua scripts to eliminate race conditions.
Comparing Rate Limiting Algorithms
Analyzing structural advantages and memory footprints of classic distributed rate limiting implementations:
| Algorithm | Traffic Spike Handling | Memory per User Key | Implementation Complexity |
|---|---|---|---|
| Fixed Window Counter | Poor (Allows 2x burst across window boundaries) | Small (~8 bytes) | Trivial |
| Sliding Window Log | Perfect; highly accurate rolling window | High (Scales linearly with request count) | Moderate |
| Sliding Window Counter | Smooth; approximates rolling boundary | Small (~16 bytes) | Moderate (Standard for API Gateways) |
| Token Bucket | Excellent; allows controlled bursts up to bucket capacity | Minimal (~24 bytes for tokens + timestamp) | Standard for cloud platforms (AWS, Stripe) |
Atomic Token Bucket Implementation via Redis Lua Script
Executing token replenishment and consumption within a single Redis Lua script guarantees thread-safe atomicity across distributed application instances without requiring distributed locks:
-- rate_limiter.lua
-- KEYS[1]: Rate limit key (e.g., 'rate:client_102')
-- ARGV[1]: Max bucket capacity (burst limit)
-- ARGV[2]: Refill rate in tokens per second
-- ARGV[3]: Current timestamp (Unix epoch in seconds)
-- ARGV[4]: Requested tokens (usually 1)
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local requested = tonumber(ARGV[4])
-- Retrieve current state [tokens, last_refreshed]
local data = redis.call("HMGET", key, "tokens", "last_updated")
local tokens = tonumber(data[1])
local last_updated = tonumber(data[2])
if tokens == nil then
tokens = capacity
last_updated = now
else
-- Compute replenished tokens based on elapsed time
local elapsed = math.max(0, now - last_updated)
tokens = math.min(capacity, tokens + (elapsed * refill_rate))
last_updated = now
end
if tokens >= requested then
tokens = tokens - requested
redis.call("HMSET", key, "tokens", tokens, "last_updated", last_updated)
redis.call("EXPIRE", key, math.ceil(capacity / refill_rate))
return {1, math.floor(tokens)} -- [Allowed, Remaining Tokens]
else
local wait_time = (requested - tokens) / refill_rate
return {0, math.ceil(wait_time)} -- [Denied, Retry-After Seconds]
end
- IETF Standard Rate-Limit Headers: Return standardized response headers (
RateLimit-Limit,RateLimit-Remaining,RateLimit-Reset) to allow compliant client SDKs to self-throttle. - Hierarchical Multi-Tier Quotas: Combine fast per-second burst throttling (e.g., 20 req/s) with broad monthly subscription caps (e.g., 1,000,000 req/month).
- Graceful Degradation: If the central Redis cluster becomes unreachable, configure API gateways to fail-open temporarily while emitting high-priority monitoring alerts.
