[Full-Stack Development]PUBLISHED 2026-11-21//15 min read//VERIFIED 2026-11-24

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.

EXECUTIVE ARCHITECTURAL OVERVIEW

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.

SECTION 01 //

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.

sliding_window_rate_limiter.lua
-- 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)
end
Atomic Redis Lua script implementing the sliding window counter rate limiter.
SECTION 02 //

Which 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.

Architectural Comparison: Anti-Pattern vs Recommended Practice
[ANTI-PATTERN] Read-Then-Write Race Condition in Node.js Code
// 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] Atomic Evaluation via Redis Lua Script
// Recommended: Evaluates count and increments atomically
const [allowed, remaining] = await redis.eval(
  rateLimitLua, 2, currentKey, prevKey, limit, 60, timeInWindow
);
[RATIONALE]Evaluating counts in application code creates race conditions between concurrent requests. Redis Lua scripts execute atomically on the Redis server, guaranteeing strict quota enforcement.
04/PRODUCTION TROUBLESHOOTING & DIAGNOSTICS
TRIAGE MATRIX
SYMPTOM 01: HTTP 429 Too Many Requests returned for all users behind a shared corporate proxy or NAT gateway.

[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.

SuggestedFix.ts
const key = user ? `rl:user:${user.id}` : `rl:ip:${ip}`;
TECHNICAL INQUIRY MATRIX

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.

Official References & Specifications:
Faisal Askari

Faisal Askari

Verified Author

Software Engineer & Full-Stack Developer

Personal Website

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.

PROFESSIONAL ENGINEERING BRIDGE

Resilient Backend Systems & Cloud Infrastructure

Architecting high-traffic APIs, DDoS protection layers, or microservice gateways?

Consult on API Security with Faisal Askari
SPEC // VERIFIED ENTITY•Karachi, Pakistan (Global Remote)
contact@faisalaskari.top
05/RELATED ENGINEERING GUIDES
CONTINUE STUDY