# Python rate limiting libraries

Python rate limiting libraries cap how many requests a client can make in a time window or how fast a program sends outgoing calls. A limiter counts hits per key under a strategy such as a fixed window or a leaky bucket. These libraries let web APIs and AI agents stay within a set request budget.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [limits](#limits) | 43.7M | 657 | Feb 2026 | MIT |
| [Django REST framework](#djangorestframework) | 30.3M | Not on GitHub | Oct 2026 | BSD-3-Clause |
| [slowapi](#slowapi) | 24.9M | 2.1K | Jun 2026 | MIT |
| [aiolimiter](#aiolimiter) | 16.0M | Not on GitHub | Sep 2026 | MIT |
| [ratelimit](#ratelimit) | 15.4M | Not on GitHub | Dec 2018 | MIT |
| [PyrateLimiter](#pyratelimiter) | 11.9M | 534 | Oct 2026 | MIT |
| [Flask-Limiter](#flask-limiter-library) | 7.5M | Not on GitHub | Dec 2025 | MIT |
| [django-axes](#django-axes) | 5.0M | Not on GitHub | Oct 2026 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[limits](#limits) has the most monthly downloads in this comparison, at 43.7M, a count that includes installs through Flask-Limiter and SlowAPI.

## Capabilities

| Library | External shared quota state | Waits for quota |
| --- | --- | --- |
| [limits](#limits) | Yes | No |
| [Django REST framework](#djangorestframework) | Yes | No |
| [slowapi](#slowapi) | Yes | No |
| [aiolimiter](#aiolimiter) | No | Yes |
| [ratelimit](#ratelimit) | Undocumented | Yes |
| [PyrateLimiter](#pyratelimiter) | Yes | Yes |
| [Flask-Limiter](#flask-limiter-library) | Yes | No |
| [django-axes](#django-axes) | Yes | No |

## Libraries

### limits

[GitHub](https://github.com/alisaifee/limits) · [PyPI](https://pypi.org/project/limits) · [Docs](https://limits.readthedocs.io/en/stable/api.html)

Provides rate-limiting strategies with interchangeable storage backends.

- Downloads / mo: 43.7M
- Stars: 657
- Last release: 5.8.0
- License: MIT
- Capabilities: [From the limits docs](https://limits.readthedocs.io/en/stable/api.html)

**Strengths**

- **Shares APIs across rate strategies.** Switch strategies while retaining hit, test, and window-stat methods.
- **Provides synchronous and coroutine interfaces.** Use the async namespace for coroutine-based storage and strategies.

**Watch out for**

- **Fixed windows allow boundary bursts.** Use a moving-window strategy when boundary bursts are unacceptable.

```sh
python3.13 -m pip install limits==5.8.0
```

**alisaifee/flask-limiter** (1.2K stars)

[alisaifee/flask-limiter](https://github.com/alisaifee/flask-limiter) 

```python
def __evaluate_limits(self, endpoint: str, limits: list[RuntimeLimit]) -> None:
    failed_limits: list[tuple[RuntimeLimit, list[str]]] = []
    limit_for_header: RequestLimit | None = None
    view_limits: list[RequestLimit] = []
    meta_limits = [
        meta_limit
        for meta_limit in itertools.chain(
            *self._meta_limits,
            *[limit.meta_limits for limit in limits if limit.meta_limits],
        )
        if not meta_limit.is_exempt
    ]
    if not (
        ExemptionScope.META
        & self.limit_manager.exemption_scope(
            flask.current_app, endpoint, flask.request.blueprint
        )
    ):
        for lim in meta_limits:
            limit_key, scope = lim.key_func(), lim.scope_for(endpoint, None)
            args = [limit_key, scope]
            on_breach = lim.on_breach or self._on_meta_breach
            if not self.limiter.test(lim.limit, *args, cost=lim.deduction_amount):
                breached_meta_limit = RequestLimit(self, lim.limit, args, True, lim.shared)
                self.context.view_rate_limit = breached_meta_limit
                self.context.view_rate_limits = [breached_meta_limit]
                meta_breach_response = None

                if on_breach:
                    try:
                        cb_response = on_breach(breached_meta_limit)

                        if isinstance(cb_response, flask.wrappers.Response):
                            meta_breach_response = cb_response
                    except Exception as err:  # noqa
                        if self._swallow_errors:
                            self.logger.exception(
                                "on_meta_breach callback failed with error %s", err
                            )
                        else:
                            raise err
                raise RateLimitExceeded(lim, response=meta_breach_response)

    for lim in sorted(limits, key=lambda x: x.limit):
        if lim.is_exempt or lim.method_exempt:
            continue

        limit_scope = lim.scope_for(endpoint, flask.request.method)
        limit_key = lim.key_func()
        args = [limit_key, limit_scope]
        kwargs = {}

        if not all(args):
            self.logger.error(f"Skipping limit: {lim.limit}. Empty value found in parameters.")

            continue

        if self._key_prefix:
            args = [self._key_prefix, *args]

        if lim.deduct_when:
            self.context.conditional_deductions[lim] = args
            method = self.limiter.test
        else:
            method = self.limiter.hit
        kwargs["cost"] = lim.deduction_amount

        request_limit = RequestLimit(self, lim.limit, args, False, lim.shared)
        view_limits.append(request_limit)

        if not method(lim.limit, *args, **kwargs):
            self.logger.info(
                "ratelimit %s (%s) exceeded at endpoint: %s",
                lim.limit,
                limit_key,
                limit_scope,
            )
            failed_limits.append((lim, args))
            view_limits[-1].breached = True
            limit_for_header = view_limits[-1]

            if self._fail_on_first_breach:
                break

    if not limit_for_header and view_limits:
        # Pick a non shared limit over a shared one if possible
        # when no rate limit has been hit. This should be the best hint
        # for the client.
        explicit = [limit for limit in view_limits if not limit.shared]
        limit_for_header = explicit[0] if explicit else view_limits[0]

    self.context.view_rate_limit = limit_for_header or None
    self.context.view_rate_limits = view_limits

    on_breach_response = None

    for limit in failed_limits:
        request_limit = RequestLimit(self, limit[0].limit, limit[1], True, limit[0].shared)

        for cb in dict.fromkeys([self._on_breach, limit[0].on_breach]):
            if cb:
                try:
                    cb_response = cb(request_limit)

                    if isinstance(cb_response, flask.wrappers.Response):
                        on_breach_response = cb_response
                except Exception as err:  # noqa
                    if self._swallow_errors:
                        self.logger.exception("on_breach callback failed with error %s", err)
                    else:
                        raise err

    if failed_limits:
        meta_limits = [
            meta_limit
            for meta_limit in itertools.chain(
                *self._meta_limits,
                *[list(lim[0].meta_limits) for lim in failed_limits if lim[0].meta_limits],
            )
            if not meta_limit.is_exempt
        ]
        for lim in meta_limits:
            limit_scope = lim.scope_for(endpoint, flask.request.method)
            limit_key = lim.key_func()
            args = [limit_key, limit_scope]
            self.limiter.hit(lim.limit, *args)
        raise RateLimitExceeded(
            sorted(failed_limits, key=lambda x: x[0].limit)[0][0],
            response=on_breach_response,
        )
```

[flask_limiter/_extension.py](https://github.com/alisaifee/flask-limiter/blob/0e715b6fbb4655756f747c78d95d61deaa69dd1c/flask_limiter/_extension.py) · [More projects using limits →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20limits%20for%20rate-limit%20strategy%20integration%2C%20request%20costs%2C%20quota%20checks%2C%20per-view%20policy%20configuration%20and%20throttled%20HTTP%20clients&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from limits import parse
from limits.storage import MemoryStorage
from limits.strategies import MovingWindowRateLimiter

limiter = MovingWindowRateLimiter(MemoryStorage())
rate = parse("1/minute")
print(limiter.hit(rate, "example"))
```

From [README.rst](https://limits.readthedocs.io/en/stable/api.html)

### Django REST framework

[GitHub](https://github.com/encode/django-rest-framework) · [PyPI](https://pypi.org/project/djangorestframework) · [Docs](https://api.github.com/repos/encode/django-rest-framework/contents/rest_framework/throttling.py?ref=3.18.3)

Builds web APIs for Django.

- Downloads / mo: 30.3M
- Last release: 3.18.3
- License: BSD-3-Clause
- Capabilities: [From the Django REST framework docs](https://api.github.com/repos/encode/django-rest-framework/contents/rest_framework/throttling.py?ref=3.18.3)

```sh
python3.13 -m pip install djangorestframework==3.18.3
```

**suitenumerique/meet** (2.5K stars)

[suitenumerique/meet](https://github.com/suitenumerique/meet) 

```python
def get_cache_key(self, request, view):
    """Use the authenticated user ID as the throttle cache key."""

    if request.user and not request.user.is_authenticated:
        return None  # Defer to RequestEntryAnonRateThrottle for anonymous users.

    return super().get_cache_key(request, view)
```

[src/backend/core/api/throttling.py](https://github.com/suitenumerique/meet/blob/043875e804891df523a5359ad8363d2e58138520/src/backend/core/api/throttling.py) · [More projects using Django REST framework →](https://dashboard.exa.ai/playground/search?q=djangorestframework%20GitHub%20projects)

**Quickstart**

```python
from django.contrib.auth.models import AnonymousUser
from rest_framework.test import APIRequestFactory
from rest_framework.throttling import UserRateThrottle

class ExampleThrottle(UserRateThrottle):
    rate = "2/minute"

request = APIRequestFactory().get("/")
request.user = AnonymousUser()
print(ExampleThrottle().allow_request(request, view=None))
```

From [throttling.py](https://api.github.com/repos/encode/django-rest-framework/contents/rest_framework/throttling.py?ref=3.18.3)

### slowapi

[GitHub](https://github.com/laurentS/slowapi) · [PyPI](https://pypi.org/project/slowapi) · [Docs](https://slowapi.readthedocs.io/en/latest/)

Adds rate limiting to Starlette and FastAPI HTTP endpoints.

- Downloads / mo: 24.9M
- Stars: 2.1K
- Last release: 0.1.10
- License: MIT
- Capabilities: [From the slowapi docs](https://slowapi.readthedocs.io/en/latest/)

**Strengths**

- **Fits asynchronous HTTP endpoints.** Limit synchronous or asynchronous routes through the same wrapper.
- **Shares quotas across routes.** Apply shared limits to a selected set of routes.

**Watch out for**

- **Endpoints need a request argument.** Include request in each rate-limited endpoint’s function signature.
- **Decorator order affects enforcement.** Place the route decorator above the limit decorator.
- **WebSocket routes are unsupported.** Use another limiter for WebSocket traffic.

```sh
python3.13 -m pip install slowapi==0.1.10 starlette
```

**mlflow/mlflow** (28.9K stars)

[mlflow/mlflow](https://github.com/mlflow/mlflow) 

```python
def _get_endpoint_handler(gateway_api: GatewayAPI, name: str, limiter: Limiter, key: str):
    endpoint_type_to_factory = {
        EndpointType.LLM_V1_CHAT: _create_chat_endpoint,
        EndpointType.LLM_V1_COMPLETIONS: _create_completions_endpoint,
        EndpointType.LLM_V1_EMBEDDINGS: _create_embeddings_endpoint,
    }
    provider, endpoint_type = gateway_api._get_provider_by_name(name)

    if factory := endpoint_type_to_factory.get(endpoint_type):
        handler = factory(provider)

        if name in gateway_api.dynamic_endpoints:
            limit = gateway_api.dynamic_endpoints[name].limit
        else:
            limit = None

        if limit:
            limit_value = f"{limit.calls}/{limit.renewal_period}"
            handler.__name__ = f"{handler.__name__}_{name}_{key}"
            return limiter.limit(limit_value)(handler)
        else:
            return handler

    raise HTTPException(
        status_code=404,
        detail=f"Unexpected route type {endpoint_type!r} for route {name!r}.",
    )
```

[mlflow/gateway/app.py](https://github.com/mlflow/mlflow/blob/04ad38e48d55520422a53d1f23c963f6b68a2999/mlflow/gateway/app.py) · [More projects using slowapi →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20slowapi%20for%20rate-limit%20strategy%20integration%2C%20request%20costs%2C%20quota%20checks%2C%20per-view%20policy%20configuration%20and%20throttled%20HTTP%20clients&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import PlainTextResponse
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)
app = Starlette()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@limiter.limit("5/minute")
async def homepage(request: Request):
    return PlainTextResponse("test")

app.add_route("/home", homepage)
```

From [index.md](https://slowapi.readthedocs.io/en/latest/)

### aiolimiter

[GitHub](https://github.com/mjpieters/aiolimiter) · [PyPI](https://pypi.org/project/aiolimiter) · [Docs](https://aiolimiter.readthedocs.io/en/latest/)

Limits asyncio code with a leaky bucket.

- Downloads / mo: 16.0M
- Last release: 1.3.0
- License: MIT
- Capabilities: [From the aiolimiter docs](https://aiolimiter.readthedocs.io/en/latest/)

```sh
python3.13 -m pip install aiolimiter==1.3.0
```

**python-telegram-bot/python-telegram-bot** (29.6K stars)

[python-telegram-bot/python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot) 

```python
async def _run_request(
    self,
    chat: bool,
    group: str | int | bool,
    allow_paid_broadcast: bool,
    callback: Callable[..., Coroutine[Any, Any, bool | JSONDict | list[JSONDict]]],
    args: Any,
    kwargs: dict[str, Any],
) -> bool | JSONDict | list[JSONDict]:
    async def inner() -> bool | JSONDict | list[JSONDict]:
        # In case a retry_after was hit, we wait with processing the request
        await self._retry_after_event.wait()
        return await callback(*args, **kwargs)

    if allow_paid_broadcast:
        async with self._apb_limiter:
            return await inner()
    else:
        base_context = self._base_limiter if (chat and self._base_limiter) else null_context()
        group_context = (
            self._get_group_limiter(group)
            if group and self._group_max_rate
            else null_context()
        )

        async with group_context, base_context:
            return await inner()
```

[src/telegram/ext/_aioratelimiter.py](https://github.com/python-telegram-bot/python-telegram-bot/blob/41e3633bd1b4e51693ee57059828a59a9773618a/src/telegram/ext/_aioratelimiter.py) · [More projects using aiolimiter →](https://dashboard.exa.ai/playground/search?q=aiolimiter%20GitHub%20projects)

**Quickstart**

```python
import asyncio
from aiolimiter import AsyncLimiter

async def main():
    limiter = AsyncLimiter(100)
    async with limiter:
        print("permit acquired")

asyncio.run(main())
```

From [index.html](https://aiolimiter.readthedocs.io/en/latest/)

### ratelimit

[GitHub](https://github.com/tomasbasham/ratelimit) · [PyPI](https://pypi.org/project/ratelimit) · [Docs](https://pypi.org/pypi/ratelimit/2.2.1/json)

Limits API calls through a function decorator.

- Downloads / mo: 15.4M
- Last release: 2.2.1
- License: MIT
- Capabilities: [From the ratelimit docs](https://pypi.org/pypi/ratelimit/2.2.1/json)

```sh
python3.13 -m pip install ratelimit==2.2.1
```

**datahub-project/datahub** (13.0K stars)

[datahub-project/datahub](https://github.com/datahub-project/datahub) 

```python
def get_rate_limited_emit_mcp(self, emitter: DataHubGraph) -> Any:
    """
    Returns a rate limited emitter that can be used to emit metadata for propagation
    """

    @sleep_and_retry
    @limits(
        calls=self.rate_limit_propagated_writes,
        period=self.rate_limit_propagated_writes_period,
    )
    @wraps(emitter.emit_mcp)
    def wrapper(*args, **kwargs):
        return emitter.emit_mcp(*args, **kwargs)

    return wrapper
```

[datahub-actions/src/datahub_actions/plugin/action/propagation/propagation_utils.py](https://github.com/datahub-project/datahub/blob/7d863576bcfac99d375485ca7e5b193b4f74b0df/datahub-actions/src/datahub_actions/plugin/action/propagation/propagation_utils.py) · [More projects using ratelimit →](https://dashboard.exa.ai/playground/search?q=ratelimit%20GitHub%20projects)

**Quickstart**

```python
from ratelimit import limits

@limits(calls=1, period=1)
def example():
    return "permitted"

print(example())
```

From [README.md](https://pypi.org/pypi/ratelimit/2.2.1/json)

### PyrateLimiter

[GitHub](https://github.com/vutran1710/PyrateLimiter) · [PyPI](https://pypi.org/project/pyrate-limiter) · [Docs](https://pypi.org/pypi/pyrate-limiter/4.5.1/json)

Provides configurable bucket algorithms and storage backends for rate limiting.

- Downloads / mo: 11.9M
- Stars: 534
- Last release: 4.5.1
- License: MIT
- Capabilities: [From the PyrateLimiter docs](https://pypi.org/pypi/pyrate-limiter/4.5.1/json)

**Strengths**

- **Chooses algorithms per bucket.** Set the bucket algorithm to match the allowed request pattern.
- **Can wait for available quota.** Choose blocking behavior or reject immediately when the bucket is full.

**Watch out for**

- **Sync acquisition can block.** Use try_acquire_async to wait without blocking the event loop.

```sh
python3.13 -m pip install pyrate-limiter==4.5.1
```

**schemathesis/schemathesis** (3.8K stars)

[schemathesis/schemathesis](https://github.com/schemathesis/schemathesis) 

```python
def build_limiter(rate: str) -> Limiter:
    from pyrate_limiter import Limiter, Rate

    limit, interval = parse_units(rate)
    return Limiter(Rate(limit, interval))
```

[src/schemathesis/core/rate_limit.py](https://github.com/schemathesis/schemathesis/blob/abb39fb00448208eeeb9aaa865218091becdfc6a/src/schemathesis/core/rate_limit.py) · [More projects using PyrateLimiter →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20pyrate-limiter%20for%20rate-limit%20strategy%20integration%2C%20request%20costs%2C%20quota%20checks%2C%20per-view%20policy%20configuration%20and%20throttled%20HTTP%20clients&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from pyrate_limiter import Duration, Rate, Limiter

limiter = Limiter(Rate(5, Duration.SECOND * 2))
print(limiter.try_acquire("my-resource"))
```

From [README.md](https://pypi.org/pypi/pyrate-limiter/4.5.1/json)

### Flask-Limiter

[GitHub](https://github.com/alisaifee/flask-limiter) · [PyPI](https://pypi.org/project/flask-limiter) · [Docs](https://flask-limiter.readthedocs.io/en/stable/api.html)

Adds rate limiting to Flask applications.

- Downloads / mo: 7.5M
- Last release: 4.1.1
- License: MIT
- Capabilities: [From the Flask-Limiter docs](https://flask-limiter.readthedocs.io/en/stable/api.html)

```sh
python3.13 -m pip install flask-limiter==4.1.1 flask==3.1.3
```

**dpgaspar/Flask-AppBuilder** (5.0K stars)

[dpgaspar/Flask-AppBuilder](https://github.com/dpgaspar/Flask-AppBuilder) 

```python
def create_limiter(self, app: Flask) -> Limiter:
    limiter = Limiter(
        key_func=app.config.get("RATELIMIT_KEY_FUNC", get_remote_address)
    )
    limiter.init_app(app)
    return limiter
```

[flask_appbuilder/security/manager.py](https://github.com/dpgaspar/Flask-AppBuilder/blob/30e13dc7916167fa159452322aa00d03999970f9/flask_appbuilder/security/manager.py) · [More projects using Flask-Limiter →](https://dashboard.exa.ai/playground/search?q=flask-limiter%20GitHub%20projects)

**Quickstart**

```python
from flask import Flask
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

app = Flask(__name__)
limiter = Limiter(get_remote_address, app=app)

@app.get("/")
@limiter.limit("5/minute")
def index():
    return "permitted"
```

From [api.html](https://flask-limiter.readthedocs.io/en/stable/api.html)

### django-axes

[GitHub](https://github.com/django-commons/django-axes) · [PyPI](https://pypi.org/project/django-axes) · [Docs](https://api.github.com/repos/django-commons/django-axes/contents/axes/handlers/proxy.py?ref=9.0.0)

Tracks failed login attempts on Django sites.

- Downloads / mo: 5.0M
- Last release: 9.0.0
- License: MIT
- Capabilities: [From the django-axes docs](https://api.github.com/repos/django-commons/django-axes/contents/axes/handlers/proxy.py?ref=9.0.0)

```sh
python3.13 -m pip install django-axes==9.0.0
```

**babybuddy/babybuddy** (3.0K stars)

[babybuddy/babybuddy](https://github.com/babybuddy/babybuddy) 

```python
def post(self, request, *args, **kwargs):
    user = self.get_object()
    form = self.get_form()
    if form.is_valid():
        reset(username=user.username)
        return self.form_valid(form)
    else:
        return self.form_invalid(form)
```

[babybuddy/views.py](https://github.com/babybuddy/babybuddy/blob/1638cfb02e2681c5a0c2f24fdf8d20048fda995a/babybuddy/views.py) · [More projects using django-axes →](https://dashboard.exa.ai/playground/search?q=django-axes%20GitHub%20projects)

**Quickstart**

```python
from django.test import RequestFactory
from axes.handlers.proxy import AxesProxyHandler

request = RequestFactory().post("/login/")
print(AxesProxyHandler.is_allowed(request, {"username": "example"}))
```

From [proxy.py](https://api.github.com/repos/django-commons/django-axes/contents/axes/handlers/proxy.py?ref=9.0.0)

## FAQ

### Which Python rate limiting library should I use?

[limits](#limits) suits code that needs rate-limiting strategies over Redis, Memcached, or MongoDB storage. [SlowAPI](#slowapi) and [Flask-Limiter](#flask-limiter-library) suit FastAPI, Starlette, and Flask routes. [aiolimiter](#aiolimiter) suits asyncio code that needs a leaky bucket limiter.

### What is SlowAPI?

[SlowAPI](#slowapi) is a rate limiting library for Starlette and FastAPI, adapted from Flask-Limiter. It tracks limits in Redis, Memcached, or memory.

### How do I rate limit FastAPI endpoints?

[SlowAPI](#slowapi) applies a limit decorator to each endpoint function. The route decorator must sit above the limit decorator. Each limited endpoint also takes the request as an explicit argument.

### What is aiolimiter?

[aiolimiter](#aiolimiter) is an asyncio rate limiter built on the leaky bucket algorithm.

### What is Flask-Limiter?

[Flask-Limiter](#flask-limiter-library) adds rate limiting to Flask applications.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python rate limiting libraries limits SlowApi Flask-Limiter PyrateLimiter examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
