Backstop
Reference

Configuration Reference

Complete reference for BackstopConfig, Priority, and all configuration options.

All configuration is done through BackstopConfig, passed to Backstop.wrap(). It is a frozen dataclass with validation in __post_init__.

from backstop import Backstop, BackstopConfig

client = Backstop.wrap(
    OpenAI(),
    budget=50_000,
    config=BackstopConfig(
        initial_concurrency=4,
        retry_max_attempts=3,
        shadow=False,
    ),
)

Priority

from backstop import Priority

Priority.CRITICAL     # user-facing, admitted ahead of the other two
Priority.DEFAULT      # standard traffic
Priority.BACKGROUND   # batch jobs, admitted last

Set priority per request via the X-Backstop-Priority header (see Priority Admission). Configurable via BackstopConfig.virtual_key_header and BackstopConfig.fallback_chain_for_priority.

BackstopConfig

Budget & estimation

FieldTypeDefaultDescription
default_max_output_tokensint1024Default max_tokens injected into requests that don't specify one. Must be ≥ 0.
chars_per_tokenfloat4.0Fallback byte-to-token ratio when no tokenizer is available. Must be > 0.

Retry

FieldTypeDefaultDescription
retry_max_attemptsint3Maximum retry attempts including the original call. Set to 1 to disable retries. Must be ≥ 1.
retry_base_delayfloat0.05Base backoff in seconds; actual wait ≈ retry_base_delay * 2^(attempt-1).
retry_max_delayfloat2.0Maximum backoff per retry, in seconds.
retry_statusesfrozenset[int]{429, 500, 502, 503, 504, 529}HTTP status codes that trigger a retry.

Circuit breaker

The circuit breaker tracks failure rate within a sliding time window.

FieldTypeDefaultDescription
circuit_window_secondsfloat60.0Sliding window over which failures are counted. Must be > 0.
circuit_failure_thresholdfloat0.20Failure-rate fraction (0–1) that trips the circuit open. Must be in (0, 1].
circuit_cooldown_secondsfloat30.0Seconds the circuit stays open before entering half-open.
circuit_min_requestsint5Minimum requests observed before the circuit can trip. Must be ≥ 1.

Concurrency & AIMD

FieldTypeDefaultDescription
initial_concurrencyint8Starting concurrency level. Must be between min_concurrency and max_concurrency.
min_concurrencyint1Floor for AIMD-adjusted concurrency. Must be ≥ 1.
max_concurrencyint64Hard ceiling on concurrent in-flight requests. Must be ≥ min_concurrency.
aimd_increaseint1Concurrency slots added per adjustment interval.
aimd_decrease_factorfloat0.5Fraction to multiply concurrency by on a decrease (e.g. 0.5 = halve). Must be in (0, 1).
aimd_adjustment_intervalfloat5.0Seconds between AIMD adjustments under sustained load.

Admission control

FieldTypeDefaultDescription
starvation_after_secondsfloat1.0Seconds after which the oldest ticket in any queue is released even if a higher priority is also waiting. 0 disables starvation protection. The gate queues and prioritises; it does not shed — it never cancels or discards a lower-priority waiter.
queue_timeoutfloat | NoneNoneHard timeout for queued requests. None = no timeout.
request_timeoutfloat | NoneNonePer-request latency budget. Raises LatencyBudgetExceededError if exceeded.

Caching

FieldTypeDefaultDescription
cache_enabledboolFalseEnable exact-match response caching.
cache_max_entriesint256Maximum cache entries (LRU eviction). Must be ≥ 1.
cache_ttlfloat60.0Time-to-live for cached entries, in seconds. Must be > 0.
cache_semanticboolFalseEnable semantic (near-duplicate) matching via embeddings. Requires cache_embedder.
cache_similarity_thresholdfloat0.95Cosine similarity threshold for semantic cache hits. Must be in (0, 1].
cache_embedderCallable | NoneNoneFunction (str) -> list[float] for semantic caching. Required if cache_semantic=True.

Token counting

FieldTypeDefaultDescription
token_counterCallable | NoneNoneCustom (text: str, model: str) -> int function for token estimation.

Shared (distributed) budget

FieldTypeDefaultDescription
shared_budgetboolFalseIf True, budget is stored in Redis for cross-process sharing.
redis_urlstr | NoneNoneRedis connection string. Used when shared_budget=True.
redis_keystr | NoneNoneOptional override for the Redis budget key.

Fallback chains

FieldTypeDefaultDescription
fallback_modelstr | NoneNoneSingle fallback model name.
fallback_base_urlstr | NoneNoneBase URL for the fallback model.
fallback_chainlist[dict] | NoneNoneOrdered list of {"model": str, "base_url"?} dicts for multi-model fallback.
fallback_chain_for_prioritydict | NoneNoneMaps Priority.value → list[dict] for priority-aware fallback routing.

Observability

FieldTypeDefaultDescription
otel_enabledboolFalseExport metrics to OpenTelemetry.
otel_meter_namestr"backstop"Meter name for OTEL export. Must be non-empty.

Session ceiling

FieldTypeDefaultDescription
max_wrap_sessionsint0Soft cap on concurrent wrap() sessions in one process. 0 = unlimited. Emits UserWarning if exceeded.

