Triamorph Systems

Architecture · 11 min read · Sep 04, 2024

Distributed Rate Limiting at 100k RPS: Redis Token Bucket & Sliding Windows

Architecting high-scale distributed rate limiters with Redis and Lua: token bucket vs sliding window logs, tier-based quotas, and sub-millisecond edge enforcement.

By Aman Aslam

Core Engineering Takeaways

  • In-memory Redis clusters running single-round-trip Lua scripts evaluate rate limits in under 0.8 milliseconds.
  • Sliding Window Counters offer the ideal balance between memory efficiency (12 bytes per user) and boundary accuracy compared to fixed windows.
  • Always return standard IETF RateLimit HTTP headers (RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset) to allow client SDKs to back off gracefully.

High-throughput enterprise APIs handle millions of requests every hour from web apps, mobile clients, and third-party integrations. Without robust rate limiting, unexpected spikes or targeted credential stuffing attacks can easily exhaust connection pools and crash backend services. This deep dive reveals how to implement sub-millisecond distributed rate limiting at 100,000+ requests per second using Redis and atomic Lua scripts.

1. Algorithm Comparison: Fixed Window vs Token Bucket vs Sliding Window

Why fixed window counters fail at boundary resets

Fixed window counters permit 2x traffic bursts across boundary borders (e.g. 100 requests at 11:59:59 and another 100 requests at 12:00:01). Token bucket and sliding window algorithms eliminate this vulnerability by calculating continuous temporal decay.

2. Implementing Sliding Window Counters in Atomic Lua

Evaluating sliding windows inside a single atomic Redis round-trip

The following script runs atomically inside Redis memory, preventing race conditions between concurrent requests.

rate-limiter/sliding_window.lua (lua)
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local clearBefore = now - window

-- Remove timestamps outside the active sliding window
redis.call('ZREMRANGEBYSCORE', key, 0, clearBefore)

-- Count requests in active window
local currentRequests = redis.call('ZCARD', key)

if currentRequests < limit then
    -- Record current request timestamp
    redis.call('ZADD', key, now, now)
    redis.call('EXPIRE', key, math.ceil(window / 1000))
    return {1, limit - currentRequests - 1} -- Allowed, Remaining
else
    return {0, 0} -- Denied, Remaining: 0
end

3. Tier-Based Quotas & Multi-Dimensional Limiting

Combining IP, user token, and endpoint cost multipliers

A single rate limit is insufficient. We apply multi-dimensional limits: unauthenticated requests are throttled strictly by IP address (60 req/min), while authenticated enterprise API tokens receive dedicated tiered allocations (5,000 req/min) with weighted cost penalties for heavy reporting endpoints.

4. IETF RateLimit Headers & Client SDK Backoff

Standardized headers preventing retry stampedes

Responses include `RateLimit-Limit: 1000`, `RateLimit-Remaining: 42`, and `Retry-After: 18`. Client libraries use exponential backoff with full jitter to distribute retry attempts evenly.

Tags: distributed rate limiter redistoken bucket algorithm distributedapi gateway DDoS protectionsub millisecond rate limitingAPI Architecture

Related Engineering Practice & Case Studies

Engineering Practice Blueprint

Custom Web Development & SaaS Platforms →

Next.js & React web platforms engineered for sub-1.5s load times and 98+ Lighthouse scores.

View Practice Blueprint & Capabilities →
Production Client System

Portfolix Developer Portfolio Builder →

Modern developer portfolio builder platform delivering sub-5 minute deployments with 98+ Lighthouse scores and 100% clean code export.

Read Deployed Case Study (Sub-5 minute edge deployment with 100% clean code export) →

Related Engineering Articles & Guides

Explore all technical guides in our Articles & Guides Index → or discuss your architecture with our engineers via Technical Discovery →