# TokenGate > Multi-tenant quota management as a service. Define metered resources, attach > quota and rate-limit policies to subjects, and atomically check-and-consume > usage. Includes reservations (reserve an estimate, commit the actual), an > append-only usage ledger, rollup reporting, and threshold alerts. Base URL: https://tokengate.rodmena.co.uk Version: 0.1.0 OpenAPI: https://tokengate.rodmena.co.uk/openapi.json Interactive docs: https://tokengate.rodmena.co.uk/docs Python SDK: pip install tokengate (https://pypi.org/project/tokengate/) MCP endpoint: https://tokengate.rodmena.co.uk/mcp/ (this guide, served as tools) Operated by: RODMENA LIMITED (https://rodmena.co.uk/) — company no. 16472788 ## Authentication Send a tenant-scoped API key as a bearer token on every request: Authorization: Bearer tg__ Keys are hashed at rest and displayed exactly once, when minted. This service cannot issue you a key — ask the operator. Unauthenticated: the pages `/`, `/llms.txt`, `/docs` and `/openapi.json`; the probes `/healthz`, `/ping` and `/readyz`; the read-only docs server at `/mcp/`; and static assets (`/robots.txt`, `/sitemap.xml`, the favicon and web-icon set, `/site.webmanifest`, `/brand/`, `/fonts/`, `/assets/`). Every other path needs a key. All of the pages, probes and assets answer GET and HEAD; any other method returns 405 with an `Allow` header. ### Scopes Ask for the narrowest scope that covers what you do. A scope implies the ones listed under it, so you do not request them separately. consume data plane: /v1/consume, /v1/check, /v1/refund, reserve/commit/release, and a subject's own usage catalog:read list resources, policies, plans catalog:write create/patch/delete them (implies catalog:read) assignments:read read a subject's plan assignment assignments:write set/remove it (implies assignments:read, catalog:read) overrides:read read per-subject limit overrides overrides:write set them (implies overrides:read) alerts:read alert rules and events alerts:write manage alert rules (implies alerts:read) webhooks:read webhook endpoints and deliveries webhooks:write manage endpoints (implies webhooks:read) keys:read list API keys keys:write mint/rotate/revoke keys (implies keys:read) reporting:read /v1/ledger, /v1/usage/summary, /v1/audit tenant:read /v1/tenant ops:jobs reserved; /v1/ops/jobs/{job} is operator-only (root key) subtenants:read list and read your subtenants subtenants:write create, rename, suspend and mint keys into them (implies subtenants:read; NOT implied by admin:*) admin:read every :read scope above except subtenants:read admin:write EVERYTHING above except subtenants:* — a tenant superuser **`admin:write` is not "write access", it is tenant root.** It can mint and revoke API keys and rewrite or disable every policy in the tenant, including other services'. Do not accept it for a service integration: if you only assign plans, ask for `assignments:write`. A key can never mint a scope it does not itself hold, and minting a key for a different `actor` requires `admin:write` — so a leaked scoped credential cannot escalate or outlive its own revocation. Every minted key records `created_by_actor` alongside the `actor` it acts as. Keys may also carry constraints, which bound *what a key may act on* rather than what it may do: "constraints": {"plan_ids": ["..."], "subject_prefix": "mail:cert:", "catalog_name_prefix": "mail"} `plan_ids` restricts which plans an `assignments:write` key may assign; assigning any other plan returns 403 `plan_not_permitted` and changes nothing. `subject_prefix` restricts which subjects the key may touch at all — on the admin plane *and* the data plane. A subject outside it returns 403 `subject_not_permitted` and changes nothing. Use it when a staging or certification instance shares a tenant with production: scopes alone give both the same power over the same customers. `limit_amount` in an override applies to QUOTA policies only. A `rate_limit` policy is governed by `bucket_capacity` and `refill_rate_per_sec` on the policy itself, so sending `limit_amount` for one now returns 422 `validation_error` rather than storing a number that could never take effect. Attaching, detaching or disabling a rate_limit policy per subject still works — omit `limit_amount`. `catalog_name_prefix` bounds catalog authority by object NAME (literal startswith): a `catalog:write` key so constrained can create, patch, rename and delete only resources/policies/plans whose names match the prefix, and can only *reference* in-prefix objects when linking (a policy's resource, a plan's policies, an override's policy). Anything else returns 403 `catalog_not_permitted` and changes nothing. It also widens `assignments:write` by name: plans whose name matches the prefix are assignable in UNION with `plan_ids`, so a key that may create a plan may assign it without an operator round trip. Use it when services share a tenant and each should govern only its own catalogue. `require_assignment: true` makes a `consume` key fail closed. Consume, check and reserve then answer 422 `subject_unassigned` (problem body names the `subject`) whenever the subject has no enforceable policy: no assignment, a plan whose policies are all disabled, or a plan that was deleted. The refusal counts nothing, writes no ledger row and stores no idempotency record, so the same `idempotency_key` succeeds once the subject is assigned. Refund, commit and release are not gated. Treat 422 `subject_unassigned` as "quota not configured": fail closed, alert, do not retry. A key carrying it cannot mint a key without it, and removing it from a key via PATCH requires `admin:write`. Turn it on for a live key with `PATCH /v1/api-keys/{id} {"constraints": {..., "require_assignment": true}}`; PATCH replaces the whole constraints object, so resend the others. All are optional; an omitted constraint is unconstrained on that axis, and the `constraints` object in a key response shows only what is actually set. A key can never mint or patch a key less constrained than itself, and widening any existing key's constraints via PATCH requires `admin:write`. A key can never issue or grant a credential **less** constrained than itself — attempting it returns 403 `constraint_escalation` — and no key may edit its own constraints (403 `self_modification`). Without those rules a bounded key could mint an unbounded one and act through it. PATCH /v1/api-keys/{id} {"constraints": {"subject_prefix": "mail:"}} tightens a live key **without rotating its secret**, so a credential already deployed in a running service can be bounded without an outage. It takes effect immediately and is recorded in the audit trail as `api_key.patch`. ## Core concepts - resource: a metered thing, e.g. `llm.tokens`, `api.calls`, `storage.bytes`. - policy: a quota (limit per window) or rate_limit (token bucket) on a resource. Quota windows are `fixed` (minute/hour/day/week/month, calendar anchored in the policy timezone), `rolling`, or `lifetime`. - plan: a bundle of policies. assignment: binds a plan to a subject. **A subject with no assignment is uncapped, not denied**: consume answers 200 `allowed: true` and reserve answers 201, both with `"results": []`. There is no default plan. Assign a dynamic subject (one you mint on the fly) BEFORE its first consume or reserve; the assignment PUT is safe to repeat. If the limit guards abuse (login or MFA failures), fail closed when `results` is empty or lacks your policy. To have TokenGate refuse instead, give the consume key the `require_assignment` constraint (422 `subject_unassigned`). - subject: whoever you meter — a user id, org id, API key, or tenant of yours. - enforcement mode: `strict` (PostgreSQL transaction, exact and durable — use for money-like budgets) or `fast` (Redis, with exactly-once ledger write-behind — use for high-throughput counters). - metered but never blocking: a quota with `"on_exceed": "allow_overage"` counts every unit and is never refused. Past its limit, consume still answers 200 `allowed: true`, the result carries `"overage": true`, and usage reads `allowed: true` with `remaining: 0`. Use it to meter a subject before anyone has agreed a commercial limit, instead of leaving the subject unassigned and invisible. The default is `"on_exceed": "block"`. A rate_limit policy always blocks and refuses `on_exceed`. ## Consume (the main call) POST /v1/consume { "subject": "user_42", "items": [{"resource": "llm.tokens", "amount": 1200}], "idempotency_key": "req-8f2c1a", "metadata": {"trace_id": "..."} } 200 response: { "allowed": true, "event_id": "01KYB...", "degraded": false, "results": [{"resource": "llm.tokens", "policy_id": "...", "policy_name": "monthly-budget", "kind": "quota", "mode": "strict", "allowed": true, "limit": 100000, "used": 1200, "remaining": 98800, "overage": false, "window": {"id": "...", "start": "...", "end": "...", "reset_at": "..."}}] } Rules: - The batch is atomic: every applicable policy is evaluated, and either all items commit or none do. - `items` may hold up to 50 entries; one entry per resource (merge duplicates yourself). Amounts are positive integers. - `degraded: true` means a backend was unavailable and the policy allowed the request through uncounted. Treat it as a signal, not an error. - One `results` entry per policy that applied, NOT per item. Quota policies report integer `used`/`remaining`; **rate_limit policies report `"used": null`** (a refilling token bucket has no cumulative usage) with `remaining` = tokens left, `limit` = `bucket_capacity`, and `window: null`. Branch on `kind` before doing arithmetic on `used`. **Do not sum `used` across a subject's policies** — the first rate_limit policy in the plan makes the total `None`/`NaN`, and that is a reporting bug, not a limit breach. Related: - POST /v1/check — same body, no side effects. **A denial is HTTP 200 with `"allowed": false`, never 429.** Branch on the field, not the status: {"allowed": false, "degraded": false, "results": [{... "allowed": false ...}], "blocking": {"code": "quota_exceeded", "blocking_policy": {"policy_name": "monthly-budget", "limit": 100, "used": 100, "requested": 10, "remaining": 0}, "reset_at": "...", "retry_after": 601626}} `blocking` is `null` when allowed. Only POST /v1/consume (and reserve/commit) answer 429. Use check for pre-flight display, never as a gate on its own — check-then-consume races; consume is the atomic decision. - POST /v1/refund — same body plus optional `reason`; returns usage to the quota (append-only: it writes a compensating ledger entry, never a mutation). Responds `{"event_id", "degraded", "results"}` — no `allowed` field. **Refund returns QUOTA units only. It never returns a token to a rate_limit bucket**: a bucket refills by time alone. A refund of a rate_limit-only item answers 200 with `"refunded": false` and changes nothing. `refunded` is true only when at least one quota counter was decremented. To give a unit back when an attempt succeeds (e.g. an MFA failure ceiling), use a quota policy, for example a 1-day rolling window, and use reserve -> release-on-success / commit-on-failure, or consume -> refund-on-success. - GET /v1/subjects/{subject}/usage — **live** usage per policy, straight from the counters. This (or /v1/ledger) is the correct source for a balance check; /v1/usage/summary is not. Same `used: null` rule for rate_limit policies. - GET /v1/subjects/{subject}/entitlements — which policies apply, with windows. Response: `{"subject": "...", "policies": [...]}`, sorted by resource name then policy_id. Each entry carries `policy_id`, `name`, `resource`, `kind` (`quota` | `rate_limit`), `limit_amount`, `window_kind`, `window_unit`, `window_size`, `tz`, `bucket_capacity`, `refill_rate_per_sec`, `enforcement_mode`, `on_exceed`, `on_backend_error`, `source` (`plan` | `override`) and `window`. `window` is `{id, start, end, reset_at}` for a quota policy (all four null on a rolling window) and null for a rate_limit, whose `tz` is also null. `resource` is the resource NAME, the string you send in consume items. A resource name is unique in its tenant and cannot be changed. A policy `name` can be changed by PATCH, so key on `policy_id` when you need a fixed identity. A subject with no assignment and no subject-level override answers 200 with `"policies": []`, also under a key with `require_assignment` (that constraint is enforced on consume). An override on an unassigned subject still lists its policy, with `source: "override"`. URL-encode the subject if it contains reserved characters; a `/` inside a subject is sent as `%2F` and works on every `/v1/subjects/{subject}/...` route. ## Reserve and commit (unknown cost up front) Use this when you learn the true cost only after the work runs (LLM calls, uploads, jobs): POST /v1/reserve {"subject": "user_42", "items": [{"resource": "llm.tokens", "amount": 4000}], "ttl_seconds": 120, "idempotency_key": "resv-1"} -> 201 {"reservation_id": "01KYB...", "status": "held", "expires_at": "...", "results": [...]} POST /v1/reservations/{reservation_id}/commit {"actuals": [{"resource": "llm.tokens", "amount": 3271}], "idempotency_key": "commit-1"} -> 200 {"status": "committed", "event_id": "...", "adjustments": [{"resource": "llm.tokens", "held": 4000, "actual": 3271, "delta": -729, "overage": 0}]} POST /v1/reservations/{reservation_id}/release {"idempotency_key": "rel-1"} -> 200 {"status": "released", "returned": [...]} POST /v1/reservations/{reservation_id}/renew {"ttl_seconds": 600, "idempotency_key": "renew-1"} -> 200 {"reservation_id": "...", "status": "held", "expires_at": "...", "window_bound": false} Rules: - A held reservation counts against available quota until committed, released, or expired (`ttl_seconds`, 1..3600; expiry frees it within 60s). - Work longer than an hour: reserve with a short TTL and renew it on a heartbeat (for example ttl 600, renewing every 180 s). Renew sets `expires_at` to now + `ttl_seconds` (1..3600) and leaves the holds exactly as they were. It never shortens a hold, and the same `idempotency_key` replays the first answer without extending again. If the holder crashes, renewals stop and the hold expires within one TTL, so the slot comes back. - A renewal never carries a hold past the end of the quota window it was taken in. For a rolling window that is one window span after the reserve. `window_bound: true` means `expires_at` was capped there: settle before then, and reserve again in the next window. - Renew on a hold that is not `held`, or at or after `expires_at`, returns 409 `reservation_not_held` and does not extend it. Renew before it lapses; there is no reviving an expired hold. - Only quota units are held. A reserve spends rate_limit tokens immediately, and release or expiry does not return them. - **`actuals` is the full settlement, and a held resource you leave out of it settles to ZERO, not to the amount held.** `commit {}` charges nothing and writes no ledger row: it frees the hold and marks the reservation committed, so it behaves like a release that looks like a success. To charge what you held, restate it: `{"actuals": [{"resource": "llm.tokens", "amount": 4000}]}`. To record "used nothing", send `"amount": 0` explicitly. Assert on `adjustments[].actual` (or on usage across the commit), never only on `status == "committed"`. - Commit always succeeds — actuals are reality. Committing more than you held is allowed and reported as `overage`. - Commit/release on a reservation that is not `held` returns 409 `reservation_not_held`. So does commit/release at or after `expires_at`, even before the expiry sweep has run. - A commit, release or renew refused as expired frees the hold before the 409 is returned: the 409 carries `current_status: "expired"`, and the held amount is already back in the quota. Settle a late commit with a plain consume of the actual usage, and it is charged once. Without such a call, an expired hold is freed by the sweep within 60s. - A commit is counted in the window its hold was taken in, not the window it is committed in. ## Idempotency Send `idempotency_key` on every consume, reserve, commit, and refund. Retrying with the same key returns the original outcome instead of consuming again, and the response carries the header `X-TokenGate-Replayed: true`. Reusing a key with a *different* payload returns 409 `idempotency_key_reuse`. Keys are remembered for at least 24 hours. Generate one per logical operation (a UUID is fine) and reuse it across retries of that operation. **Key scope depends on the enforcement mode, so derive keys as if the subject were NOT part of the scope.** - Strict policies scope the key to (your TokenGate tenant, idempotency_key), so the subject is not part of it. Reusing a key for a different subject gets 409 `idempotency_key_reuse` and nothing is counted. - Fast-only calls scope the key to (tenant, subject, idempotency_key), so the same key on two subjects is two separate operations, each counted once. In neither mode does TokenGate replay one subject's response to another. If you map your own customers onto subjects inside one TokenGate tenant (the recommended topology), they share a key space on strict policies. Then the key derivation is the only thing carrying your customer boundary across to us, which makes it a security control: wrong: idempotency_key = f"{request_id}" two of your customers may both send request_id "op-1" right: idempotency_key = f"{your_customer_id}:{request_id}" Treat a 409 `idempotency_key_reuse` between two of your customers as a bug in your key derivation, not as a retry signal. ## Per-tenant concurrency Each API node runs at most 24 concurrent consume, refund, reserve, commit, release and renew calls per tenant; `check` and reads are not counted. This includes rate_limit-only consumes. A slot is held only for the duration of the call, so at 15 ms per call 24 slots carry roughly 1,600 calls/s. Calls beyond 24 wait up to 10 s for a slot, then get 429 `tenant_concurrency_limit`. Retry with backoff, and keep your client concurrency per tenant under 24. ## Errors (RFC 7807 problem+json, stable `code` field) {"type": "https://tokengate.dev/problems/quota-exceeded", "title": "Quota exceeded", "status": 429, "code": "quota_exceeded", "blocking_policy": {"policy_name": "monthly-budget", "limit": 100000, "used": 99000, "requested": 1200, "remaining": 1000}, "reset_at": "2026-08-01T00:00:00+00:00", "retry_after": 601626} | status | code | what to do | |--------|-------------------------|-------------------------------------------| | 401 | unauthenticated, | Key missing, malformed, revoked, or the | | | invalid_api_key | tenant is suspended. Do not retry. | | 403 | insufficient_scope | Key lacks the scope. Do not retry. | | 429 | ledger_budget_exceeded | Tenant's daily ledger-row budget is spent. | | | | Batch your consumes; retry after reset_at. | | 409 | idempotency_key_reuse | Same key, different payload. New key. | | 409 | idempotency_in_flight | Duplicate in flight. Retry after ~1s. | | 429 | tenant_concurrency_limit| Over 24 concurrent writes. Back off. | | 409 | reservation_not_held | Already committed/released/expired. | | 409 | plan_in_use | Plan still has assigned subjects; list | | | | them, reassign or unassign, then delete. | | 409 | resource_in_use | Policies still meter the resource; | | | | delete them first. | | 422 | unknown_resource | Resource not defined for this tenant. | | 422 | subject_unassigned | Key requires assignment; subject has no | | | | enforceable policy. Assign it. No retry. | | 422 | validation_error | Fix the payload; see `errors`. | | 429 | quota_exceeded | Wait for `reset_at` / `Retry-After`. | | 429 | rate_limited | Retry after `Retry-After` seconds. | | 503 | backend_unavailable | Backend down, policy says deny. Retry | | | | with backoff. Never treat as allowed. | | 503 | authz_unavailable | RBAC service down (admin plane only). | | 503 | lock_timeout | The subject's counter was locked by other | | | | work for over 6 s. Retry after 1 s. | Always honor the `Retry-After` header rather than a fixed sleep. A 429 or 503 means the usage was NOT counted. ## Reading a subject's usage — the envelope is frozen `GET /v1/subjects/{subject}/usage` returns **exactly** these two keys, and this shape is a supported contract, not an implementation detail: {"subject": "user_42", "policies": [{"policy_id": "...", "policy_name": "monthly-budget", "kind": "quota", "limit": 100000, "used": 240, "remaining": 99760, "window": {...}}]} The list key is `policies` — not `usage`, not `results`. There is no need to probe for alternatives; a change here would be a breaking change and is pinned by a contract test. ## SDK exception contract (supported, stable) `QuotaExceeded` and `RateLimited` both expose these as **guaranteed attributes** — read them directly, not via `getattr`: | Attribute | Type | Meaning | |---|---|---| | `retry_after` | `int \| None` | Seconds to wait; mirrors the `Retry-After` header | | `reset_at` | `str \| None` | ISO-8601 instant the window resets | | `blocking_policy` | `dict` | The policy that tripped; `["policy_name"]` is always present | `blocking_policy` returns `{}` rather than `None` when absent, so `exc.blocking_policy.get("policy_name")` is always safe. `ServiceUnavailable` (503) also carries `retry_after`. These names will not be renamed without a major version bump. try: tg.consume(subject, {"api.calls": 1}) except RateLimited as exc: raise HTTPException(429, headers={"Retry-After": str(exc.retry_after or 1)}, detail=f"limit {exc.blocking_policy['policy_name']} reached") ## Admin plane (least-privilege scope shown per call) catalog:write POST /v1/resources {"name": "llm.tokens", "unit": "tokens"} POST /v1/policies {"name": "monthly-budget", "resource_id": "...", "kind": "quota", "limit_amount": 100000, "window_kind": "fixed", "window_unit": "month", "window_size": 1, "enforcement_mode": "strict"} POST /v1/policies {"name": "burst", "resource_id": "...", "kind": "rate_limit", "bucket_capacity": 20, "refill_rate_per_sec": 5} POST /v1/plans {"name": "pro", "policy_ids": ["...", "..."]} DELETE /v1/plans/{id} 204 deleted; 404 unknown plan; 409 plan_in_use while ANY subject is assigned to it (the body carries assigned_subjects). Nothing changes on 409: reassign or unassign the subjects first. A plan delete never uncaps a subject. DELETE /v1/resources/{id} 204 deleted; 409 resource_in_use while any policy meters it: delete those policies first. The ledger keeps the resource name and id. DELETE /v1/policies/{id} 204 deleted, never 409. It cascades: the policy leaves every plan, and its subject overrides, strict counters and alert rules are deleted with it, so the cap stops applying at once. Alert events already fired are kept. assignments:write PUT /v1/subjects/{s}/assignment {"plan_id": "..."} DELETE /v1/subjects/{s}/assignment assignments:read GET /v1/plans/{id}/assignments who is on a plan, before you delete it: {"plan_id", "total", "entries": [{"subject", "plan_id", "created_at"}], "next_cursor"}; ordered by subject, limit 1-500 (default 100), pass next_cursor back as cursor. A key with a subject_prefix sees, and counts, only its own subjects. overrides:write PUT /v1/subjects/{s}/overrides {"overrides": [{"policy_id": "...", "limit_amount": 250000}]} keys:write POST /v1/api-keys {"scopes": ["consume"], "actor": "svc@you"} POST /v1/api-keys {"scopes": ["assignments:write"], "actor": "mail@you", "constraints": {"plan_ids": ["...", "..."]}} reporting:read GET /v1/ledger append-only usage, keyset paginated GET /v1/usage/summary rollup aggregates — LAGS, see below GET /v1/audit admin audit trail, keyset paginated ### Audit trail Every admin mutation is recorded and readable. `GET /v1/audit` returns the same paged envelope as the ledger, newest first, and supports `actor=`, `action=`, `from=`, `to=`, `limit=` and `cursor=`: {"entries": [{"id": "...", "seq": 412, "actor": "mail@you", "action": "assignment.put", "entity_type": "assignment", "entity_id": "cust_42", "before": {"plan_id": "..."}, "after": {"plan_id": "..."}, "at": "2026-07-25T17:40:00Z"}], "next_cursor": null} The log is append-only: there is no endpoint that edits or deletes an entry. Page with `seq`, not `at` — timestamps can collide, `seq` cannot. ### Subtenants (a platform running its own tenants) A platform that resells metering to its own customers can give each customer a separate tenant: own catalog, plans, keys, ledger and audit, isolated by the database exactly as any two tenants are. The operator turns it on per tenant by setting an allowance (`max_subtenants`, default 0). Until then every call below answers 403 `subtenants_not_enabled`. subtenants:write POST /v1/subtenants {"slug": "--acme", "name": "Acme"} -> 201 {"tenant": {...}, "admin_key": {"key": "tg_...", ...}} PATCH /v1/subtenants/{id} {"name": "...", "tz": "...", "status": "active"} DELETE /v1/subtenants/{id} suspend (data kept; frees an allowance slot) POST /v1/subtenants/{id}/api-keys {"scopes": ["consume"], "name": "acme-runtime"} POST /v1/subtenants/{id}/bootstrap-authz retry the RBAC set-up subtenants:read GET /v1/subtenants your subtenants only GET /v1/subtenants/{id} Rules: - The slug must start with your own slug followed by `--`. `--` is reserved for this, so no top-level tenant can contain it. - The new tenant's `admin_key` (admin:write, admin:read, consume) is shown once. Lost it? Mint a replacement with `/v1/subtenants/{id}/api-keys`. - You manage the subtenant's catalog with ITS keys, not yours: every other route acts on the tenant of the key you send. - Keys minted into a subtenant carry your actor and cannot hold `subtenants:*` or `ops:jobs`. Subtenants cannot have subtenants (403 `subtenant_depth`). - Over the allowance: 403 `subtenant_limit_reached`. Reactivating a suspended subtenant counts against it again. - Suspending your tenant suspends all your subtenants' keys (403 `tenant_suspended`, within 30 s). - If the operator suspended a subtenant (`suspended_by_operator: true`), only the operator can reactivate it (403 `suspended_by_operator`). - An id that is not your subtenant answers 404, same as one that does not exist. - Only an unconstrained key may use these routes or mint `subtenants:*`. Ask the operator to enable the allowance, then mint a dedicated key with your `admin:write` key: `POST /v1/api-keys {"scopes": ["subtenants:write"], ...}`. - Each subtenant has its own daily ledger-row budget and is metered on its own; there is no roll-up across subtenants. - Every create, change and key mint is audited in both tenants (`subtenant.*` in yours). ### Reading usage back `GET /v1/ledger` returns a **paged envelope, not a bare array**: {"entries": [{"id": "...", "event_id": "...", "subject": "user_42", "resource": "llm.tokens", "resource_id": "...", "amount": 1200, "entry_type": "consume", "idempotency_key": "...", "reservation_id": null, "strict_deferred": false, "occurred_at": "..."}], "next_cursor": "eyJvY2N1cnJlZF9hdCI6..."} Filters: `subject`, `resource`, `from`, `to`, `limit` (1..500, default 100). Page by passing `next_cursor` back as `cursor`; it is `null` on the last page. Refunds appear as entries with a negative `amount`. Deleting a resource does not change history: its ledger entries and summary rows keep the name the resource had when it was deleted, and every entry also carries `resource_id`. Attribute by `resource_id` if you rename resources. `GET /v1/usage/summary` is served from **rollup tables built by a periodic job (hourly cadence)**, so it is eventually consistent and **returns `[]` for activity that has just happened**. Never use it for a balance check, a quota gate, or a "did my consume land?" assertion — use `GET /v1/subjects/{subject}/usage` (live counters) or `GET /v1/ledger` (live append-only truth). Summary is for reporting and charts over settled periods; its rows are `{resource, subject, granularity, bucket_start, amount_sum, event_count}` with `granularity` of `hour` or `day`. Notes: **`enforcement_mode: "strict"` combined with `window_kind: "rolling"` is rejected at policy creation with 422 `validation_error`** — strict counting needs discrete windows; use `fixed`/`lifetime` for strict, or `fast` for rolling. Window shape, window kind, and enforcement mode are immutable after creation — create a new policy instead. Alert rules (`/v1/alert-rules`) fire once per (rule, subject, policy, window, threshold) over HMAC-signed webhooks and/or email. Verify every webhook delivery before trusting it. The request carries `X-TokenGate-Signature: t=,v1=`, where `v1 = HMAC-SHA256(endpoint secret, "." + raw request body)`. The endpoint secret is returned once, when the endpoint is created. Recompute the HMAC over the raw bytes you received (not over re-serialised JSON), compare in constant time, and reject a `t` more than 5 minutes from your clock to stop replays. In a shell: `printf '%s.%s' "$t" "$body" | openssl dgst -sha256 -hmac "$secret"`. `POST /v1/webhook-endpoints/{id}/test` sends a signed `{"event": "ping"}` so you can check your verifier against a real delivery. `subject_filter` matches one subject EXACTLY by default. To watch a whole namespace, set `"subject_match": "prefix"` together with a filter such as `"subject_filter": "trace:"`, which then matches every subject starting with it. A key with a `subject_prefix` must set a filter inside its own namespace, so for such a key `"subject_match": "prefix"` is the way to watch all of its subjects. `subject_match` can be changed on an existing rule with PATCH. `"prefix"` without a `subject_filter` is refused with 422. Alert events are history. Deleting a rule, or the policy it watches, keeps every event the rule already fired; their `rule_id` then names a rule that no longer exists. Email delivery is asynchronous and depends on the host's mail configuration, so do not treat a recorded event as a sent email. `GET /v1/alert-events` carries `email_delivery` on every event: `none` (no email channel, or suppressed by cooldown), `pending`, `sending`, `sent` (the mail service accepted it), `failed` (retrying with backoff), `dead` (gave up after 8 attempts), `expired` (never sent within 24 h), or `mail_disabled` (this deployment has no mail credential, so it will expire unsent). `email_attempts` counts send attempts and `email_error` holds the last error, or null. `GET /readyz` reports `"mail": "configured" | "unconfigured"`. For a decision that must not be missed, poll `GET /v1/subjects/{subject}/usage` instead. ## Ledger rows, aggregation and the per-tenant row budget - A consume is a durable ledger write, not a free pre-check. Do not call /v1/consume once per event to enforce a token bucket: batch (`amount=N`), lease with /v1/reserve + commit, or run a local bucket and consume the tokens you actually used. /v1/check writes nothing. - A consume that touches ONLY `rate_limit` policies writes NO usage_ledger row. Its amounts are aggregated per minute and land in `/v1/usage/summary` (hour/day buckets) within ~3 minutes; `/v1/ledger` will not list those events. Quota consumes, refunds and reservation commits are ledgered as before. Token buckets are never reconciled from the ledger, so enforcement is unchanged. - Every tenant has a daily usage_ledger row budget (default 500,000 rows/UTC day; the operator can raise it per tenant). Past it, requests that would write rows are refused `429 ledger_budget_exceeded` with `budget`, `used`, `reset_at` and `Retry-After` (seconds to the next UTC midnight), and nothing is charged. An ops alert fires at 80%. If you hit this, you are metering per event; fix the call shape rather than asking for a bigger budget. ## Operational guarantees - Every failure direction over-counts rather than under-counts: TokenGate may deny early, but it will not silently oversubscribe a quota. The guarantee is durable, not instantaneous: if Redis fails while a commit adds usage above its hold, the fast counter stays below ledger truth for that amount until the reconciler corrects it (seconds to minutes). The ledger is always right. - The usage ledger is append-only with exactly-once insertion; corrections are new entries, never row mutations. - Under a Redis outage, strict policies stay fully enforced via PostgreSQL. Under a PostgreSQL outage, fast policies stay enforced via Redis and the ledger catches up. Each policy's `on_backend_error` decides deny vs. allow. ## Client SDK The official typed Python SDK (sync + async, automatic idempotency keys, a reserve/commit metering context manager) is on PyPI: pip install tokengate from tokengate import TokenGate tg = TokenGate("https://tokengate.rodmena.co.uk", api_key="tg_...") tg.consume("user_42", {"llm.tokens": 1200}) with tg.meter("user_42", {"llm.tokens": 4000}) as m: # reserve -> commit m.record("llm.tokens", 3271) Typed helpers (`consume`, `check`, `refund`, `reserve`, `commit`, `release`, `usage`, `entitlements`, `meter`) return parsed pydantic models. Denials raise typed exceptions — `QuotaExceeded`, `RateLimited`, `UnknownResource`, `IdempotencyKeyReuse`, `ReservationNotHeld`, `ServiceUnavailable`, `AuthenticationError`, `PermissionDenied`, `InvalidRequest`, `TransportError`, `ServerError`, all deriving from `TokenGateError`. Note `check()` does NOT raise on a denial: it mirrors the endpoint and returns `allowed=False` with a populated `blocking`. A success status always means permission, and the client enforces it: if a 2xx `consume` body ever carried `allowed: false` (impossible under the current server contract), the SDK raises `ProtocolViolation` rather than returning — a denial must never be readable as a grant. `tg.request(method, path, json=..., params=...)` is the escape hatch for admin endpoints without a typed helper. **It returns already-parsed JSON — a dict or list (and `None` for 204) — not an HTTP response object**, so there is no `.status_code` / `.json()` to call on it; failures raise the typed exceptions above: resources = tg.request("POST", "/v1/resources", json={"name": "llm.tokens"}) resources["id"] # dict, not a Response page = tg.request("GET", "/v1/ledger", params={"limit": 50}) page["entries"], page["next_cursor"] `AsyncTokenGate` mirrors the whole surface with `await` and `async with tg.meter(...)`. Plain HTTP works everywhere else — there is nothing SDK-specific about the protocol. ## MCP (Model Context Protocol) This guide is also served over MCP for agents that prefer tools to scraping: endpoint https://tokengate.rodmena.co.uk/mcp/ (streamable HTTP, stateless, no auth) tools list_sections, get_section(name), get_llms_txt Register it with an MCP client, e.g.: claude mcp add --transport http tokengate https://tokengate.rodmena.co.uk/mcp/ It is documentation only — the same content as this file, no tenant data and no way to call the metered API. API calls always go through the endpoints above with your own bearer key.