Skip to main content

Async ASGI rate limiter for FastAPI with Redis.

Project description

fastapi‑easylimiter

GitHub stars GitHub forks GitHub issues GitHub license PyPI

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

Features

  • Path based rules (/api/*, /auth/*, /api/users/me, etc)
  • Fixed, Sliding & Moving window algorithms (Lua)
  • RateLimit, RateLimit-Policy, Retry-After headers
  • ASGI async middleware for FastAPI/Starlette
  • Asyncio Redis support
  • Easy to configure
  • No decorators needed
  • HTML/JSON error responses
  • Site-wide or per-endpoint bans, with configurable durations

TODO

  • In-memory option
  • Forwarded-For handling
  • Better websocket support

Rule Matching

Single Rule

Use these when you want a rule to apply to one specific endpoint only.

"/api/users/me": (20, 60, "sliding")

This applies only to requests where the normalized path is exactly:

/api/users/me

Nothing else matches. Not /api/users/me/profile, not /api/users/me/123, not /api/users.

Prefix Wildcards

A rule ending with /* applies to all sub-paths under a given prefix, as one shared rate-limit bucket.

"/api/*": (100, 60, "sliding")

This matches:

/api
/api/
/api/users
/api/users/123
/api/anything/here/nested

How Rule applies

Rules are normalized and sorted so that:

  • Exact matches come before wildcard matches.
  • Longer prefixes take priority over shorter prefixes (so /api/users/* overrides /api/*)
  • A request may match multiple rules, if so, ALL matching rules run, and the strictest one determines whether the request is allowed.
  • Bans will double with each offense, up to the configured maximum ban length.

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, "moving"),           
        "/api/*": (10, 1, "sliding"),
        "/api/auth/*": (3, 1, "sliding"),
        "/api/users/me": (3, 30, "fixed"),
    },
    exempt=[],
    ban_offenses=15,
    ban_length="3m",
    ban_max_length="30m",
    ban_counter_ttl="1h",
    site_ban=True,
    )

Example: /api/auth/login matches /api/auth and /api. If any rule is exceeded → 429 returned. If banned → 403 returned.


Redis Key Patterns

Key Pattern Example Used For
rl:fixe:{hash}:{limit}:{window} rl:fixe:a1b2c3d4e5f6a7b8:100:60 Fixed-window counter
rl:slid:{hash}:{limit}:{window} rl:slid:a1b2c3d4e5f6a7b8:60:60 Sliding window request log
rl:movi:{hash}:{limit}:{window}:{window_id} rl:movi:a1b2c3d4e5f6a7b8:100:60:12345 Moving window per-subwindow counter
{rl_key}:meta rl:fixe:a1b2c3d4e5f6a7b8:100:60:meta Stores both: offenses & ban_count for doubling
ban:{hash} ban:a1b2c3d4e5f6a7b8 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
ban_offenses int No Offenses before ban triggers
ban_length str No Initial ban length
ban_max_length str No Maximum exponential ban ceiling
ban_counter_ttl int No TTL for ban metadata (default 3600s)
site_ban bool No Enable site-wide bans or per-endpoint

Tests

Used Ratelimit Tester for testing rate-limit atomicity.

Screenshot

image image image ---

Contributing

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

Buy Me a Coffee

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.4.6.tar.gz (12.4 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.4.6-py3-none-any.whl (10.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastapi_easylimiter-0.4.6.tar.gz
  • Upload date:
  • Size: 12.4 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.4.6.tar.gz
Algorithm Hash digest
SHA256 2e4e3896e68b169afd855fdc0e05ebbd757da95d3de289813f5aaebb0706726c
MD5 29a031519a7ec224d7a03b11f0fc0b6b
BLAKE2b-256 e246f20c79dd501c421254f411d2bb143174f7d1aac8c53eaca5f4b00e46e0ec

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for fastapi_easylimiter-0.4.6-py3-none-any.whl
Algorithm Hash digest
SHA256 a35c811a2fb4eabc5a8aa37086319a9f64f4947c32e716249aa491748cf75689
MD5 ae107a547bf5fc2444568f000cb3ad0c
BLAKE2b-256 1eb88e75d7cf091214a1230e0095b5be120e15a6c9ff2e1b7e282d48d952bfaa

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