Building Resilient Rate Limiters: Token Bucket, Leaky Bucket, and Distributed Sliding Window Counters with Redis
An engineering blueprint for protecting APIs against abuse: atomic Redis Lua scripts, sliding window logs, and tiered client quotas.
APIs without rate limiting are susceptible to credential stuffing, denial-of-service, and resource starvation. While fixed window counters are easy to implement, they suffer from the burst boundary vulnerability (allowing double the rate limit across window edges). This guide contrasts the Token Bucket algorithm with the Sliding Window Counter and provides production-ready Redis Lua scripts that execute atomically in sub-millisecond time.
THE PRODUCTION PROBLEM STATEMENT
In fixed window rate limiters (e.g. 100 requests per minute resetting at :00), a client can send 100 requests at 00:59 and another 100 requests at 01:00, pushing 200 requests in a two-second window and overwhelming backend microservices.
How Does the Redis Sliding Window Counter Work?
A sliding window log stores timestamps in a Redis Sorted Set (ZADD) and removes entries older than the current window (ZREMRANGEBYSCORE). However, storing an entry per request consumes high memory under load.
The Sliding Window Counter optimizes this by maintaining counts for the current window and previous window. It calculates an estimated count using a weighted formula: currentCount + previousCount * ((windowSize - timeIntoCurrentWindow) / windowSize). This delivers 99.9% accuracy with constant O(1) memory per client.
-- Keys: KEYS[1] = current_window_key, KEYS[2] = prev_window_key
-- Args: ARGV[1] = limit, ARGV[2] = window_size_seconds, ARGV[3] = time_into_window
local current_key = KEYS[1]
local prev_key = KEYS[2]
local limit = tonumber(ARGV[1])
local window_size = tonumber(ARGV[2])
local time_into_window = tonumber(ARGV[3])
-- Read counts
local current_count = tonumber(redis.call('get', current_key) or "0")
local prev_count = tonumber(redis.call('get', prev_key) or "0")
-- Calculate weighted sliding window total
local weight = (window_size - time_into_window) / window_size
local estimated_count = current_count + (prev_count * weight)
if estimated_count < limit then
-- Increment current window and set TTL (twice window size)
redis.call('incr', current_key)
redis.call('expire', current_key, window_size * 2)
return {1, math.floor(limit - estimated_count - 1)} -- 1 = ALLOWED, remaining
else
return {0, 0} -- 0 = REJECTED (HTTP 429)
endWhich HTTP Headers Should Be Returned to Clients?
Standard rate limiters communicate quota status through IETF standard headers: RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset.
When rejected with HTTP 429 Too Many Requests, always include a Retry-After header indicating seconds until the next allowable attempt.
// Anti-Pattern: Non-atomic check leads to race condition!
const count = await redis.get(key);
if (count < 100) {
// Concurrent requests can pass check simultaneously!
await redis.incr(key);
}// Recommended: Evaluates count and increments atomically
const [allowed, remaining] = await redis.eval(
rateLimitLua, 2, currentKey, prevKey, limit, 60, timeInWindow
);[PROBABLE CAUSE] Rate limiting purely on req.ip when thousands of legitimate employees share the same external public IP.
[VERIFIED RESOLUTION] Combine IP address with authenticated user ID, API key, or session token in the rate limit key hash.
const key = user ? `rl:user:${user.id}` : `rl:ip:${ip}`;Frequently Asked Questions & Technical Inquiries
Direct, practical answers to common architectural and debugging questions.
Token Bucket is best for burst-tolerant APIs (like image processing or batch uploads) because it allows a client to accumulate tokens up to a bucket capacity and burst them instantly.
Faisal Askari
Verified AuthorSoftware Engineer & Full-Stack Developer
Faisal Askari is a software engineer with deep expertise in web systems architecture, the JavaScript runtime ecosystem, and client-side performance engineering. Over years of hands-on production engineering, he has designed and shipped enterprise dashboards, high-converting digital interfaces, and specialized full-stack applications.
Resilient Backend Systems & Cloud Infrastructure
Architecting high-traffic APIs, DDoS protection layers, or microservice gateways?
Resilient Full-Stack Architecture: Idempotent APIs, Optimistic UI, and Cache Invalidation
Engineering robust distributed state between client and server: idempotency keys, safe optimistic rollbacks, exponential backoff with jitter, and cache coherence.
Server-Sent Events (SSE) vs WebSockets over HTTP/2: Choosing the Right Real-Time Streaming Architecture
Why HTTP/2 multiplexing made Server-Sent Events the modern standard for LLM token streams and live telemetry over complex WebSockets.