Skip to main content

Async rate limiter for FastAPI with Redis or in-memory backend and advanced proxy-aware security

Project description

fastapi‑easylimiter

GitHub stars GitHub forks GitHub issues GitHub license PyPI


An ASGI async rate-limiting middleware for FastAPI with Redis or in-memory caching, designed to handle auto-generated routes (e.g., FastAPI-Users) without decorators, for simplicity and ease of use.


Features

  • Path based rules (/api/*, /admin/*, exact matches)
  • Fixed & sliding window strategies (Lua)
  • RateLimit, RateLimit-Policy, Retry-After headers
  • Bans with back-off per IP with configurable window
  • BaseHTTPMiddleware for FastAPI/Starlette

Installation

pip install fastapi-easylimiter

Usage

from fastapi import FastAPI
import redis.asyncio as redis
from middleware.rate import RateLimitMiddleware

app = FastAPI()

redis_client = redis.from_url("redis://localhost:6379/0")

app.add_middleware(
    RateLimitMiddleware,
    redis=redis,
    rules={
        "/*": (200, 60, "fixed"),           
        "/api/*": (5, 1000, "sliding"),
        "/api/auth/*": (3, 1, "sliding"),
        "/api/users/me": (2, 30, "fixed"),
    },
    exempt=[],
    enable_bans=True,
    ban_offenses=8,
    ban_window="10m",
    ban_length="5m",
    ban_max_length="1d",
    )

@app.get("/api/hello")
async def hello():
    return {"message": "ok"}

Example: /api/users/me matches /api/users and /api. If any rule is exceeded → 429 returned.


Redis Key Patterns

Key Pattern Example Type Used For
rl:Fixe:{hash}:{limit}:{window} rl:Fixe:a1b2c3d4e5f6a7b8:100:60 String Fixed-window counter
rl:Slid:{hash}:{limit}:{window} rl:Slid:a1b2c3d4e5f6a7b8:60:60 ZSET Sliding window request log
offense:{identifier} offense:203.0.113.5 ZSET Offense tracking for ban escalation
ban:{identifier} ban:203.0.113.5 String+TTL Active ban flag

Middleware Parameters

Parameter Type Required Description
redis redis.asyncio.Redis Yes Redis async client
rules Dict[str, Tuple[int, int, str]] Yes Path → (limit, period, strategy)
exempt Optional[List[str]] No Paths that bypass rate limits
enable_bans bool No Enable/disable ban system
ban_offenses int No Offenses before ban triggers
ban_window str No Time window for offense accumulation
ban_length str No Initial ban length
ban_max_length str No Maximum exponential ban ceiling

Screenshot

image image

Contributing

Contributions and forks are always welcome! Adapt, improve, or extend for your own needs.


Support

Buy Me a Coffee


Parts of this code were generated/assisted by AI (Claude, Grok).

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_easylimiter-0.3.8.tar.gz (9.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_easylimiter-0.3.8-py3-none-any.whl (8.7 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_easylimiter-0.3.8.tar.gz.

File metadata

  • Download URL: fastapi_easylimiter-0.3.8.tar.gz
  • Upload date:
  • Size: 9.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.1

File hashes

Hashes for fastapi_easylimiter-0.3.8.tar.gz
Algorithm Hash digest
SHA256 04998084eb27c096fd97efb9d318791051fae94a34db8006de758c257f21150a
MD5 aa425e99d8767c04fd251e1b0121a89a
BLAKE2b-256 5d9c0891f3e18997c8fb48bf95dc217347a9397a13e9ff7dfe68d3b895b889e0

See more details on using hashes here.

File details

Details for the file fastapi_easylimiter-0.3.8-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_easylimiter-0.3.8-py3-none-any.whl
Algorithm Hash digest
SHA256 90cf06087b8f71d57154165981127f1fbef28ce0b32dff4ed83a7dbe9f15fc33
MD5 7ef1a825aa44e770d859bd7272498cff
BLAKE2b-256 3fa94888eeb56643249cc2e6f5e2f473eaf8ac61a04f83d6ab8e1bcf8e640887

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page