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")

Drop-in Compatibility for Instant Migration

Migrating an existing codebase? UniLimit provides drop-in compatibility shims that mirror the public APIs of legacy libraries:

# Instead of: from slowapi import Limiter, _rate_limit_exceeded_handler
from unilimit.compat.slowapi import Limiter, _rate_limit_exceeded_handler

# Instead of: from django_ratelimit.decorators import ratelimit
from unilimit.compat.django_ratelimit import ratelimit

Existing decorators (@limiter.limit("5/minute"), @ratelimit(key="ip", rate="10/m", block=True)) and exception handlers continue to work untouched, backed by UniLimit's atomic Redis Lua engine and multi-node protection.


AI Agent Ready (llms.txt)

UniLimit is designed natively for AI coding assistants (Cursor, Windsurf, Claude Code, GitHub Copilot).

  • llms.txt: Concise context and API patterns optimized for LLM system prompts.
  • llms-full.txt: Complete architectural reference and code recipes.
  • AI Agent Prompts: Ready-to-use .cursorrules and instructions in docs/ai_agents.md.

Documentation

Comprehensive guides, comparisons, and architectural specifications are available:


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.1

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.1
File Size Uploaded Provenance Actions
unilimit-0.1.1.tar.gz 241.5 kB With provenance Details for unilimit-0.1.1.tar.gz

Built distribution (wheel)

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

Total release size: 354.6 kB

Release files / unilimit-0.1.1.tar.gz

Download URL unilimit-0.1.1.tar.gz
Size 241.5 kB
Tags Source
SHA-256 checksum
How to use checksums
1b7b2af301b4988e3fdf61e50b02a7527599974c2db691b5b535fae5c06fe724
BLAKE2b-256 checksum
How to use checksums
988012ecefa51989f4d2b8503d4bcebee711cca675df3ffba9e75a2a14e86e8e
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.1-py3-none-any.whl

Download URL unilimit-0.1.1-py3-none-any.whl
Size 113.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e2e6b040531275195a71000c7cabf154e88ae83c57351334a3f8af11a8273965
BLAKE2b-256 checksum
How to use checksums
1edcf638f9916e679e9c70ceac0b1b2ac378f1fed36d30db501e2a9eb62c95e3
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.1

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.1.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.1 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