Typed Python client for the Detent rate-limiting API.
Project description
detent-sdk
Typed Python client for the Detent rate-limiting API. Sync and async, one dependency (httpx).
pip install detent-sdk
Usage
from detent import Detent
rg = Detent(api_key="dt_live_...")
# Rate-limit check (fails open by default on transport error or 5xx)
r = rg.limit(namespace="api", key=user_id)
if not r.allowed:
... # return HTTP 429
# Concurrent-limit lease (auto-released)
with rg.lease(namespace="jobs", key=user_id):
run_expensive_job()
# Read-only usage stats
stats = rg.get_stats(namespace="api")
Async
from detent import AsyncDetent
async with AsyncDetent(api_key="dt_live_...") as rg:
r = await rg.limit(namespace="api", key=user_id)
async with rg.lease(namespace="jobs", key=user_id):
await run_expensive_job()
FastAPI
Enforce limits with a dependency — it runs before the handler, composes per-route, and shows up in the OpenAPI schema. Create one client in the lifespan and reuse it:
from contextlib import asynccontextmanager
from math import ceil
from fastapi import Depends, FastAPI, HTTPException, Request, Response
from detent import AsyncDetent, DetentLeaseDenied
@asynccontextmanager
async def lifespan(app: FastAPI):
async with AsyncDetent(api_key="dt_live_...") as rg:
app.state.detent = rg
yield
app = FastAPI(lifespan=lifespan)
def rate_limit(namespace: str):
async def dep(request: Request, response: Response) -> None:
rg: AsyncDetent = request.app.state.detent
# Throttle identity: an API key, a user id, or the client IP. Trust
# X-Forwarded-For only if it's set by a proxy you control.
key = request.client.host if request.client else "anon"
r = await rg.limit(namespace=namespace, key=key)
response.headers["X-RateLimit-Remaining"] = str(r.remaining)
if not r.allowed: # a verdict, not an exception — you emit the 429
retry_after = max(1, ceil(r.reset_ms / 1000))
raise HTTPException(429, "Rate limit exceeded",
headers={"Retry-After": str(retry_after)})
return dep
@app.get("/search", dependencies=[Depends(rate_limit("api"))])
async def search(q: str):
return {"q": q}
For a concurrency cap, hold a lease for the handler's lifetime with a yield
dependency — the slot is auto-released even if the handler raises, and a full
namespace raises DetentLeaseDenied:
async def with_slot(request: Request):
rg: AsyncDetent = request.app.state.detent
key = request.client.host if request.client else "anon"
try:
async with rg.lease(namespace="jobs", key=key):
yield
except DetentLeaseDenied:
raise HTTPException(429, "Too many concurrent requests")
@app.post("/report", dependencies=[Depends(with_slot)])
async def generate_report():
...
The account-level policy errors (DetentQuotaExceeded 429, DetentPaymentRequired
402) propagate out of limit()/lease(); register an @app.exception_handler for
each to turn them into a response.
Configuration
| Option | Default | Notes |
|---|---|---|
api_key |
— (required) | dt_live_… / dt_test_… |
base_url |
https://api.detent.dev |
Override for self-host / tests |
timeout |
1.0 |
Seconds; client-side transport timeout |
fail_mode |
"open" |
"open" allows, "closed" denies on a degraded backend |
on_error |
None |
Called on a degraded (transport/5xx) limit() call |
limit() never raises on a degraded backend (transport error or 5xx) — it
returns a result with degraded=True. A 4xx (bad key, plan gate, unknown
rule) raises DetentAPIError.
acquire() / lease() do not fail open — unlike limit(), they raise
DetentTransportError when Detent is unreachable, regardless of fail_mode. A
failed-open acquire would return no lease_id, so the work would run holding a
slot it can never release (a lease leak). Raising lets you decide whether to
proceed or shed load. This is distinct from the server's own Redis fail-open,
where the API still returns 200 with allowed=True and a None lease_id.
When an account exceeds its monthly hard ceiling the API returns 429, and
limit()/acquire() raise DetentQuotaExceeded (a DetentAPIError
subclass carrying status/body). It is never failed open — the cap is a
deliberate block. Catch it to alert or prompt an upgrade:
from detent import DetentQuotaExceeded
try:
result = client.limit(namespace="api", key=user_id)
if not result.allowed:
... # routine per-key rate deny → return HTTP 429
except DetentQuotaExceeded:
... # account over its monthly ceiling → page ops / upgrade nudge
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file detent_sdk-0.3.1.tar.gz.
File metadata
- Download URL: detent_sdk-0.3.1.tar.gz
- Upload date:
- Size: 19.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b82f08e031a390f90c70bb6c2e6bffd803b62c6960c8075308ab9d91d9434475
|
|
| MD5 |
8aa025381b69346b1fb5d2fbf3b0435c
|
|
| BLAKE2b-256 |
6ad1e78fbb81c8658724701224e94155b0dbc6579e7a0256fe7508e30e0bcf54
|
Provenance
The following attestation bundles were made for detent_sdk-0.3.1.tar.gz:
Publisher:
release.yml on cguillerminet/detent-sdk-python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
detent_sdk-0.3.1.tar.gz -
Subject digest:
b82f08e031a390f90c70bb6c2e6bffd803b62c6960c8075308ab9d91d9434475 - Sigstore transparency entry: 2095868407
- Sigstore integration time:
-
Permalink:
cguillerminet/detent-sdk-python@8e3332084b00b875af1dac7b7438bedcc96a4ae4 -
Branch / Tag:
refs/tags/v0.3.1 - Owner: https://github.com/cguillerminet
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@8e3332084b00b875af1dac7b7438bedcc96a4ae4 -
Trigger Event:
push
-
Statement type:
File details
Details for the file detent_sdk-0.3.1-py3-none-any.whl.
File metadata
- Download URL: detent_sdk-0.3.1-py3-none-any.whl
- Upload date:
- Size: 10.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
13173dc135023910490e4a2b72f7cdcb9e25438634fb9ba41b5b9560f4682bc2
|
|
| MD5 |
4be3dc9ab8e251e45c1c68dfa143e8b9
|
|
| BLAKE2b-256 |
acfb14b285a334e439b4a546543d511b2794eefa038b939691dac888f59f024f
|
Provenance
The following attestation bundles were made for detent_sdk-0.3.1-py3-none-any.whl:
Publisher:
release.yml on cguillerminet/detent-sdk-python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
detent_sdk-0.3.1-py3-none-any.whl -
Subject digest:
13173dc135023910490e4a2b72f7cdcb9e25438634fb9ba41b5b9560f4682bc2 - Sigstore transparency entry: 2095868829
- Sigstore integration time:
-
Permalink:
cguillerminet/detent-sdk-python@8e3332084b00b875af1dac7b7438bedcc96a4ae4 -
Branch / Tag:
refs/tags/v0.3.1 - Owner: https://github.com/cguillerminet
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@8e3332084b00b875af1dac7b7438bedcc96a4ae4 -
Trigger Event:
push
-
Statement type: