Skip to main content

omnilimit for Python

Rate limiting that behaves the same across stacks, and proves it. This port follows the same spec and passes the same conformance vectors as the TypeScript one, and both can share a counter in Redis or Postgres.

  • Trusted client IPs. It reads X-Forwarded-For from the right. Rotating the header does not evade the limit.
  • An explicit failure mode. You must decide, per limiter, what happens when the store is down.
  • No dependencies. Extras only install a client: omnilimit[redis], omnilimit[postgres], omnilimit[sqlalchemy], omnilimit[asyncpg], omnilimit[fastapi].
pip install omnilimit

Usage

from redis import Redis

from omnilimit import Limiter
from omnilimit.stores.redis import RedisStore

client = Redis.from_url(url, socket_timeout=0.25, socket_connect_timeout=0.25)
limiter = Limiter(
    store=RedisStore(client),
    scope="login",
    limit=5,
    window_ms=60_000,
    burst=2,
    on_store_error="closed",  # required: "open" lets requests through, "closed" answers 503
)

decision = limiter.check(user_id)
if not decision.allowed:
    ...  # answer decision.status with decision.headers, which include Retry-After

5 per minute with burst 5 can admit 9 requests in one minute: this is a rate, not a counter that resets. Lower burst if you need fewer.

A request can weigh several units, such as a batch: limiter.check(user_id, cost=len(items)). The cost is an integer from 1 to the burst, and a denied request counts nothing.

To read the policy from configuration, parse_policy("10/minute") returns limit and window_ms ready to spread: Limiter(**parse_policy(setting), store=..., scope=..., on_store_error=...). The grammar is <limit>/<count><unit> with second, minute, hour or day, and it is strict: 5/15minute is valid, 10/min is not.

Peek, reset and refund

decision = limiter.peek(user_id)  # what check() would answer now, without counting
limiter.reset(user_id)  # forget the bucket, e.g. after a successful login

reserved = limiter.reserve(user_id, cost=len(items))  # check(), and keep a way to give it back
if reserved.decision.allowed:
    try:
        do_work()
    except Exception:
        limiter.refund(reserved.reservation)  # only what has not drained yet
        raise

peek builds its decision like check and follows on_store_error the same way. When allowed, remaining includes the request you asked about. It is advisory: a concurrent request can take the last unit, so the check that follows is still the authority. reset returns True once the bucket is gone (or was never there) and False if the store failed or timed out, which on_event reports; it never raises for a store failure. Both raise TypeError if the store cannot do them, which is a configuration error. Every event carries op ("check", "peek", "reset" or "refund"), and a successful reset emits type "reset".

reserve decides like check, and its reservation is None when nothing was counted (a denial, or on_store_error="open" after a store failure). refund gives back what is left of the request after the meter drained since it was counted, so a bucket never ends up more generous than if the request had never happened. It returns True once applied, and False for None, for a reservation already refunded (without calling the store), or when the store failed or timed out; it never raises for a store failure and never retries, since a timed-out refund may have been applied. A reservation belongs to the limiter that made it: another one raises TypeError. A successful refund emits type "refund", and reserve reports as "check". With an asyncpg, SQLAlchemy or psycopg store, reapply MIGRATION_SQL when upgrading to 0.4 to add omnilimit_refund_v1.

Recipes

from omnilimit import Lockout, check_all

# Several limits on one request: nothing is counted unless all of them allow.
result = check_all([(per_ip, ip), (per_account, email)])
if not result.allowed:
    ...  # answer result.decision.status with result.decision.headers

# Count only failed attempts, and refuse even a correct one once they are spent.
attempt = Lockout(failed_logins).attempt(f"{email}:{ip}", lambda: password_matches(email, password))
if not attempt.allowed:
    ...  # the verification did not run

Lockout(limits=[LockoutLimit(...), ...], mode="reserve") counts each failure under several limits and never runs the verification more often than they allow. With an AsyncLimiter, use check_all_async and AsyncLockout. Both are built on peek, so they are not atomic. peek_all and reserve_all split a combined check in two around work that may not happen, and reserve_all counts first and refunds, so it never lets more through: see recipes.

Sync or async

Code Limiter Stores
Flask, Django, def dependencies Limiter MemoryStore, RedisStore, PostgresStore, SqlAlchemyStore
async def AsyncLimiter MemoryStore, AsyncRedisStore, AsyncPostgresStore, AsyncSqlAlchemyStore, AsyncpgStore

Limiter runs each store call in its own daemon thread, because Python cannot abandon a blocking call. store_timeout_ms bounds the request, and max_store_threads bounds the calls in flight. Set socket timeouts on your client as well, so a hung call ends.

redis-py caps its pool and raises past that cap, which omnilimit reports as a store failure. If you expect bursts of concurrent checks, use BlockingConnectionPool.

FastAPI

from fastapi import Depends, FastAPI

from omnilimit import MemoryStore, Limiter
from omnilimit.fastapi import ip_key, rate_limit

limiter = Limiter(
    store=MemoryStore(), scope="api", limit=100, window_ms=60_000, on_store_error="open"
)
app = FastAPI(dependencies=[
    Depends(rate_limit(limiter, key=ip_key(preset="cloud-run"), on_missing_key="shared")),
])

Denials raise HTTPException, so your own handlers format them. Headers on allowed requests are not added when a route returns its own Response object, as a file download usually does.

To build the denial response yourself, pass on_denied and register its handler. It receives a Denial with status, headers, error ("rate_limited", "rate_limiter_unavailable" or "client_not_identified") and decision (None for a missing key):

from fastapi.responses import JSONResponse

from omnilimit.fastapi import RateLimitDenied, denied_handler


def on_denied(request, denial):
    return JSONResponse({"error": denial.error}, status_code=denial.status, headers=denial.headers)


app.add_exception_handler(RateLimitDenied, denied_handler)  # without it, a denial raises TypeError
limit = Depends(rate_limit(limiter, key=..., on_missing_key="reject", on_denied=on_denied))

With an AsyncLimiter, on_denied may be async.

To key by user or API key, pass your authentication dependency as identity. What it returns arrives as context.identity, FastAPI resolves it once per request, and a request it rejects is not counted:

limit = rate_limit(limiter, identity=current_user, key=lambda ctx: ctx.identity.id, on_missing_key="reject")

limiter may also be a function of the context, to choose a limiter per request.

To let some requests through without counting them, pass skip. It runs before key:

Depends(rate_limit(limiter, key=..., on_missing_key="shared", skip=lambda ctx: ctx.request.url.path == "/health"))

Any ASGI application

omnilimit.asgi.RateLimitMiddleware limits a whole application, with skip for the paths to leave alone. It is plain ASGI, so it needs no extra and works under Starlette, FastAPI, Litestar, Quart or Django:

from omnilimit.asgi import RateLimitMiddleware, ip_key

app.add_middleware(
    RateLimitMiddleware,
    limiter=limiter,
    key=ip_key(preset="cloud-run"),
    on_missing_key="shared",
    skip=lambda ctx: ctx.path == "/health",
)

It runs before routing, so it cannot key by an identity a dependency resolves later. See adapters.

Client IP only

omnilimit.ip uses only the standard library and also works next to slowapi:

from omnilimit.ip import resolve_client_ip

ip = resolve_client_ip(request.headers, request.client.host, preset="cloud-run-lb")

client_key takes the same arguments and also groups IPv6 by /64, which is the id a hand-written key wants: client_key(request.headers, preset="cloudflare") or "shared".

It returns None rather than guessing. Check that the preset matches your deployment: see client IP.

Postgres

omnilimit.stores.postgres.MIGRATION_SQL creates the table and functions: apply it with your migration tool. Stores take a psycopg 3 pool or a connection with autocommit=True. Each hit is a write, so it is not meant for high traffic, and cleanup() is yours to schedule. MIGRATION_SQL is idempotent: apply it again after upgrading, since peek needs omnilimit_peek_v1.

If the application already has a SQLAlchemy engine or an asyncpg pool, use that instead of opening a second pool: SqlAlchemyStore(engine) and AsyncSqlAlchemyStore(async_engine) from omnilimit.stores.sqlalchemy (extra omnilimit[sqlalchemy], any Postgres driver), or AsyncpgStore(pool) from omnilimit.stores.asyncpg (extra omnilimit[asyncpg]). The SQLAlchemy stores take the engine, not a session, and commit each hit on their own.

Metadata

Release files for omnilimit 0.4.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 omnilimit 0.4.0
File Size Uploaded Provenance Actions
omnilimit-0.4.0.tar.gz 189.4 kB With provenance Details for omnilimit-0.4.0.tar.gz

Built distribution (wheel)

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

Total release size: 232.7 kB

Release files / omnilimit-0.4.0.tar.gz

Download URL omnilimit-0.4.0.tar.gz
Size 189.4 kB
Tags Source
SHA-256 checksum
How to use checksums
c70d691aa1979a93de293210f7df02e808d4f13d903d4a52e50c923d13014423
BLAKE2b-256 checksum
How to use checksums
8e54dd128237a0c69e585a285753083773a40a05593b83bd159a6471423f9994
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 Nov 20, 2026.

Transparency log

Release files / omnilimit-0.4.0-py3-none-any.whl

Download URL omnilimit-0.4.0-py3-none-any.whl
Size 43.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
805d7dd28d95b11f884b99b4be8378129bd9bb2ee24857e986dd1393c71da8ef
BLAKE2b-256 checksum
How to use checksums
0f24758919fb86ecdc3fcf2fee044a7d44c8330b5fee5e5b260295cd248dd800
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 Nov 20, 2026.

Transparency log

Security for omnilimit 0.4.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 omnilimit-0.4.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 Nov 20, 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.

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