Audit log

FieldTypeDefaultDescription
audit_enabledboolFalseEnable tamper-evident JSONL audit log. Requires audit_hmac_key.
audit_sinkstr | callable | NoneNoneFile path or callable for audit records.
audit_hmac_keystr | NoneNoneHMAC key for chain anchoring. Required if audit_enabled.

Advanced

FieldTypeDefaultDescription
quota_awareboolTrueUse provider x-ratelimit-* headers to clamp concurrency proactively.
per_tenant_circuitboolFalseMaintain a separate circuit breaker per tenant ID.
virtual_keysdict | NoneNoneMaps API key → tenant ID for gateway deployments.
virtual_key_headerstr"X-Backstop-Key"Header name for virtual key extraction. Must be non-empty.
auto_token_countboolFalseUse tiktoken for accurate pre-dispatch token counts.
rate_limiterAny | NoneNonePluggable rate limiter with allow(tokens) -> bool interface.
compressCallable | NoneNonePre-send compression function (body, model) -> body.
secret_providerAny | NoneNoneSecret resolution strategy. Defaults to env-first chain.
agent_guardAny | NoneNoneAgent guardrails instance (runaway loop / stall detection).
log_jsonboolFalseEmit structured JSON log lines. Requires log_sink.
log_sinkAny | NoneNoneFile path or callable for structured logs.
forecast_horizon_secondsfloat0.0Proactive concurrency tightening when burn rate implies budget exhaustion within this horizon. 0 = disabled.
webhook_endpointslist | NoneNoneURLs to notify on budget threshold crossings.
webhook_secretstr | NoneNoneHMAC-SHA256 key for webhook signatures.
alert_tierslist[float] | NoneNoneUsage fractions (e.g. [0.5, 0.8, 0.95]) that trigger threshold_crossed alerts.
alert_dedup_ttlfloat86400.0Minimum seconds between repeated alerts for the same threshold.
alert_project_horizon_callsint5Number of future calls to project for exhaustion warnings.

Spend ledger

All off by default. With the ledger off, the entire per-request cost is one attribute load, two truth tests and one function call — no event is built and the price catalog is not even constructed. With it on, a request roughly doubles in cost (+130 to +147 µs p50 against +3–5 µs off); see the chargeback recipe.

FieldTypeDefaultDescription
ledger_enabledboolFalseMaster switch. When on, every completed provider request produces one SpendEvent.
ledger_pathstr | NoneNoneWhen set, append NDJSON to this path. Parent directories are created on the first write.
ledger_memory_eventsint10000With no path, the size of the bounded in-memory ring.
price_catalog_pathstr | NoneNoneA JSON catalog of your own rates, layered over the bundled list prices. Checked at construction, so a typo fails at wrap() rather than silently pricing everything at the bundled rate.

The request path never opens a file and never touches a socket: submit takes one short lock, appends to a bounded queue and returns, and a single daemon thread does the I/O with the lock dropped. Overflow refuses the incoming event and counts it in dropped_events rather than buffering without limit or silently evicting the oldest.

Runaway-spend detection

detection_enabled builds a detector over a bounded window of the last detection_window_size events per attribution key. It is report-only by construction: a signal cannot block a request, cancel work, kill an agent, or raise. Auto-kill is deliberately absent — a legitimate agent run can be six hours of work, and a kill switch that cannot resume destroys it.

FieldTypeDefaultDescription
detection_enabledboolFalseEnable the runaway-spend detector.
detection_shadowboolTrueShadow mode. The same signals are produced and filed in a bounded log with a per-kind counter, so a threshold can be tuned before it can interrupt anybody. Override in both directions with BACKSTOP_DETECTION_SHADOW.
detection_velocity_threshold_usd_per_minfloat1.0velocity fires when priced spend in the window, over the minutes it spans, exceeds this.
detection_baseline_multiplierfloat3.0drift fires when mean tokens per request in the recent half of the window exceeds this × the older half. Must be ≥ 1.0; below 1.0 inverts the comparison rather than alerting earlier.
detection_retry_ratio_thresholdfloat0.5retry_amplification fires when mean retries per request exceeds this.
detection_context_growth_thresholdfloat2.0context_growth fires when this request's input tokens exceed the rest of the window's median by this factor.
detection_window_sizeint50Events retained per key. Must be > 0.
detection_min_samplesint8Samples required before a signal is considered. Must be ≤ detection_window_size; a larger value produces a detector that can never speak and looks exactly like a healthy one.
detection_max_keysint1024Bounds the number of attribution keys. Eviction is LRU and counted in evictions, because a silently evicted key is a key whose baseline silently restarts.

A negative or non-finite threshold, a non-positive window, and min_samples > window_size are all refused at wrap() rather than discovered on the first request.

Shadow mode

FieldTypeDefaultDescription
shadowboolFalseIf True, record enforcement decisions as "would-have" without actually blocking.
shadow_policyAny | NoneNoneShadowPolicy instance for sampled shadow routing.

Kill-switch: set BACKSTOP_SHADOW=false in the environment to hard-disable shadow mode regardless of config.


— Edit this page on GitHub

On this page