Initial thought: Just write Python code for everything.
Correction: The user asked for "Distributed counters (Redis)". Python local variables won't cut it. I must show the Redis command or Lua script.
Initial thought: Just say "add headers".
Correction: Be specific. Mention standard headers like Retry-After and custom ones like X-RateLimit-Remaining.
Final Polish: Ensure the distinction between "Rate Limiting" (Dropping requests) and "Throttling" (Slowing down/Queuing requests) is clear, though they are often used interchangeably.
Let's build the content.
Token Bucket: capacity vs rate.
Leaky Bucket: Queue implementation.
Fixed vs Sliding: Fixed creates spikes at window edges (minute boundaries). Sliding fixes this.
Redis Keys: rl:{user_id}:{endpoint}.
Okay, I'm ready to generate the response following this structure.
Here is a comprehensive guide to implementing rate limiting and throttling patterns, covering algorithms, distributed systems, resilience, and observability.
1. Core Algorithms
A. Token Bucket (Burst Handling)
Best for: API endpoints where you want to allow short bursts of traffic but limit the average rate over time.
Logic: A bucket holds tokens (max capacity N). Tokens refill at a constant rate R. Each request consumes one token. If empty, request denied.
Pros: Allows bursts (good for user experience), memory efficient.
python
import time
class TokenBucket:
def __init__(self, rate, capacity):
self.rate = rate # Tokens added per second
self.capacity = capacity # Max bucket size
self.tokens = capacity
self.last_time = time.time()
def allow_request(self):
now = time.time()
# Calculate tokens added since last call
elapsed = now - self.last_time
self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
self.last_time = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
B. Leaky Bucket (Traffic Smoothing)
Best for: Background workers or payment processing where you need a strict, constant output rate (no bursts).
Logic: Requests enter a queue (bucket). The queue processes requests at a fixed rate (leak). If the queue is full, the request is dropped.
Pros: Smooths traffic flow perfectly. Cons: Latency increases as the queue fills.
python
from collections import deque
import time
import threading
class LeakyBucket:
def __init__(self, rate, capacity):
self.rate = rate # Processing rate (req/s)
self.capacity = capacity
self.queue = deque()
self.thread = threading.Thread(target=self._leak, daemon=True)
self.thread.start()
def _leak(self):
while True:
if self.queue:
# Process item (simulated)
self.queue.popleft()
time.sleep(1.0 / self.rate)
def allow_request(self):
if len(self.queue) < self.capacity:
self.queue.append(1) # 1 represents a request
return True
return False
C. Sliding Window Log (Strict Precision)
Best for: Preventing stampedes at minute boundaries (e.g., preventing exactly 100 requests at 12:00:59 and 100 more at 12:01:01).
Logic: Store timestamps of every request in a sorted set. Query the set to count requests in the last T seconds.
Pros: Very accurate. Cons: Memory intensive if volume is high (storing many timestamps).
2. Distributed Rate Limiting (Redis)
In a microservices environment, local memory doesn't work. You need a centralized atomic counter.
Sliding Window Counter (Hybrid Approach)
This is the industry standard for distributed limiting. It combines the memory efficiency of Fixed Windows with the smoothed accuracy of Sliding Windows.
Formula:Count=CurrentWindowC
Redis Implementation (Lua Script for Atomicity):
This script runs inside Redis to ensure no race conditions occur between fetching the count and incrementing it.
lua
-- Lua Script (sliding_window.lua)
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2]) -- Window size in seconds
local current = redis.call('INCR', key)
if current == 1 then
redis.call('EXPIRE', key, window)
end
-- Simplification: This is a Fixed Window Counter.
-- For true Sliding Window Hybrid, you would fetch the previous key's count
-- and perform the weighted math in Lua or the application layer.
if current > limit then
return 0 -- Reject
else
return 1 -- Allow
end
Python Redis Integration:
python
import redis
import time
r = redis.Redis(host='localhost', port=6379, db=0)
def is_allowed(user_id, limit=10, window=60):
key = f"rate_limit:{user_id}"
# Using a simple Fixed Window approach for snippet brevity
# In production, use the Lua script above.
pipe = r.pipeline()
try:
current = r.incr(key)
if current == 1:
r.expire(key, window)
if current > limit:
return False
return True
except redis.exceptions.RedisError:
# Fail-open strategy (see section 4)
return True
3. Key Strategies & Burst Handling
Per-User / Per-IP Keys
You should layer your rate limits. A robust configuration looks like this:
Global Limit: 10,000 req/sec across the entire cluster (Protect infrastructure).
Per-IP Limit: 20 req/sec (Mitigate DDoS).
Per-User Limit: 5 req/sec (Fairness/Logic).
python
def get_rate_limit_key(user_id, ip_addr):
# Prioritize User ID if authenticated, else fall back to IP
identifier = f"user:{user_id}" if user_id else f"ip:{ip_addr}"
return f"limit:{identifier}"
4. Resilience Patterns
Idempotency (Preventing Double Charges)
Rate limiting stops flood; Idempotency ensures safety on retries. Clients send a unique Idempotency-Key. The server caches the response for that key.
python
# Middleware pseudo-code
def handle_request(request):
idempotency_key = request.headers.get('Idempotency-Key')
# Check Redis for existing result
if cache.exists(idempotency_key):
return cache.get(idempotency_key) # Return cached response (don't reprocess)
# Process logic...
response = process_business_logic(request)
# Cache result for 24 hours
cache.set(idempotency_key, response, ttl=86400)
return response
Backoff Strategies (Client & Server Side)
When a limit is hit, simply returning 429 isn't enough. You need to tell the client how long to wait.
Exponential Backoff: Wait 1s, then 2s, then 4s...
Jitter: Add randomness to backoff to prevent "thundering herd" (all clients retrying at the exact same second).
Server Response Headers:
http
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1678886400 (Unix Epoch)
Retry-After: 30 (Seconds)
Client Retry Logic:
python
import random
import time
def request_with_backoff(func, max_retries=5):
for attempt in range(max_retries):
response = func()
if response.status_code != 429:
return response
# Calculate wait: Base * 2^attempt + Jitter
wait = (2 ** attempt) + random.random()
print(f"Rate limited. Retrying in {wait:.2f}s")
time.sleep(wait)
5. Observability
You cannot tune what you cannot measure. Rate limiting should emit metrics, not just logs.