StackMonkey
Home / Templates / API Rate Limiter

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.

Evaluated Throughput
1,000,000 req/s
Edge gateway evaluation
Latency Overhead SLA
< 2.0 ms
p99 added evaluation time
Active Rate Entities
100M keys
Per-IP & per-token buckets
Partition Policy
Fail-Open
Zero outage propagation
Step 1 of 4

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.
Step 2 of 4

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 key = KEYS[1]
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
Step 3 of 4

The Retry Storm Amplification Trap

Why a poorly configured rate limiter actually worsens cascading failures during a service outage.

The Exponential Explosion

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.

Production Mitigations
  • 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))$.
Step 4 of 4

Six-Component Rate Limiting Grid

The distributed architecture providing low-latency token evaluation across multi-region edge locations.

01 路 Edge Gateway Wasm Filter
Envoy Proxy / Cloudflare Worker
Inspects API keys, user IDs, and client IP addresses on ingress. Evaluates local token cache in < 0.1ms before proxying upstream.
02 路 Central Atomic Counter Store
Redis 7 Cluster (CL.THROTTLE)
Sharded cluster partitioned by hash of client identifier. Executes atomic token bucket updates via C-optimized internal modules.
03 路 Local Token Reservoir
In-Memory Guava / Go Bucket
Maintains local quota batches per pod. Asynchronously synchronizes token replenishments with Redis in background threads every 100ms.
04 路 Rules Engine Control Plane
etcd / Consul Configuration Bus
Stores dynamic rate limit rules (e.g. tier-based limits: Free vs Enterprise). Propagates rule updates to edge proxies in sub-1s without restarts.
05 路 Abuse & Telemetry Stream
Kafka 429 Metric Pipeline
Logs all rate-limited events asynchronously. Flink anomaly detectors identify coordinated bot attacks and trigger automated IP bans.
06 路 Resiliency Circuit Breaker
Resilience4j / Envoy Circuit Filter
Monitors health of the Redis counter tier. Immediately bypasses rate limiting during internal cluster failures to protect production availability.
Interactive Discrete Event Simulation

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.