The engineering problem
When autonomous agents or multi-tenant SaaS features call frontier models (gpt-4o, claude-3-5-sonnet) directly, a single recursive retry loop or burst of uncached queries can exhaust monthly token budgets in hours. Provider billing dashboards update with a multi-minute lag—far too late to stop a runaway loop.
Existing gateways either require heavy external infrastructure or binary hard-stops that break user-facing workflows. I needed a deterministic, sub-4ms async proxy that tracks exact IEEE-safe Decimal token spend across sliding windows, caches semantically equivalent prompts, and gracefully degrades to lower-cost models (gemini-2.5-flash / gpt-4o-mini) when a tenant crosses their 80% soft threshold.
System architecture & interactive topology
A 2,442-line asynchronous FastAPI & OpenTelemetry proxy gateway built around four core subsystems:
- Multi-Scope Sliding Window Ledger (
budget_engine.py): Enforces concurrent budgets acrossGLOBAL,TENANT,PROJECT, andAGENTscopes using exactDecimal('0.000001')arithmetic. - Dynamic Soft-Cap Model Downgrading: At 80% budget utilization, transparently rewrites the upstream model target from frontier tiers to high-speed flash tiers while injecting warning headers.
- Runaway Agent Loop Circuit Breaker: Tracks consecutive agent turn hashes and trips an
OPENcircuit if an agent exceeds 25 recursive tool calls without state progression. - OpenTelemetry GenAI Semantic Conventions: Emits structured
gen_ai.usage.cost,gen_ai.request.model, andgen_ai.budget.actionspans to Jaeger/OTLP collectors.
Click any node in the SVG diagram or list below to inspect its payload contract, latency SLA, and retry policy.
Select any node in the pipeline to examine its architectural responsibility, input/output schema types, p95 execution latency, and error recovery policy.
Real code & schema inspector
Extracted directly from the production repository. Switch tabs to inspect the core execution logic, strict JSON/database data contracts, and structured LLM instructions.
# Enums and Data Models
# ============================================================================
class EnforcementAction(str, Enum):
ALLOW = "ALLOW"
FALLBACK = "FALLBACK"
THROTTLE = "THROTTLE"
REJECT = "REJECT"
class WindowType(str, Enum):
SLIDING_MINUTE = "SLIDING_MINUTE"
SLIDING_HOUR = "SLIDING_HOUR"
DAILY = "DAILY"
MONTHLY = "MONTHLY"
class ScopeLevel(str, Enum):
GLOBAL = "GLOBAL"
TENANT = "TENANT"
PROJECT = "PROJECT"
AGENT = "AGENT"
USER = "USER"
@dataclass(frozen=True)
class ModelPrice:
"""Pricing configuration per million tokens in USD."""
prompt_price_per_m: Decimal
completion_price_per_m: Decimal
def calculate_cost(self, prompt_tokens: int, completion_tokens: int) -> Decimal:
p_cost = (Decimal(prompt_tokens) / Decimal(1_000_000)) * self.prompt_price_per_m
c_cost = (Decimal(completion_tokens) / Decimal(1_000_000)) * self.completion_price_per_m
return (p_cost + c_cost).quantize(Decimal("0.000001"), rounding=ROUND_HALF_UP)
@dataclass
class BudgetPolicy:
"""Policy governing financial and invocation limits for a specific scope."""
scope_id: str
scope_level: ScopeLevel
limit_usd: Decimal
window_type: WindowType
soft_cap_ratio: float = 0.80 # 80% triggers dynamic fallback
hard_cap_ratio: float = 1.00 # 100% triggers hard rejection
max_requests_per_minute: int = 120
max_consecutive_agent_loops: int = 25 # Runaway loop circuit breaker
fallback_models: List[str] = field(default_factory=list)
@dataclass
class EvaluationDecision:
"""Output decision returned by the Budget Engine prior to upstream invocation."""
action: EnforcementAction
allowed_model: str
original_model: str
current_spend_usd: Decimal
budget_limit_usd: Decimal
utilization_pct: float
reason: str
retry_after_seconds: Optional[float] = None
telemetry_attributes: Dict[str, Any] = field(default_factory=dict)
@dataclass
class UsageRecord:
timestamp: float
cost_usd: Decimal
prompt_tokens: int
completion_tokens: int
model: str
# ============================================================================
# Model Pricing Registry
# ============================================================================
class ModelPricingRegistry:
"""Catalog of model token rates per million tokens."""
DEFAULT_PRICING: Dict[str, ModelPrice] = {
# OpenAI Models
"gpt-4o": ModelPrice(Decimal("2.50"), Decimal("10.00")),
"gpt-4o-2024-08-06": ModelPrice(Decimal("2.50"), Decimal("10.00")),
"gpt-4o-mini": ModelPrice(Decimal("0.15"), Decimal("0.60")),
"gpt-4-turbo": ModelPrice(Decimal("10.00"), Decimal("30.00")),
"o1-preview": ModelPrice(Decimal("15.00"), Decimal("60.00")),
"o1-mini": ModelPrice(Decimal("3.00"), Decimal("12.00")),
# Anthropic Models
"claude-3-5-sonnet-20241022": ModelPrice(Decimal("3.00"), Decimal("15.00")),
"claude-3-5-haiku-20241022": ModelPrice(Decimal("0.80"), Decimal("4.00")),
"claude-3-opus-20240229": ModelPrice(Decimal("15.00"), Decimal("75.00")),
Interactive dry-run simulator
Select a test scenario and trigger a deterministic dry-run execution across the node topology to inspect real-time logs, compute metrics, and final output payloads.
Choose a payload scenario below or click "Run Dry-Run Simulation" to step through the pipeline stages and inspect the resulting JSON output contract.
Under normal budget utilization (<80%), the gateway adds only 3.2ms of routing overhead, preserves the requested frontier model, and commits exact 6-decimal-place token spend.
{
"id": "chatcmpl-otel-98a7f2c1",
"model": "gpt-4o",
"budget_governance": {
"action": "ALLOW",
"original_model": "gpt-4o",
"routed_model": "gpt-4o",
"utilization_pct": 42.19,
"current_spend_usd": "42.187350",
"budget_limit_usd": "100.000000"
},
"otel_trace_id": "4bf92f3577b34da6a3ce929d0e0e4736"
}
Production resilience & edge-case handling
Every production system is defined by how it behaves when upstream dependencies fail, rate-limits trigger, or malformed payloads arrive at the boundary.
Zero Floating-Point Drift Under Concurrency
Token prices ($0.00000015/token) accumulate binary IEEE 754 drift in standard floats. All ledger math uses Python Decimal('0.000001') with per-tenant asyncio.Lock primitives.
Two-Stage Thresholds (80% Soft / 100% Hard)
Instead of dropping production traffic at 100%, the 80% soft-cap rewrites requests to gemini-2.5-flash or gpt-4o-mini, extending remaining runway by up to 15x.
AST & Prompt-Hash Loop Detection
Tracks sliding state hashes across agent turns. If an autonomous agent repeats tool-call signatures past max_consecutive_agent_loops, the proxy trips fast with Retry-After.
Why in-process sliding windows + OTel instead of synchronous Postgres queries
Querying an external SQL database on every LLM request adds 15–40ms of network round-trip latency and creates a single point of failure when the database connection pool saturates.
By keeping sliding-window deques in memory with asynchronous WAL snapshots and emitting OpenTelemetry spans out-of-band, p95 proxy overhead stays under 3.5ms.
TRADE-OFF Sub-4ms in-memory speed with periodic async persistence, trading strict cross-region SQL locking for zero-latency hot-path execution.
Streaming SSE responses don't report token usage until the final chunk
When clients request stream: true, upstream providers omit the usage object until the final SSE frame—or drop it entirely if the client disconnects mid-stream.
To prevent budget bypass via aborted streams, the gateway pre-reserves estimated prompt tokens using a fast BPE tokenizer heuristic before opening the upstream stream, then reconciles the exact delta on stream close.
FIX Pre-flight token reservation eliminates concurrent stream over-spend.
Stack & specifications
- Python 3.11+ & FastAPI / ASGI: Asynchronous non-blocking HTTP proxy server
- OpenTelemetry SDK: Native
gen_ai.*semantic span instrumentation and OTLP exporter - Decimal Cost Engine: Fixed-point 6-decimal USD accounting across 5 hierarchy scopes
- Asyncio & httpx: Connection-pooled upstream streaming with jittered backoff
Architectural takeaway
Observability without enforcement is just a post-mortem receipt. Putting a deterministic Decimal budget state machine directly in the proxy hot path turns LLM spend from an unpredictable monthly invoice into a bounded engineering invariant.