This reference covers advanced configuration and runtime tuning: per-model
in-process caps, unlimited configs, the usage_counter contract, and runtime
limit overrides. Start with the README for the
shorter setup path.
See also docs/api.md for public constants and type aliases, and docs/custom-backends.md for implementing your own backend.
A callable config maps each model name to a PerModelConfig. The README shows
the basic shape; this section covers the in-process caps and idle-family
maintenance that matter for long-lived or dynamic deployments.
model_family defaults to the request model name. A typo such as
"gpt-4o-mini-prod" therefore creates a distinct family. Limiters fail closed
once mandatory in-process caps are reached: by default 10,000 model families,
100 metrics per family, 10,000 model aliases, and 100,000 in-flight
reservations. Key-segment length is also capped by default: model families and
aliases at 256 characters, metrics at 64 characters. Exceeding any of these
caps raises CardinalityLimitExceededError. Tune these constructor arguments
lower for tighter deployments and validate model names in your application if
they come from users or configuration.
Long-lived dynamic deployments should periodically call
limiter.clear_unused_model_families(unused_for_seconds) (or the sync method
with the same name) from an operator-controlled maintenance path. It evicts idle
in-process family caches and skips families with in-flight reservations. Redis
bucket keys expire separately through the Redis bucket TTL.
Adding or removing metrics or quota windows rebuilds a family's backend. If
another acquisition for that family is still pending, the operation requesting
the rebuild raises ValueError before changing backend state. Retry after the
pending acquisitions finish. This applies to sync and async limiters with
Memory, Redis, and SQLite backends, including changes requested through
record_usage() or set_max_capacity().
Existing waiters retain their original buckets and reservation authority. Refunds that encounter this condition warn and use the cached backend, so an earlier reservation can release capacity and let those waiters complete. A later operation applies the new config once no other acquisitions are pending. Limit-only changes do not rebuild the bucket set and remain allowed during waits. Changes to another model family are independent.
This rejection replaces previously accepted concurrent bucket-set changes; applications that rotate callable configs during traffic must handle it.
To disable rate limiting for a model while keeping the same API surface, return an unlimited config from your config callable:
PerModelConfig(
quotas=UsageQuotas.unlimited(),
model_family="paid-tier",
)Unlimited configs still validate direct usage values for acquire_capacity()
but do not require usage keys to match quota names because there are no quotas.
For acquire_capacity_for_request(), a configured usage_counter may still run
for telemetry; any extra_usage keys are accepted and then discarded with the
unlimited reservation. If you toggle a model between limited and unlimited,
keep extra_usage keys compatible with the limited quota metrics.
OpenAIUsageCounter handles text-only OpenAI requests. It counts input or
messages, plus prompt-bearing request context such as instructions,
tool/function definitions, and structured output schemas. The plural inputs
field is rejected because it is not an OpenAI request field. Image/audio/file
inputs are still unsupported; pass usage manually for those.
Token estimates are bounded by tiktoken's model encodings plus local
best-effort heuristics for chat/message overhead, tools, functions, schemas,
and output budgets. They have not been reconciled against live OpenAI billing
dashboards across a request corpus; periodically compare reserved tokens with
your actual billing and pass usage manually where local counting is not
representative.
Custom usage_counter callables receive the same kwargs you pass to
acquire_capacity_for_request(). They can accept **request for the whole
payload or only the named request fields they use; fixed-signature counters do
not need to accept unrelated kwargs like model. Custom counters are trusted
application code: nested request objects are passed by reference, so counters
should avoid mutating them. Return a plain dict or another well-behaved
mapping of metric names to finite numeric values.
Reserve the provider-side worst case for each call — the maximum tokens the request could consume, including an explicit output budget if you set one. Over-reserving is always safe: it costs only in-flight throughput (the reserved capacity is unavailable to other callers until you refund), never correctness.
Under-reserving is accepted, not rejected. If actual usage exceeds what you
reserved, refund_capacity() emits a RuntimeWarning and applies a negative
refund. That debt is not a separate error state; it recovers through the
bucket's normal linear refill over the quota window like any other consumed
capacity. Treat repeated warnings as a tuning signal — a mis-estimated
reservation size, not a correctness bug — and raise the reserved amount for
that call shape. Tune reservation sizes from the delta between reserved and
actual usage; the additive lifecycle callback in
docs/observability.md is the recommended way to record
that delta per request.
OpenAIUsageCounter only reserves an explicit output budget when the request
sets one of the OpenAI output-budget fields: max_tokens,
max_completion_tokens, or max_output_tokens. Without one of these fields,
output tokens are not reserved at all, so set one of them for chat and
completions requests where the provider bills output tokens.
Adjust bucket limits at runtime without rebuilding the limiter — useful for
adaptive rate limiting (e.g., reacting to x-ratelimit-* response headers):
# After the limiter has initialized this model with an acquire call:
await limiter.set_max_capacity(
model="gpt-4o",
metric="tokens",
per_seconds=60,
value=5000,
)For Redis backends the new limit is written to Redis, so all processes sharing the same Redis see the change within ~1 second. For SQLite backends it is written to the shared database; other processes see it on their next operation, with an approximately one-second upper polling interval for capacity waiters. In both cases the shared value is an explicit runtime override, not a static config edit.
Redis and SQLite preserve existing debt when a maximum decreases and extend
bucket retention to let it refill. Limit changes or rebuilds requiring more
than 2**31 - 1 seconds of retention raise ValueError; the conservative bound
uses the slower configured/override rate even for a short override. Allow debt
to refill or choose a less restrictive limit before retrying. See
retention guidance.
SQLite override lifetime and process-local fallback details are in the SQLite backend guide.
If a callable config removes a bucket and later re-adds it, the re-added
bucket starts from the static quota in the current config. Runtime overrides
from earlier set_max_capacity() calls do not survive a remove-and-readd;
call set_max_capacity() again if you want the override restored.
If you want to change the static configured quota, update the callable config
and let the limiter rebuild on the next acquire/refund. set_max_capacity() is
an explicit runtime override, not a config edit. Config rotations concurrent
with set_max_capacity() are ordered by whichever backend update completes
last; a later config rebuild resolves back to the static quota unless you
reapply the override. For SQLite, applying a changed static quota clears the
shared override for that bucket, so coordinate config rollout and override
writers across processes. See the SQLite backend guide
for the persistence and expiry details.