System DesignOct 22, 2026⏱️ 4 min read
Design a Distributed Rate Limiter: Token Bucket, Sliding Window & Redis Lua

Design a Distributed Rate Limiter: Token Bucket, Sliding Window & Redis Lua

Why Every Public API Needs a Rate Limiter

Without rate limiting, a single misconfigured retry loop, scraper, or DDoS spike can saturate database connection pools, exhaust downstream LLM/cloud quotas, and take down healthy tenants.
A Rate Limiter caps traffic per client IP, API key, or user ID before requests reach expensive upstream services.
Distributed Rate Limiter Architecture

Distributed Rate Limiter Architecture


1. Where Should the Rate Limiter Live?

PlacementProsConsBest Fit
Client-SideZero server overheadEasily bypassed / forgedNever rely on alone
Application MiddlewareAware of domain logic & user tiersCouples infra rules to app codeMonoliths / custom rules
API Gateway / Reverse ProxyCentralized across all microservicesNeeds shared state (Redis) for clustersMicroservices (Envoy, Kong, Nginx)

2. Core Rate Limiting Algorithms Compared

AlgorithmBurst ToleranceMemory UsageEdge Boundary AccuracyCommon Users
Token BucketAllows short burstsVery Low ($O(1)$)GoodAmazon API Gateway, Stripe
Leaking BucketSmooth fixed outflowLowGoodShopify, network traffic shaping
Fixed Window CounterCan allow 2× burst at boundaryVery Low ($O(1)$)Weak at window edgesSimple counters
Sliding Window LogStrict accuracyHigh (stores every timestamp)ExactSecurity / auth endpoints
Sliding Window CounterSmooth + accurateVery Low ($O(1)$)~99.99% accurateCloudflare, high-scale APIs

How Token Bucket Works

  1. Each user gets a virtual bucket with capacity $B$ tokens.
  2. Tokens refill continuously at rate $R$ tokens/sec (capped at $B$).
  3. Incoming request consumes 1 token: if tokens $\ge 1$, allow; otherwise return HTTP 429 Too Many Requests.

3. Standard HTTP Rate Limit Response Headers

Always inform well-behaved clients how to back off cleanly:
http
HTTP/1.1 429 Too Many Requests X-Ratelimit-Limit: 100 X-Ratelimit-Remaining: 0 X-Ratelimit-Reset: 1793450400 Retry-After: 42

4. Solving Distributed Race Conditions with Redis Lua

In a multi-node cluster, naive GET followed by SET in Redis suffers from a read-modify-write race condition: two concurrent requests read remaining = 1, both succeed, and violate the quota.
Executing the check-and-decrement inside a Redis Lua script guarantees single-threaded atomicity:
lua
-- token_bucket.lua -- KEYS[1]: rate limit key (e.g., "rl:user:123") -- ARGV[1]: capacity, ARGV[2]: refill_rate_per_sec, ARGV[3]: current_timestamp_sec local key = KEYS[1] local capacity = tonumber(ARGV[1]) local refill_rate = tonumber(ARGV[2]) local now = tonumber(ARGV[3]) local bucket = redis.call("HMGET", key, "tokens", "last_refill") local tokens = tonumber(bucket[1]) local last_refill = tonumber(bucket[2]) if tokens == nil then tokens = capacity last_refill = now else local elapsed = math.max(0, now - last_refill) tokens = math.min(capacity, tokens + elapsed * refill_rate) last_refill = now end local allowed = 0 if tokens >= 1 then tokens = tokens - 1 allowed = 1 end redis.call("HMSET", key, "tokens", tokens, "last_refill", last_refill) redis.call("EXPIRE", key, math.ceil(capacity / refill_rate) * 2) return { allowed, math.floor(tokens) }

5. Production Hardening & Fail-Open vs Fail-Closed

  • Fail-Open: If the Redis rate-limit cluster has an outage, log an alert and allow traffic through so a cache blip doesn't cause a total site outage.
  • Local Caching of Rules: Keep throttle rules in memory on gateway nodes (refreshed asynchronously) rather than querying a SQL DB on every request.
  • Multi-Data Center: Use sticky region routing for users or asynchronous gossip/CRDT counters when global sub-millisecond syncing isn't feasible.

Share this article

Comments