Async rate limiter for FastAPI with Redis or native in-memory backend
Project description
fastapi‑easylimiter
An ASGI async rate-limiting middleware for FastAPI with Redis or in-memory caching. Designed to handle auto-generated routes (such as those provided by FastAPI-Users) without requiring decorators, purely for simplicity.
Features
- Async rate limiting
- Optional temporary IP bans
- Configurable threshold (default 10 violations)
- Sliding 30-min offense window
- 5-min ban on repeat abuse
- Cache
- Redis
- In-Memory (single worker dev)
- Path Based Rules
- Multi-rule prefix matching
- Capable of global rate-limits and per-route
- Standard rate-limit headers
X-RateLimit-LimitX-RateLimit-RemainingX-RateLimit-Reset- Retry-After on
429responses - Tracking for remaining time sent in headers
- Proxy Aware
- Uses
'X-Forwarded-For'only when the sender is trusted - Rejects spoofed XFF headers
- Uses
'CF-Connecting-IP'and chekcks connection IP against CF CIDR list - Falls back to ASGI
scope["client"]if no trusted headers exist
- Uses
- Zero Dependencies Beyond Redis Client
- Starlette-style ASGI middleware
- HTMLResponse for banned browser clients or JSONResponse for API clients
Installation
pip install fastapi-easylimiter
Usage
from fastapi import FastAPI
from fastapi_easylimiter import AsyncRedisBackend, InMemoryBackend, RateLimiterMiddleware
import redis.asyncio as redis_async
app = FastAPI()
REDIS_URL = "redis://localhost:6379/0"
# Redis backend (recommended for multi-instance deployments)
redis_client = redis_async.from_url(REDIS_URL, decode_responses=True)
backend = AsyncRedisBackend(redis_client)
# Or for single-instance/local development:
# backend = InMemoryBackend()
rules = {
"/": {"limit": 600, "period": 60}, # GLOBAL: 600 req/min per IP
"/api/": {"limit": 10, "period": 1},
"/api/users": {"limit": 1, "period": 2},
}
app.add_middleware(
RateLimiterMiddleware,
rules=rules,
backend=backend,
trusted_proxies=[""], # ← NEW: your proxy IPs here: OPTIONAL
cloudflare=False, # ← NEW: enables CF-Connecting-IP: OPTIONAL
enable_bans=True, # ← NEW: turn on/off banning: OPTIONAL
ban_threshold=15, # ← violations before ban
ban_duration=300, # ← ban length in seconds
offenses_ttl=900, # ← offense counting window
ban_page="<p>Your IP has been temporarily banned due to excessive requests.</p>", # ← NEW: custom ban page: OPTIONAL
rate_page="<p>Too many requests. Please try again later.</p>", # ← NEW: custom rate limit page: OPTIONAL
)
A request to /api/users/me will match:
/api/users/api
If ANY rule is exceeded → request becomes 429.
Uses Atomic LUA script:
local c = redis.call('INCR', KEYS[1])
if c == 1 then redis.call('EXPIRE', KEYS[1], ARGV[2]) end
Existing key patterns in Redis
rl:{client_ip}:{prefix}- Example:
rl:203.0.113.5:/api
- Example:
ban:{client_ip}- Example:
ban:203.0.113.5
- Example:
offenses:{client_ip}- Example:
offenses:203.0.113.5
- Example:
| Parameter | Type | Description |
|---|---|---|
app |
ASGIApp | FastAPI/ASGI app |
rules |
dict | { prefix: {"limit": int, "period": int} } |
backend |
Redis or InMemory backend | Rate-limit storage |
trusted_proxies |
list[str] | Proxies allowed to trust XFF headers |
cloudflare |
bool | Enable Cloudflare IP extraction |
enable_bans |
bool | Enable temporary IP bans |
ban_threshold |
int | Violations before ban |
ban_duration |
int | Ban length in seconds |
offenses_ttl |
int | Offense counting window in seconds |
ban_page |
str | Custom HTML ban page |
rate_page |
str | Custom HTML rate-limit page |
Contributing
Contributions and forks are always welcome! Feel free to adapt and improve for your own needs.
Support
Parts of this code were generated/assisted by AI (Grok).
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_easylimiter-0.3.2.tar.gz.
File metadata
- Download URL: fastapi_easylimiter-0.3.2.tar.gz
- Upload date:
- Size: 8.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cdd8138f87a1a61b8a7727b6d3bddfa87d4fdb7e732f852be148f76f4c5197f6
|
|
| MD5 |
74912bcceb762d7f300b29c8d570c60e
|
|
| BLAKE2b-256 |
bffed326b3f3448bef343d7281a64f96bd86868726d50fe893a009996fdd7fbb
|
File details
Details for the file fastapi_easylimiter-0.3.2-py3-none-any.whl.
File metadata
- Download URL: fastapi_easylimiter-0.3.2-py3-none-any.whl
- Upload date:
- Size: 9.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bbba90226bb7719e763941c662fc95d2d55613e93d4d299bcb69336c84d837dc
|
|
| MD5 |
4ff9bda1759667908c4d1410325924cb
|
|
| BLAKE2b-256 |
745a25b9a8d8e8fc4c6aa27cb7c0bf8d8f704990dec4e5436ed4fe29be7077a3
|