Observability¶
Limiter and Cache emit structured events to user-supplied observers, keeping paceapi decoupled from specific logging, metrics, or tracing backends.
Custom limiter observers¶
Implement on_decision and on_store_error:
class LogDenials:
"""Observer logging rejected requests and direct store failures."""
def on_decision(self, event: DecisionEvent) -> None:
# Exclude zero-cost peeks (`cost == 0`) and post-execution forced charges (`forced=True`).
if event.cost and not event.forced and not event.decision.allowed:
logger.warning("Turned away on %s, which allows %s", event.scope, event.decision.rate)
def on_store_error(self, event: StoreErrorEvent) -> None:
# Log only direct store failures (`asked=True`), not circuit-breaker bypasses.
if event.asked:
logger.error(
"The rate limit store failed (%s). What became of the request: %s",
event.error,
event.outcome,
)
Attach the observer when creating the limiter:
Observer contract:
- Fast and non-blocking: Runs synchronously on the request path. Offload slow I/O.
- Never raise: Exceptions are caught, rate-limited logged on
paceapi(at most once per minute), and do not affect requests. - Synchronous methods only:
Limiterrejectsasync defobserver methods at construction time.
Event model¶
DecisionEvent¶
DecisionEvent exposes scope, cost, decision (Decision), key, and forced.
cost and forced distinguish three operation kinds:
cost |
forced |
Kind | Meaning |
|---|---|---|---|
> 0 |
False |
count |
Standard admission check (decision.allowed indicates pass/deny) |
0 |
any | look |
Zero-cost peek (used on entry by Meter and count="failures") |
> 0 |
True |
charge |
Unconditional post-execution charge (Meter.charge, failure recording) |
To count rejected requests, count count events (cost > 0 and not forced) where not decision.allowed. Notes:
- Denied
Meter.hitcalls (e.g., WebSocket messages) are included. - Zero-cost limits that deny a caller in debt emit
look, notcount. - Disabled limiters and requests skipped via
on_missing_key="skip"emit no events.
StoreErrorEvent¶
StoreErrorEvent fires whenever a store fails to evaluate a limit, carrying error, outcome ("allow", "deny", "raise", or "fallback"), and asked:
asked=True: an actual store call failed (log or alert on these to avoid log floods).asked=False: the circuit breaker was open and bypassed the store;errorcarries the last store error (see Failure modes).- Events are per store operation, not per HTTP request: a failing primary + failing fallback emits two events, and meters/failure limits call the store on both entry and exit. When
outcome="fallback", a separateDecisionEventfollows from the fallback store.
OpenTelemetry¶
OTelObserver exports rate limit decisions and store errors as OpenTelemetry metrics and span attributes:
# Set up OpenTelemetry's SDK and an exporter as you would for anything else
# you measure. Until then the observer counts nothing.
limiter = Limiter(observers=[OTelObserver()])
Requires opentelemetry-api>=1.20.0 (bundled with recent FastAPI, or install pip install "paceapi[otel]"). Configure your OpenTelemetry SDK and exporter normally; until configured, the API is a near-zero-cost no-op. A single OTelObserver instance can be shared across limiters.
| Instrument | Attributes |
|---|---|
paceapi.rate_limit.decisions |
paceapi.rate_limit.scope, paceapi.rate_limit.rate (e.g. 100/60s), paceapi.rate_limit.result (allowed | denied), paceapi.rate_limit.kind (count | look | charge) |
paceapi.rate_limit.store.errors |
paceapi.rate_limit.store.outcome (allow | deny | raise | fallback), paceapi.rate_limit.store.asked, error.type |
paceapi.rate_limit.store.duration (histogram, seconds) |
error.type on failed calls only |
Denied requests also attach paceapi.rate_limit.result, paceapi.rate_limit.scope, and paceapi.rate_limit.rate to the active span when tracing is enabled.
Cardinality and instrumentation notes:
- Caller
keyis never a metric attribute (prevents unbounded cardinality; logevent.keyin a custom observer if needed). - Keep
scopelow-cardinality: Default route scopes use route templates (GET /items/{item_id}), not concrete paths; avoid putting IDs in customscope=strings. - Dynamic rates: Pass
OTelObserver(rate=False)if per-customer rates would create high cardinality. For multi-rate limits,ratereports the tightest rate. - Store latency:
paceapi.rate_limit.store.durationrecords each store call end to end (connection checkout, send, and reply), excluding time queued for a pool slot. It is sourced fromstore_secondson both event types, which isNonefor in-memory stores. Buckets span 0.5 ms to 5 s; onopentelemetry-api<1.30the instrument cannot advise its own buckets, so configure them with an SDK view. Instrument your Redis client directly for a per-command breakdown.
With per-customer rates, leave the rate attribute off:
# Each customer has a rate of their own. As an attribute, the rate would give
# the metric a series for every customer, so it is left off.
observer = OTelObserver(meter_provider=provider, rate=False)
limiter = Limiter(observers=[observer])
Observing caches¶
Cache(observers=[...]) accepts CacheObserver instances implementing synchronous on_cache and on_cache_error (distinct method names so one observer class can monitor both a limiter and a cache).
Events (CacheEvent, CacheErrorEvent) report namespace, entity, resource, and CacheOutcome. A CacheErrorEvent also reports the operation that failed and its source: the store, a serializer, or a cached function that failed in a background refresh. Compute hit rate per namespace using hit / (hit + miss + stale); avoid indexing metrics by high-cardinality entity IDs.
Note: OTelObserver currently instruments Limiter only, not Cache.