The user wants a "distributed rate limiter" that works across "multiple servers".
1. Understand the Core Requirement:
- Goal: Limit the number of requests a user/client can make to a service within a specific time window.
- Constraint: The service runs on multiple nodes (servers).
- Implication: A simple in-memory solution (like a Go map or Python dict) won't work because a request hitting Server A won't know about the request count on Server B.
- Solution: We need a centralized, shared state storage that is fast and supports atomic operations.
2. Choose the Right Tool:
- Redis: This is the industry standard for this specific problem.
- Why? It's in-memory (fast), supports atomic commands (critical for race conditions), and is easily accessible by all application servers.
3. Choose the Algorithm:
There are several rate-limiting algorithms:
- Fixed Window: Simple, but allows "bursting" at the boundary of the window (e.g., 5 requests at 0:59 and 5 at 1:01 = 10 requests in 2 seconds).
- Sliding Log: Accurate, but memory intensive (storing timestamps).
- Token Bucket / Leaky Bucket: Good for traffic shaping (smoothing out flow), often used in API gateways.
- Sliding Window (Approximated): The best balance of performance and accuracy for general API rate limiting. It uses the previous window's count to weight the current limit.
Decision: I will implement the Sliding Window algorithm using Redis. It's efficient and solves the "fixed window bursting" problem better than a simple Fixed Window, though Fixed Window is easier to explain. Actually, for a clear tutorial, Fixed Window is often the starting point, but Sliding Window is the "pro" version. Let's stick to a robust Fixed Window first for simplicity, or maybe the Token Bucket?
Re-evaluating: The standard Redis pattern for rate limiting usually involves Lua scripts for atomicity. The "GCRA" (Generic Cell Rate Algorithm) or the simple "Fixed Window with Lua" is common.
Let's go with the "Fixed Window" logic first because it's easier to understand, but I will mention Sliding Window as an improvement.
Actually, the most common robust implementation is the Token Bucket or Sliding Window.
Let's implement a Lua Script based Sliding Window Counter. It's performant and accurate enough.
Wait, let's keep it simple but effective. The most standard interview-ready answer is usually Redis + Lua Script.
4. Programming Language:
- Python is widely understood. Node.js and Go are also popular. I'll use Python with
redis-py as it's very readable.
5. Architecture Design:
- Client -> Load Balancer -> Server A / Server B -> Redis.
- The logic lives on the servers.
- The state lives in Redis.
6. Implementation Details (The "How"):
- Key:
rate_limit:{user_id}:{endpoint}
- Value: Count of requests.
- TTL: Expiration time.
Algorithm Logic (Lua Script for atomicity):
- Get current count.
- If count < limit: Increment and allow.
- If count >= limit: Deny.
- Correction: If we just do
GET, then INCR, that's two network round trips and not atomic without transactions. Using a Lua script sends the logic to Redis to execute atomically.
Refining the Algorithm (Sliding Window Log vs Fixed Window):
Let's use a simplified Token Bucket approach or the Generic Cell Rate Algorithm (GCRA)? No, that's too complex for a basic example.
Let's use the "Moving Window" approach (often called Sliding Window) where we store timestamps in a sorted set (ZSET).
- Concept: Store the timestamp of every request in a ZSET.
- Cleanup: Remove old timestamps outside the window.
- Count: Check the size of the ZSET.
- Pros: perfectly accurate.
- Cons: Memory usage can be high if request volume is massive.
- Better Alternative: The Sliding Window Counter (approximation). Current_Rate=.
Actually, let's do the Token Bucket implementation using Redis. It is very standard.
No, let's stick to the Generic Rate Limiter pattern: Lua script for Fixed Window. It's the standard Redis recipe.
7. Drafting the Code (Mental Draft):
import redis
import time
# Lua script to check limit atomically
# KEYS[1] = key
# ARGV[1] = limit
# ARGV[2] = window_size
script = """
local current
current = redis.call("incr", KEYS[1])
if current == 1 then
redis.call("expire", KEYS[1], ARGV[2])
end
if current > tonumber(ARGV[1]) then
return 0
else
return 1
end
"""
Critique of this script: It has a race condition. If the process crashes after incr but before expire, the key lives forever.
Better script: Use INCR and check if it's the first one to set expiry. Or use SET with NX and EX? No, we need to increment.
The standard Lua script:
local tokens_key = KEYS[1]
local timestamp = tonumber(ARGV[1])
local replenish_rate = tonumber(ARGV[2])
local capacity = tonumber(ARGV[3])
-- This is getting complex (Token Bucket).
Let's go back to the simplest robust solution: Sorted Sets (ZSET) for a Sliding Window. It handles the edge cases of Fixed Window and is memory efficient enough for reasonable limits (e.g., 100 req/min).
Algorithm (Sliding Window using ZSETS):
- Key:
limit:user_id
ZREMRANGE: Remove elements with score (timestamp) < now - window.
ZCARD: Count remaining elements.
- If count < limit:
ZADD current timestamp, return OK.
- Else: return Limit Exceeded.
- Set expiry on the key.
8. Structure of the Answer:
- Conceptual Overview: Why distributed? Why Redis? The architecture diagram (in text).
- Prerequisites: Redis installed, Python installed.
- The Implementation (Python + Redis): A class that wraps the logic. Using a Lua script is best for network efficiency and atomicity.
- Code Breakdown: Explain the Lua script part clearly.
- Simulation: Code to simulate multiple "servers" hitting the limiter.
- Production Considerations: Race conditions, latency, fallback strategies.
9. Refining the Code Implementation:
I'll provide a Python solution using the redis library.
The Lua Script (Sliding Window - Sorted Set approach):
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2]) -- in seconds
local now = tonumber(ARGV[3])
-- 1. Remove old items
redis.call('ZREMRANGE', key, 0, now - window * 1000) -- assuming milliseconds
-- 2. Get count
local count = redis.call('ZCARD', key)
-- 3. Check limit
if count < limit then
redis.call('ZADD', key, now, now .. '-' .. math.random()) -- unique member
redis.call('EXPIRE', key, window)
return 1 -- allowed
else
return 0 -- denied
end
Correction: now - window * 1000 depends on unit. Let's stick to seconds or milliseconds consistently.
Actually, for a simple fixed window, the code is shorter and easier to digest.
Decision: I will provide the Fixed Window algorithm first because it is the standard "Hello World" of rate limiting, but I will mention the boundary issue and suggest the Sliding Window or Token Bucket for production if strict smoothing is needed.
Wait, the user asked for "Create a distributed rate limiter". A Fixed Window with burst issues is often considered a "bad" limiter.
Let's implement the Token Bucket algorithm or GCRA. These are state-of-the-art.
Actually, let's stick to the Generic Cell Rate Algorithm (GCRA) or Sliding Window Log.
Let's go with Sliding Window Log (using ZSET). It's intuitive: "Count requests in the last minute".
10. Drafting the Final Content:
- Architecture: App Servers <-> Redis.
- Algorithm: Sliding Window (using Redis Sorted Sets). It prevents the "end-of-window" burst spike inherent in Fixed Window limiters.
- Language: Python.
Step-by-Step Code Construction:
- Import redis.
- Define the Lua script (Atomic execution).
- Lua script logic:
- Clear out timestamps older than
now - window.
- Count remaining timestamps.
- If count < limit: Add current timestamp, return True.
- Else: Return False.
- Python wrapper class
RateLimiter.
- Example usage.
Self-Correction/Refinement during thought process:
- Issue: If I just dump the code, they might not know how to run it.
- Fix: Include a
docker run command for Redis so they can spin it up instantly.
- Issue: Network latency between App and Redis.
- Fix: Mention that the Lua script runs on the Redis server, minimizing round trips.
Final Plan:
- Concept: Explain the "Why" (Centralized state).
- Tool: Redis (Fast, Atomic).
- Algorithm: Sliding Window using Sorted Sets (ZSets).
- Code: Full Python script with Lua integration.
- Testing: A script simulating concurrent access.
Let's write the response.
Creating a distributed rate limiter requires a centralized storage system that all your servers can talk to. The industry standard for this is Redis.
Below is a complete, production-ready implementation using the Sliding Window Log algorithm. This algorithm is preferred over a simple "Fixed Window" (e.g., "100 requests per minute") because it prevents "boundary bursts" (where a user makes 100 requests at 0:59 and another 100 at 1:01).
The Architecture
- In-Memory (Local): Cannot be used. Server A doesn't know how many requests Server B has processed.
- Redis: Acts as the shared counter.
- Lua Scripting: We will use a Lua script running inside Redis. This is crucial for Atomicity. We need to "check the count" and "add a timestamp" in a single step. If we did this in Python code, a race condition could occur where two servers read the count at the exact same time and both let a request through.
The Solution (Python + Redis)
You will need the redis library: pip install redis
import redis
import time
import uuid
class DistributedRateLimiter:
def __init__(self, redis_host='localhost', redis_port=6379, limit=100, window_size_seconds=60):
"""
:param limit: Max requests allowed in the window
:param window_size_seconds: Size of the sliding window
"""
self.redis_client = redis.StrictRedis(host=redis_host, port=redis_port, decode_responses=True)
self.limit = limit
self.window_size = window_size_seconds
# Lua script for atomic execution
# Logic:
# 1. Remove timestamps older than the window
# 2. Count remaining items
# 3. If count < limit, add current timestamp and return True
# 4. Else, return False
self.lua_script = """
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local current_time = tonumber(ARGV[3])
-- Remove items outside the window
redis.call('ZREMRANGEBYSCORE', key, 0, current_time - window)
-- Get the current count
local count = redis.call('ZCARD', key)
if count < limit then
-- Add the current request timestamp
-- We use a random UUID just to ensure the member value is unique if timestamps are identical
redis.call('ZADD', key, current_time, current_time .. '-' .. math.random())
-- Reset the expiry for the key to clean up memory
redis.call('EXPIRE', key, window)
return 1 -- Allowed
else
return 0 -- Denied
end
"""
self.script_sha = self.redis_client.script_load(self.lua_script)
def is_allowed(self, user_id):
"""
Checks if a request is allowed for a specific user.
"""
key = f"rate_limit:{user_id}"
current_time = time.time()
# Execute the Lua script atomically
# KEYS[1] = key, ARGV[1] = limit, ARGV[2] = window, ARGV[3] = now
result = self.redis_client.evalsha(
self.script_sha,
1,
key,
self.limit,
self.window_size,
current_time
)
return bool(result)
# --- Usage Simulation ---
if __name__ == "__main__":
# Configuration: 5 requests allowed every 10 seconds
limiter = DistributedRateLimiter(limit=5, window_size_seconds=10)
user_id = "user_123"
print(f"Testing rate limit for {user_id} (Limit: 5, Window: 10s)")
for i in range(7):
allowed = limiter.is_allowed(user_id)
status = "ALLOWED" if allowed else "BLOCKED"
print(f"Request {i+1}: {status}")
time.sleep(1) # Simulate time passing
How it Works (Deep Dive)
1. The Data Structure: Sorted Set (ZSET)
We use a Redis Sorted Set to store the request history.
- Key:
rate_limit:user_123
- Member: A unique ID for the request (e.g.,
timestamp-random_uuid). We combine the timestamp with a random number because Sorted Sets are sets; if two requests happen at the exact same millisecond, the second one would overwrite the first if we only used the timestamp.
- Score: The timestamp (Unix epoch) of the request.
2. The Lua Script (Atomic Logic)
When is_allowed is called, the following happens entirely inside the Redis server engine:
- Clean Up (
ZREMRANGEBYSCORE): We delete all entries from the set that have a timestamp older than Current Time - Window Size. This effectively "slides" the window.
- Count (
ZCARD): We count how many items are left in the set. These represent requests made within the valid time window.
- Decide:
- If
count < limit: We add the new timestamp (ZADD) and return 1 (True). We also set an expiration (EXPIRE) on the key so that if the user stops making requests, Redis cleans up the memory automatically.
- If
count >= limit: We do nothing and return 0 (False).
Why this is Production Grade
- Atomicity: Because the logic is in a Lua script, Redis guarantees that no other command runs between the "Check" and the "Add". This prevents race conditions where 10 servers check the limit simultaneously and all think they are safe to proceed.
- Memory Efficiency: We use
EXPIRE. If a user makes 1 request and never comes back, that key will eventually be evicted by Redis, preventing a memory leak.
- Accuracy: Unlike a "Leaky Bucket" or "Token Bucket" which usually requires a background thread to refill tokens, the Sliding Window Log calculates the limit based on the actual history of requests. It is mathematically accurate to the millisecond.
Alternative Algorithms
While the Sliding Window Log is excellent for strict accuracy, here are two other common approaches: