Codeplant IT Solution
Codeplant IT Solution
Custom Software & AI Engineering

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

AlgorithmAccuracyMemory EfficiencyBurst ProtectionProduction Fit
Fixed Window CounterLow (Boundary spike flaws)Extremely High (Single integer)PoorLow-priority internal APIs
Sliding Window Log100% PreciseLow (Stores all timestamps)ExcellentFinancial & High-Security Auth
Sliding Window Counter99% ApproximatedHigh (2 integer keys)Very GoodGeneral Public API Ingress
Token BucketHighHigh (Timestamp + float)Smooth Rate LimitingStripe-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