Defending APIs: Redis-Backed Sliding Window Algorithms
Ascend Technical Editorial
Published: May 2026 • 7 min read
Layer 7 (Application) DDoS attacks target specific, computationally expensive API endpoints. Basic IP blocking at the WAF level is easily bypassed via botnets. True defense requires algorithmic rate limiting at the application edge.
1. The Flaw of Fixed Window Limiting
Traditional "Fixed Window" counters reset exactly at the top of the minute. Attackers exploit this by sending 2x the allowed traffic exactly at the boundary (e.g., 59 seconds and 01 seconds), temporarily crashing backend databases.
2. Implementing Sliding Window Logs via Redis
A Sliding Window algorithm provides precise, rolling protection. By using Redis Sorted Sets (ZSET), each request's timestamp is stored, and older timestamps are continuously evicted. Evaluating this logic inside a single Redis Lua script ensures atomic execution with sub-millisecond overhead (~1.2ms latency penalty), effectively neutralizing burst attacks.
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local count = redis.call('ZCARD', key)
if count >= limit then
return 0 -- Reject
end
redis.call('ZADD', key, now, now)
redis.call('EXPIRE', key, window / 1000)
return 1 -- Allow
Mechanism: Sliding Window
Datastore: Redis (ZSET)
Protection Layer: App-Edge