I need a rate limiter middleware for FastAPI using the sliding window log algorithm instead of fixed window. It should use Redis sorted sets to store timestamps with atomic Lua transactions for accuracy under high concurrency.
Assistant
Providing FastAPI rate limiter middleware with Redis and Lua
I'm preparing a complete Python example implementing a FastAPI middleware using Redis sorted sets and an atomic Lua script for sliding window rate limiting, ensuring concurrency-safe request counting per client IP.
Below is a minimal FastAPI middleware that applies a sliding window log rate limit using Redis sorted sets. It uses a Lua script to perform all Redis operations atomically (removing expired entries, inserting the new timestamp, counting, and setting TTL), which helps maintain accuracy under high concurrency.
Key points
Uses Redis sorted sets where each entry is a timestamp.
Sliding window log algorithm: on each request, remove timestamps older than window, add the current timestamp, then count how many remain.
The Lua script ensures these steps happen as a single atomic operation.
You can adapt the “key” to be per IP, per user ID, etc.
Example code
python
import time
from fastapi import FastAPI, Request, HTTPException
from starlette.middleware.base import BaseHTTPMiddleware
from redis import asyncio as aioredis
# -------------------------------------------------------------------
# Redis connection
# -------------------------------------------------------------------
# Make sure Redis is running and reachable at these settings:
redis_client = aioredis.Redis(host="localhost", port=6379, db=0)
# -------------------------------------------------------------------
# Lua script for sliding window log
# -------------------------------------------------------------------
# Args:
# KEYS[1] = rate limit key
# ARGV[1] = now (ms)
# ARGV[2] = window size (ms)
# ARGV[3] = limit (integer)
# ARGV[4] = unique member for ZADD (e.g. timestamp + random)
#
# Returns:
# 1 if allowed, 0 if rate limit exceeded
SLIDING_WINDOW_LUA = """
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local member = ARGV[4]
-- 1) Remove old entries
redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window)
-- 2) Add the current timestamp as a unique member
redis.call('ZADD', key, now, member)
-- 3) Count how many are in the window
local count = redis.call('ZCARD', key)
-- 4) Set expiration to avoid unbounded growth
redis.call('PEXPIRE', key, window)
-- 5) If count exceeds limit, deny
if count > limit then
return 0
else
return 1
end
"""
# Preload the script into Redis to get a SHA (optional but recommended)
async def load_lua_scripts():
await redis_client.script_load(SLIDING_WINDOW_LUA)
# -------------------------------------------------------------------
# Rate Limit Middleware
# -------------------------------------------------------------------
class SlidingWindowRateLimitMiddleware(BaseHTTPMiddleware):
def __init__(self, app, window_ms: int, max_requests: int, key_prefix: str = "rate-limit"):
super().__init__(app)
self.window_ms = window_ms
self.max_requests = max_requests
self.key_prefix = key_prefix
async def dispatch(self, request: Request, call_next):
# Identify the client (customize as needed)
# Example: per-IP limiting. You could also use an auth token, user ID, etc.
client_id = request.client.host if request.client else "unknown"
redis_key = f"{self.key_prefix}:{client_id}"
# Current timestamp in ms
now_ms = int(time.time() * 1000)
# Member is timestamp plus some suffix to ensure uniqueness
member = f"{now_ms}-{client_id}"
try:
# Evaluate the script atomically
allowed = await redis_client.eval(
SLIDING_WINDOW_LUA,
1, # number of keys
redis_key,
now_ms,
self.window_ms,
self.max_requests,
member
)
except Exception as e:
# If Redis is down or another error occurs, decide whether to allow or block
# Here we allow by default; adjust to your policy
allowed = 1
if allowed == 0:
# Rate limit exceeded
raise HTTPException(status_code=429, detail="Rate limit exceeded")
# Otherwise proceed to the next middleware/route
response = await call_next(request)
return response
# -------------------------------------------------------------------
# FastAPI app
# -------------------------------------------------------------------
app = FastAPI()
# Configure your rate limit here:
# window_ms = 60000 means 60 seconds
# max_requests = 100 means allow up to 100 requests per 60s
app.add_middleware(
SlidingWindowRateLimitMiddleware,
window_ms=60000,
max_requests=100,
)
@app.on_event("startup")
async def on_startup():
# Pre-load Lua script into Redis (optional but recommended for performance)
await load_lua_scripts()
@app.get("/")
async def root():
return {"message": "Hello, world!"}
How it works
Middleware runs on every request: It identifies the client (here, by IP) and builds a Redis key.
Atomic Lua execution:
Remove timestamps older than now - window_ms.
Insert the new timestamp.
Count how many timestamps remain in the window.
If above max_requests, return 0 (blocked); otherwise return 1 (allowed).
Set a TTL on the key to avoid unbounded growth if the client stops sending requests.
Return 429 if blocked, otherwise continue to the handler.
Notes
Adjust client_id to your own auth model (e.g., user ID from a JWT).
Tune window_ms and max_requests to your needs.
For production, ensure Redis is configured for persistence and high availability as appropriate.
The code uses redis.asyncio (redis-py >= 4.2). If you prefer aioredis, adapt accordingly.