API Rate Limiting and DDoS Mitigation Strategies Using Redis Sliding Windows
Category: Backend Systems | Reading Time: 2 min read
How to engineer high-throughput API rate limiting and DDoS mitigation using Redis Sliding Windows and Token Buckets. Protect your backend infrastructure from brute force, bot scraping, and credential stuffing.
Public-facing APIs are under perpetual siege. Automated credential stuffing bots attempt thousands of logins per minute, malicious scrapers drain computing resources by crawling entire catalogs, and distributed denial-of-service (DDoS) floods attempt to knock business platforms offline.
Basic rate limiting techniques—such as fixed-window counters—suffer from severe vulnerability: traffic spikes at window boundaries (e.g., 100 requests at 11:59:59 and 100 requests at 12:00:01) allow double the intended quota in a 2-second burst.
Engineering a production-grade rate limiter requires atomic Sliding Window algorithms powered by Redis Sorted Sets (ZSET) or sliding-window logs executed directly at the API gateway tier.
1. Core Industry Challenges & Architectural Dilemmas
- Boundary Burst Vulnerability: Fixed-window limiters allowing 2x traffic bursts across boundary resets.
- Race Conditions in Distributed Clusters: Non-atomic get-and-increment operations allowing concurrent requests to bypass limits.
- Redis Network Round-Trip Latency: Adding 5ms of network latency to every single API request just to check rate limit keys.
- IP Spoofing & Header Tampering: Attackers rotating fake X-Forwarded-For headers to evade IP-based throttles.
2. Technical Comparison & Architectural Trade-offs
| Algorithm | Accuracy | Memory Efficiency | Burst Protection | Production Fit |
|---|---|---|---|---|
| Fixed Window Counter | Low (Boundary spike flaws) | Extremely High (Single integer) | Poor | Low-priority internal APIs |
| Sliding Window Log | 100% Precise | Low (Stores all timestamps) | Excellent | Financial & High-Security Auth |
| Sliding Window Counter | 99% Approximated | High (2 integer keys) | Very Good | General Public API Ingress |
| Token Bucket | High | High (Timestamp + float) | Smooth Rate Limiting | Stripe-style API developer tiers |
3. Production Implementation Blueprint & Code Pattern
Atomic Redis Lua Script executing Sliding Window rate limiting with sub-millisecond latency and zero race conditions:
-- Redis Lua Script: Atomic Sliding Window Rate Limiter
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
-- 1. Remove timestamps older than the active window
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
-- 2. Count requests currently inside the sliding window
local count = redis.call('ZCARD', key)
if count < limit then
-- Allowed: record current request timestamp and set TTL
redis.call('ZADD', key, now, now)
redis.call('EXPIRE', key, math.ceil(window / 1000))
return 1 -- ALLOWED
else
return 0 -- THROTTLED (HTTP 429)
end