Skip to main content

UniLimit

One rate limiter. Every Python backend.

CI PyPI Python License: MIT

UniLimit is a unified rate-limiting, concurrency-limiting, and quota-enforcement library for Python. It provides one battle-tested, framework-independent core shared seamlessly across FastAPI, Starlette, Django, Django REST Framework (DRF), and plain Python.

Backed by Redis (standalone, Cluster, Sentinel, TLS) or in-memory storage.


Highlights

  • Atomic Multi-Rule Batches: Evaluate multiple rules (e.g. 10/second burst + 10,000/day quota) in a single atomic operation. If any limit is exceeded, none are consumed. No compensating decrements.
  • Identical Python & Lua Semantics: Our Redis Lua engine is a line-by-line mirror of the Python algorithms, validated with differential property-based fuzzing.
  • Distributed WebSocket Concurrency: Cap active concurrent connections across distributed worker nodes with auto-expiring leases, heartbeats, and crash recovery.
  • Never Over-Admits: Zero race conditions under concurrency or across processes.
  • No Blocking I/O on Async Paths: True asyncio execution using redis.asyncio.
  • Zero Raw Identities in Storage: Keys contain keyed HMAC-SHA256 digests. Raw IPs, usernames, and tokens are never written to storage or leaked in logs.
  • Production Observability: Low-cardinality Prometheus metrics, OpenTelemetry integration, structured events, and throttled failure logging.
  • Fail-Open or Fail-Closed: Fine-grained resilience strategies with optional local in-memory fallback during Redis outages.

Installation

The core library has zero external runtime dependencies. Install extras for your stack:

# Core with in-memory backend
pip install unilimit

# Redis backend (standalone, Cluster, Sentinel, TLS)
pip install "unilimit[redis]"

# Framework integrations
pip install "unilimit[fastapi]"
pip install "unilimit[starlette]"
pip install "unilimit[django]"
pip install "unilimit[drf]"

# Observability exporters
pip install "unilimit[prometheus]"
pip install "unilimit[otel]"

# Or everything together
pip install "unilimit[all]"

Quickstart

1. FastAPI

from fastapi import Depends, FastAPI
from unilimit import Limiter, Rule
from unilimit.integrations.fastapi import RateLimit, setup

app = FastAPI()

# Configure limiter with global and route rules
limiter = Limiter.from_url(
    "redis://localhost:6379/0",
    global_rules=[Rule("site", rate="300/minute")],
)
setup(app, limiter)


# Rate limit specific route: 10 requests per minute
@app.get("/search", dependencies=[Depends(RateLimit("search", rate="10/minute"))])
async def search() -> dict[str, str]:
    return {"status": "ok"}

2. WebSockets & Connection Concurrency (FastAPI & Starlette)

from fastapi import FastAPI, WebSocket
from unilimit import Limiter
from unilimit.integrations.fastapi import WebSocketConnectionLimit, WebSocketRateLimit

app = FastAPI()
limiter = Limiter.from_url("redis://localhost:6379/0")

# Limit concurrent connections per IP across all workers:
concurrency = WebSocketConnectionLimit(limiter, max_connections=5, key="ip")

# Limit message throughput: 20 messages per 10 seconds:
msg_limit = WebSocketRateLimit(limiter, rate="20/10s")


@app.websocket("/chat")
async def chat(ws: WebSocket):
    async with concurrency.connection(ws):
        await ws.accept()
        while True:
            text = await ws.receive_text()
            if not await msg_limit.consume(ws):
                await ws.send_text('{"error": "rate_limited"}')
                continue
            await ws.send_text(f"echo: {text}")

3. Django & Django REST Framework

In your settings.py:

# settings.py
INSTALLED_APPS = [
    ...,
    "unilimit.integrations.django",
]

MIDDLEWARE = [
    ...,
    "unilimit.integrations.django.UniLimitMiddleware",
]

UNILIMIT = {
    "URL": "redis://localhost:6379/0",
    "OPTIONS": {
        "namespace": "myproject",
        "fail_mode": "open",
    },
}

Decorate Django views (sync or async):

from django.http import HttpRequest, HttpResponse
from unilimit.integrations.django import ratelimit


@ratelimit("search", rate="10/minute", key="ip")
def search(request: HttpRequest) -> HttpResponse:
    return HttpResponse("search results")

Or use DRF Throttles:

from rest_framework.response import Response
from rest_framework.views import APIView
from unilimit.integrations.drf import UniLimitUserRateThrottle


class ProfileView(APIView):
    throttle_classes = [UniLimitUserRateThrottle]

    def get(self, request):
        return Response({"user": request.user.username})

4. Plain Python (Framework-Free)

from unilimit import Limiter, MemoryBackend, Rule

# In-memory or Redis backend
limiter = Limiter(MemoryBackend())
rule = Rule("checkout", rate="5/minute")

# Synchronous evaluation
decision = limiter.consume(rule, identity="user:123")
if decision.allowed:
    print(f"Admitted! Remaining: {decision.remaining}")
else:
    print(f"Rate limited. Retry after {decision.retry_after:.1f} seconds")

# Asynchronous evaluation
# decision = await limiter.aconsume(rule, identity="user:123")

Documentation

Comprehensive guides and architectural specifications are available in the repository:


Testing & Quality Assurance

UniLimit enforces strict invariants tested against real Redis binaries:

uv sync
uv run pytest tests/unit                          # Fast in-memory unit tests (~2s)
uv run pytest                                     # Full suite (~1,500 tests across Redis & Cluster)
uv run ruff check . && uv run ruff format --check .
uv run mypy                                       # Strict typing, 0 errors

License

UniLimit is open-source software licensed under the MIT License. Attributions and prior-art adaptations are catalogued in THIRD_PARTY_NOTICES.md and context/prior-art.md.

Metadata

Release files for unilimit 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for unilimit 0.1.0
File Size Uploaded Provenance Actions
unilimit-0.1.0.tar.gz 232.6 kB With provenance Details for unilimit-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for unilimit 0.1.0
File Interpreter ABI Platform Actions
unilimit-0.1.0-py3-none-any.whl Python 3 none any Details for unilimit-0.1.0-py3-none-any.whl

Total release size: 341.7 kB

Release files / unilimit-0.1.0.tar.gz

Download URL unilimit-0.1.0.tar.gz
Size 232.6 kB
Tags Source
SHA-256 checksum
How to use checksums
c780e4a36fc1b91540666c0b45f0dd43044afeacc40831688ca7a816960f3c19
BLAKE2b-256 checksum
How to use checksums
ce5638601a2eaea37cef4c3a182612a40f56f3861927d0657bfd007ffb2ae45d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

Release files / unilimit-0.1.0-py3-none-any.whl

Download URL unilimit-0.1.0-py3-none-any.whl
Size 109.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d4ebdf9b83a7e3b011cf7bb9978658be780c574928ea5f7eae978a9d705f36ab
BLAKE2b-256 checksum
How to use checksums
ada5e502c47606315c77357b205b1c5ef49e3bf11367c1f94a4ef2f1eda2aa00
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

Security for unilimit 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for unilimit-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page