A custom implementation of a Sliding Window API Rate Limiter inside FastAPI using Redis. It protects the /api/data endpoint by limiting requests to 5 per 10 seconds per IP address. If a user exceeds the limit, they are blocked with a 429 Too Many Requests response. Includes a simple, unified frontend to test spamming the API.
65-fastapi-rate-limit/
main.py # FastAPI Entry point
rate_limiter.py # Redis sliding window logic implemented as a Dependency
index.html # Unified Frontend (Button spamming tool)
requirements.txt # Dependencies
README.md # This file
You must have Redis installed and running on default port 6379.
pip install -r requirements.txtuvicorn main:app --reloadOpen index.html directly in your browser and click "Send Request" as quickly as you can!
// After 5 fast requests:
{
"detail": "Rate limit exceeded. Try again in 10 seconds."
}- Sliding Window Algorithm: Unlike Fixed Window (which resets at the top of the minute), Sliding Window tracks precise timestamps. We use Redis Sorted Sets (
ZADD,ZREMRANGEBYSCORE,ZCARD) to atomically log and count request timestamps. - FastAPI Dependencies: We inject
rate_limitdirectly into our routes. If the limit is exceeded, the dependency raises anHTTPException(429)before the route logic even begins. request.client.host: Identifying unique users implicitly by IP address (or could be linked to JWTs).