← All Engineering Blueprints
// blueprint #01 · complexity score: 96/100 · async proxy gateway

Enforcing hard token budgets with automatic model failover and OpenTelemetry spans

Multi-agent loops and unthrottled tenant traffic can burn through an LLM API budget in minutes. This self-hosted FastAPI gateway intercepts every completion request in <4ms, enforces sliding-window Decimal budgets, serves semantic cache hits, and downgrades frontier models to fast flash tiers before hard quota exhaustion.

< 4 msProxy routing overhead (p95)
80% / 100%Soft-fallback vs. Hard-cap gates
2,442 LOCAsync Python + OpenTelemetry

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 across GLOBAL, TENANT, PROJECT, and AGENT scopes using exact Decimal('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 OPEN circuit 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, and gen_ai.budget.action spans to Jaeger/OTLP collectors.
SYSTEM TOPOLOGY & ARCHITECTURE BLUEPRINT
PRODUCTION ENGINE
OTel LLM Budget Enforcer & Dynamic Cost-Fallback Proxy architecture visualization
END-TO-END FLOW: Async Ingress → Semantic Cache → Budget Enforcer → Fallback Router → Upstream Dispatch → OTel Span & Ledger ● DETERMINISTIC PIPELINE
NODE 01 Async Ingress FastAPI + Bearer Auth NODE 02 Semantic Cache SHA-256 + Cosine >=0.92 NODE 03 Budget Enforcer Decimal Sliding Window NODE 04 Fallback Router Tier Downgrade + Breaker NODE 05 Upstream Dispatch Async httpx Stream NODE 06 OTel Span & Ledger OTLP Export + Commit

Click any node in the SVG diagram or list below to inspect its payload contract, latency SLA, and retry policy.

01 · INTERACTIVE NODE TOPOLOGY INSPECTOR
Inspect Stage-by-Stage Execution Contracts & Fault Boundaries

Select any node in the pipeline to examine its architectural responsibility, input/output schema types, p95 execution latency, and error recovery policy.

NODE 01 · Async Ingress
LATENCY: 0.4 ms
Architectural Role
Intercepts OpenAI/Anthropic/Gemini-compatible chat completion payloads, extracts X-Tenant-ID and X-Agent-Loop-Count headers, and initializes the OpenTelemetry root span.
Input / Output Payload Contract
IN: POST /v1/chat/completions (JSON) -> OUT: ValidatedChatRequest(tenant_id, model, messages, loop_depth)
Error & Retry Policy
Immediate HTTP 400/401 rejection on malformed schema or missing tenant scope.

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.

// SOURCE: products/otel-llm-budget-enforcer-cost-fallback-proxy-20261012/package/budget_engine.py
# 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.

03 · LIVE DETERMINISTIC DRY-RUN SIMULATOR
Step Through Topology Nodes & Stream Execution Telemetry

Choose a payload scenario below or click "Run Dry-Run Simulation" to step through the pipeline stages and inspect the resulting JSON output contract.

SELECT TEST SCENARIO:
NODE 01 · Async IngressNODE 02 · Semantic CacheNODE 03 · Budget EnforcerNODE 04 · Fallback RouterNODE 05 · Upstream DispatchNODE 06 · OTel Span & Ledger
// TIMESTAMPED EXECUTION TRACE ACTION: ALLOW (PRIMARY MODEL)
[00:00.001] INGRESS: POST /v1/chat/completions | tenant=enterprise_alpha | model=gpt-4o [00:00.002] CACHE: Canonical SHA-256 miss (similarity=0.41 < 0.92 threshold) [00:00.003] BUDGET: Tenant spend $42.18 / $100.00 (42.18% < 80.0% soft cap) -> Action: ALLOW [00:00.003] ROUTER: Circuit state=CLOSED | Dispatching primary target model=gpt-4o [00:00.316] UPSTREAM: HTTP 200 OK from primary provider (1,420 in / 380 out tokens) [00:00.318] OTEL: Exported span gen_ai.chat | cost_usd=0.007350 | utilization_pct=42.19%

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.

FINAL OUTPUT PAYLOAD CONTRACT SCHEMA VALIDATED ✓
{
  "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"
}
TOTAL LATENCY 318 ms (3.2 ms proxy)
COMPUTE / TOKENS 1,420 prompt / 380 completion tokens
ESTIMATED RUN COST $0.007350 USD (Exact Decimal)
EXECUTION MODE Deterministic Self-Hosted

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.

01 · DECIMAL PRECISION & LOCKING

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.

02 · SOFT-CAP GRACEFUL DEGRADATION

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.

03 · RUNAWAY LOOP CIRCUIT BREAKER

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.

ARCHITECTURAL DECISION

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.

PRODUCTION PITFALL

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.