1. Understand the Goal: The user wants to implement a distributed rate limiter. This implies a system where multiple application instances (servers) need to coordinate to enforce a global rate limit (e.g., 100 requests per minute across the entire cluster, not just per individual server).
-
Identify the Core Challenge:
- Standard rate limiting (e.g., using a token bucket in memory on a single server) is easy but doesn't work for distributed systems because Server A doesn't know about requests handled by Server B.
- We need a shared state or a synchronization mechanism.
-
Determine the Best Approach:
- Approach 1: Sticky Sessions. (Not really a distributed rate limiter, just sidestepping the issue. Bad for load balancing).
- Approach 2: Database Polling. (Too slow, high latency, contention).
- Approach 3: Redis (In-memory Data Store). This is the industry standard. Redis is fast, atomic, and supports operations that make rate limiting efficient.
-
Select the Algorithm:
- Fixed Window: Simple, but allows bursts at the boundary (e.g., 100 req/min. 99 at 00:59, 100 at 01:01 = 199 in 2 seconds).
- Sliding Log: Precise, but memory intensive (storing every timestamp).
- Token Bucket / Leaky Bucket: Good for shaping traffic, but harder to implement atomically in Redis without Lua scripts.
- Sliding Window (Hybrid): This is usually the best balance of performance and accuracy. It combines the memory efficiency of Fixed Window with the smoothed boundaries of Sliding Log.
-
Design the Solution (The "Sliding Window Log" or "Approximated Sliding Window" approach):
- I will use the Generic Cell Rate Algorithm (GCRA) or a simpler Lua Script based Sliding Window.
- Actually, the most common and easiest to understand robust implementation is the Token Bucket or Leaky Bucket implemented via a Lua script in Redis to ensure atomicity.
- Alternative: The "Fixed Window with Overlap" (Sliding Window approximation).
- Decision: Let's go with a Lua Script based Fixed Window Counter with Sliding Window logic (often just called "Sliding Window" in Redis contexts). It's performant and prevents the boundary burst issue better than simple Fixed Window.
- Actually, let's stick to the standard Token Bucket algorithm implemented in Lua. It's intuitive. Or the Leaky Bucket.
- Re-evaluating: The most requested implementation usually involves a simple "X requests per Y seconds". A Fixed Window counter is the easiest to code, but let's provide the Sliding Window approach using Redis Sorted Sets (ZSETs) because it's accurate and demonstrates the distributed nature well.
Wait, let's look at performance vs. complexity.
- Simple Counter:
INCR. Fast. Bursty at edges.
- Sorted Set (Sliding Log):
ZADD + ZREMRANGEBYSCORE + ZCARD. Accurate. Slightly heavier on memory if traffic is huge, but fine for most uses.
- Token Bucket (Lua): Requires storing tokens and a timestamp.
Decision: I will implement the Token Bucket algorithm using a Redis Lua script. Why? Because it's the classic "shaping" algorithm and guarantees atomicity without race conditions, which is the biggest pitfall in distributed systems.
-
Drafting the Architecture:
- Client: Sends request.
- Middleware/Service: Checks with Rate Limiter.
- Rate Limiter: Connects to Redis, runs logic.
- Redis: Stores state (tokens, last update time).
-
Code Structure (Python/Redis example):
- Python is readable.
redis-py library.
- Lua script for the atomic check-and-decrement.
-
Refining the Lua Script (Token Bucket):
- Keys:
key (identifier, e.g., user_id).
- Args:
capacity, rate (refill rate), timestamp.
- Logic:
- Get current state (tokens, last_time).
- Calculate elapsed time.
- Refill tokens based on elapsed time (capped at capacity).
- If tokens >= 1:
- tokens -= 1
- allowed = true
- Else:
- Save state.
- Return allowed + remaining tokens.
-
Addressing "Distributed" nuances:
- Clock Skew: System clocks on different servers might vary.
- Solution: Use Redis's
TIME command inside the Lua script instead of passing time from the app server. This ensures a single source of truth for time.
- Race Conditions: Lua scripts in Redis are executed atomically (blocking other commands for the key), solving the race condition.
-
Structuring the Response:
- Introduction: Why it's hard (shared state).
- Architecture: Redis + Lua.
- Algorithm: Token Bucket (allows bursting, smooth refill).
- Implementation (Python): Code snippet.
- The Lua Script: The critical part.
- Edge Cases/Production Readiness: Latency, Clock Skew, Fail-open vs Fail-close.
-
Self-Correction during drafting:
- Initial thought: Just use
INCR and EXPIRE.
- Correction: That's a Fixed Window. It suffers from the "thundering herd" problem at minute boundaries. A Token Bucket is better.
- Lua Script Detail: Make sure to handle the "first time" case (key doesn't exist).
-
Finalizing Code Snippet:
- Need a class
DistributedRateLimiter.
- Method
allow_request(key).
- Redis connection handling.
-
Adding Context: Explain why Lua is necessary (atomicity). Explain why Redis (speed).
-
Review against User Prompt: "Create a distributed rate limiter..." -> Yes, the solution covers multiple servers sharing one Redis instance.
Let's write the code.
- Algorithm: Generic Cell Rate Algorithm (GCRA) or Token Bucket. Let's stick to Token Bucket as it's conceptually easier to explain (Bucket holds tokens, refill over time).
- Lua Script logic:
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2]) -- tokens per second to add
local now = redis.call('TIME') -- Array: {seconds, microseconds}
-- convert to float
local now_f = tonumber(now[1]) + tonumber(now[2]) / 1000000
local info = redis.call('HMGET', key, 'tokens', 'last_time')
local tokens = tonumber(info[1])
local last_time = tonumber(info[2])
if tokens == nil then
tokens = capacity
last_time = now_f
end
-- Calculate refill
local delta = math.max(0, now_f - last_time)
local filled_tokens = delta * rate
tokens = math.min(capacity, tokens + filled_tokens)
local allowed = 0
if tokens >= 1 then
tokens = tokens - 1
allowed = 1
end
redis.call('HMSET', key, 'tokens', tokens, 'last_time', now_f)
redis.call('EXPIRE', key, math.ceil(capacity/rate) + 10) -- cleanup
return {allowed, tokens}
Refinement: redis.call('TIME') is available in Redis 5+. If older, pass time from app. I will use TIME for clock synchronization safety but mention the version requirement.
- Constructing the final output:
- Overview.
- The Algorithm (Token Bucket).
- The Code (Python + Redis).
- Explanation of components.
- Scaling considerations.
(Self-Correction during final review): Is there a simpler way? The "Leaky Bucket" implemented as a list is also common, but Token Bucket is usually preferred for API rate limiting where bursts are okay. I will stick to Token Bucket.
Let's refine the Python code to be clean and production-ready style (using a class).
One specific detail: The Lua script needs to handle the initialization correctly.
Also, the EXPIRE is important so we don't fill Redis with keys for users who visited once a year ago.
Let's write it out.
Designing a distributed rate limiter requires solving two main problems: Shared State (all servers must know the global request count) and Atomicity (race conditions must be prevented).
The most common architectural pattern uses Redis as the shared state store and Lua Scripts to ensure atomic operations.
Below is a complete design and implementation using the Token Bucket Algorithm.
The Architecture
- Algorithm: Token Bucket.
- Concept: A "bucket" holds tokens (e.g., 100). Requests consume 1 token. Tokens refill at a set rate (e.g., 10/second). If the bucket is empty, the request is denied.
- Storage: Redis.
- Used because it is in-memory (fast) and supports atomic execution of Lua scripts.
- Logic Flow:
- Application receives a request for
User_A.
- App sends a command to Redis: "Check and decrement tokens for
User_A".
- Redis executes a script that calculates current tokens based on time, checks if tokens > 0, and decrements—all in one atomic step.
- Redis returns "Allowed" or "Denied".
Implementation (Python & Redis)
Here is a production-ready Python implementation.
Prerequisites:
pip install redis
Ensure you have a Redis server running.
1. The Lua Script
This is the core logic. We use Lua because it runs inside the Redis server. This guarantees that no other request can read the counter between our "read" and "update" operations (preventing race conditions).
import redis
import time
import math
# Lua script for Token Bucket Algorithm
# KEYS[1]: The unique identifier (e.g., user_id or IP)
# ARGV[1]: Capacity (Max tokens)
# ARGV[2]: Refill Rate (Tokens added per second)
# ARGV[3]: Cost (Usually 1)
# ARGV[4]: Current Timestamp (passed from app to ensure time consistency)
TOKEN_BUCKET_SCRIPT = """
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local now = tonumber(ARGV[4])
-- Get current bucket state
local info = redis.call('HMGET', key, 'tokens', 'last_refill')
local tokens = tonumber(info[1])
local last_refill = tonumber(info[2])
-- Initialize if nil
if tokens == nil then
tokens = capacity
last_refill = now
end
-- Calculate refill
local interval = math.max(0, now - last_refill)
local filled = interval * rate
-- Update tokens, cap at capacity
tokens = math.min(capacity, tokens + filled)
-- Check if enough tokens
local allowed = false
if tokens >= cost then
tokens = tokens - cost
allowed = true
last_refill = now -- Reset timer to now to start calculating next refill
end
-- Save state
redis.call('HMSET', key, 'tokens', tokens, 'last_refill', last_refill)
redis.call('EXPIRE', key, math.ceil(capacity / rate) + 60) -- Cleanup idle keys
return {allowed, tokens}
"""
2. The Python Rate Limiter Class
class DistributedRateLimiter:
def __init__(self, redis_host='localhost', redis_port=6379):
self.redis_client = redis.StrictRedis(host=redis_host, port=redis_port, decode_responses=True)
# Register the Lua script
self.script_sha = self.redis_client.script_load(TOKEN_BUCKET_SCRIPT)
def is_allowed(self, key: str, capacity: int, refill_rate: float, cost: int = 1) -> bool:
"""
key: Unique identifier (e.g., 'user_123')
capacity: Max burst size (e.g., 10)
refill_rate: Tokens per second (e.g., 0.5 = 1 token every 2 seconds)
"""
current_time = time.time()
try:
# Execute the atomic Lua script
# We use eval_sha for performance (sends hash instead of full script text)
result = self.redis_client.evalsha(
self.script_sha,
1, # Number of keys
key, # KEYS[1]
capacity, # ARGV[1]
refill_rate, # ARGV[2]
cost, # ARGV[3]
current_time # ARGV[4]
)
allowed = bool(int(result[0]))
remaining = int(result[1])
return allowed, remaining
except redis.exceptions.NoScriptError:
# If script was cleared from Redis cache (rare), reload it
self.script_sha = self.redis_client.script_load(TOKEN_BUCKET_SCRIPT)
return self.is_allowed(key, capacity, refill_rate, cost)
except Exception as e:
print(f"Redis error: {e}")
# Fail-safe strategy: If Redis goes down, do you block everyone or let everyone in?
# Usually, let them in (return True) to prevent total outage, but log the error.
return True, 0
# --- Usage Example ---
limiter = DistributedRateLimiter()
# Configuration: Allow 5 requests max, refills 1 token per second
user_id = "user_123_api"
MAX_BURST = 5
REFILL_PER_SEC = 1.0
print(f"Limiting for {user_id} (Max: {MAX_BURST}, Rate: {REFILL_PER_SEC}/s)")
for i in range(1, 8):
allowed, remaining = limiter.is_allowed(user_id, MAX_BURST, REFILL_PER_SEC)
status = "ALLOWED" if allowed else "BLOCKED"
print(f"Request {i}: {status} (Remaining: {remaining})")
if i == 5:
print("... Waiting 2 seconds to refill tokens ...")
time.sleep(2)
Key Technical Details
1. Why use Lua Scripts?
In a distributed environment, network latency causes race conditions.
- Bad Approach (Application Logic):
- App:
GET count
- App:
if count < 10: count++
- App:
SET count
- Problem: If two requests happen at the exact same time, they both read
count=9, both increment to 10, and both allow the request. You effectively allowed double the limit.
- Good Approach (Lua): Redis executes Lua scripts atomically. The server blocks other commands while the script runs. The logic "Check -> Update -> Return" happens in a single step.
2. Performance Optimization (EVALSHA)
Sending the full Lua script text over the network for every request is slow.
- We use
SCRIPT LOAD once during initialization. This returns a SHA hash.
- We send
EVALSHA <hash> .... Redis looks up the hash in its memory and executes it. This significantly reduces bandwidth usage.
3. Handling Clock Skew
In this implementation, we pass time.time() from the Application to Redis.
- Why? While Redis has its own time (
TIME command), in high-precision scenarios, you want the logic to be based on the timestamp when the request hit your application server, not when it reached Redis (which might be milliseconds later due to network latency).
- Note: For strict consistency across distributed app servers, ensure your servers use NTP (Network Time Protocol) to sync their clocks.
4. Failure Modes (Circuit Breaking)
What happens if the Redis server crashes?
- Strict Mode: Return
False (Block all requests). Good for critical security endpoints.
- Availability Mode: Return
True (Allow all requests). Good for general web traffic where a 503 error is worse than a slight overload. In the code above, the try/except block implements Availability Mode.