Designing a Distributed API Rate Limiter
Defending production services against malicious scrapers and thundering retry storms requires evaluating millions of API requests per second in under 2ms. Learn how to compare Token Bucket vs Sliding Window algorithms, execute atomic Redis Lua scripts, and engineer fail-open circuit breakers.
Latency Overhead & Memory Geometry
A rate limiter sits inline on every API call. If your rate limiter takes 15ms to evaluate, your entire API slows down by 15ms. The system must operate with extreme memory efficiency and zero disk I/O.
Latency Budget & Local Reservoir
- 1. Network Hop Latency: A round-trip query to a centralized Redis cluster consumes 1.0ms - 2.5ms across regional VPCs. At 1,000,000 req/s, hitting Redis on every request requires 1,000,000 Redis ops/s, requiring massive sharding.
- 2. Batch Token Pre-allocation: Edge API gateway nodes acquire a block of tokens (e.g. 50 tokens) from Redis in a single atomic call, then satisfy local requests from in-memory token reservoirs with 0.01ms overhead.
- 3. Accuracy vs Performance: Pre-allocation introduces a minor burst tolerance (~5% variance across edge pods) in exchange for reducing Redis network traffic by 98%.
Memory Footprint (Sliding Window Counter)
- 1. Bucket State: Storing exact timestamps (Sliding Window Log) requires 8 bytes per request. Under 1,000 req/min, that is 8 KB per user. For 100M users = 800 GB RAM.
- 2. Sliding Window Counter Optimization: Only stores 2 integers: current minute counter (4 bytes) and previous minute counter (4 bytes). Total memory per rate key with Redis metadata: ~64 bytes.
- 3. Cluster Sizing: 100M active tracking keys * 64 bytes = 6.4 GB RAM. A 3-node Redis cluster with 16 GB RAM easily accommodates the entire global rate limiting state with 100% in-memory headroom.
Comparing the 4 Core Rate Limiting Algorithms
Different API endpoints require different algorithms. Login APIs protect against brute-force attacks via sliding window counters; user upload APIs permit traffic bursts via token buckets.
| Algorithm | Memory Complexity | Burst Handling | Boundary Vulnerability | Best Use Case |
|---|---|---|---|---|
| Fixed Window Counter | O(1) - 8 bytes | Poor (drops legitimate spikes) | 2x burst at window edges (e.g. 59s & 01s) | Simple low-traffic quotas |
| Sliding Window Log | O(N) - 8 KB / key | Accurate (exact boundary) | None (mathematically precise) | Sensitive security / auth endpoints |
| Token Bucket | O(1) - 16 bytes | Excellent (allows burst up to capacity) | None (continuous token refill) | General REST API rate limiting |
| Sliding Window Counter | O(1) - 12 bytes | Smooths spikes over window | Approximation error < 0.05% | High-throughput edge gateways (Envoy) |
Atomic Redis Lua Script Implementation
Preventing race conditions requires executing bucket replenishment and token deduction atomically on Redis without multiple round-trip locks:
local limit = tonumber(ARGV[1])
local current = tonumber(redis.call('get', key) or "0")
if current + 1 > limit then
return 0 -- Rejected (429 Too Many Requests)
else
redis.call("INCRBY", key, 1)
if current == 0 then redis.call("EXPIRE", key, 60) end
return 1 -- Allowed (200 OK)
end
The Retry Storm Amplification Trap
Why a poorly configured rate limiter actually worsens cascading failures during a service outage.
Suppose a database slowdown increases API response time to 2,000ms. Clients time out after 1,000ms and immediately retry.
The rate limiter rejects retried requests with 429 Too Many Requests. However, if clients lack exponential backoff and jitter, they retry the 429 immediately.
Incoming request rate $\lambda$ quadruples from 100k to 400k req/s. The edge rate limiter CPU saturates evaluating Lua scripts, degrading edge proxy throughput and turning a partial database outage into a total edge outage.
-
Retry-After Header Standards: Every 429 response must include
Retry-After: {seconds}to force client libraries to sleep before retrying. - Fail-Open Circuit Breakers: If Redis cluster latency exceeds 5ms or errors spike > 2%, the rate limiting filter automatically switches to fail-open pass-through mode.
- Client Exponential Backoff with Jitter: Enforce client SDKs to implement Decorrelated Jitter: $T_{\text{wait}} = \min(M, \text{random}(B, T_{\text{prev}} \times 3))$.
Six-Component Rate Limiting Grid
The distributed architecture providing low-latency token evaluation across multi-region edge locations.
Simulate the Rate Limiter Topology Live
Test Token Bucket burst capacity, trigger malicious client retry storms, and verify fail-open circuit breaker behavior in the live simulator.