FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Cost Latency and Reliability

How budgets fallbacks retries routing and service targets balance operating outcomes.

Freshness: current•14 min read•Evaluation, Reliability, and Observability

Key Learning Outcomes

  • ✓Model unit cost
  • ✓Set reliability targets
  • ✓Design bounded fallback behavior
Full Technical Reference Document

Mental model

Production AI reliability optimizes a coupled portfolio—task quality, cost per successful outcome, tail latency (p95/p99), and graceful degradation—rather than minimizing raw token price alone. By combining fast-to-flagship model cascading, jittered retry caps with sliding-window circuit breakers, bounded hedged requests, and OpenTelemetry GenAI cost attribution, gateways absorb upstream provider stalls without triggering retry storms or budget runaway.

Classify Task Difficulty
Check Circuit Breaker State
Fast Tier or Hedged Call
Escalate or Shed Load
Emit OTel GenAI Cost Span
Conceptual teaching model synthesized from:Latency OptimizationOpenTelemetry Generative AI Semantic ConventionsCircuitBreaker

Learning outcomes

  • Model effective request amplification Reff=λ∑rkR_{\text{eff}} = \lambda \sum r^k during upstream brownouts and stop retry storms using sliding-window circuit breakers.
  • Compare tail-latency hedging against retry-with-backoff on total token expenditure, concurrency pressure, and p99 completion delay.
  • Design model-tier cascading pipelines that route routine queries to small, low-latency models and escalate only low-confidence or complex cases to flagship models.
  • Instrument per-request token cost, cache hits, and fallback outcomes using OpenTelemetry GenAI semantic conventions (gen_ai.usage.*).

Theory

Optimizing an LLM application solely on sticker price per million tokens misstates real unit economics. A cheap model that fails schema checks 25% of the time and triggers two multi-turn retries costs more per completed task—and delivers worse tail latency—than a calibrated cascade or a single higher-capability call. True Cost per Successful Task amortizes input tokens, cached prompt hits, reasoning/output tokens, retries, retrieval calls, and fallback escalations across verified task completions.

Retry Amplification Storms vs Circuit Breakers

When an upstream model endpoint degrades (for instance rate-limiting 429 or 503 overload), naive client retries multiply incoming load at the exact moment downstream capacity collapses. If incoming baseline traffic arrives at rate λ\lambda, each failed request triggers up to KK retries, and individual attempt failure probability is r∈[0,1)r \in [0, 1), the effective downstream request rate ReffR_{\text{eff}} follows a geometric series:

Reff=λ∑k=0Krk=λ⋅1−rK+11−rR_{\text{eff}} = \lambda \sum_{k=0}^{K} r^k = \lambda \cdot \frac{1 - r^{K+1}}{1 - r}

Suppose normal traffic is λ=200\lambda = 200 req/s and each client allows K=3K = 3 retries (4 total attempts). Under a mild partial outage where r=0.60r = 0.60, effective request pressure climbs to 200 * (1 + 0.60 + 0.36 + 0.216) = 435.2 req/s (2.18x load), pushing saturated token buckets deeper into overload and raising failure probability toward r=0.90r = 0.90, where load approaches 200 * 3.44 = 688 req/s.

Resilience4j-style count-based or time-based sliding-window circuit breakers halt this positive feedback loop. When the rolling failure rate or slow-call rate over the last 100 calls crosses a threshold (for example 50%), the breaker transitions CLOSED -> OPEN, short-circuiting primary traffic immediately to a secondary region or degraded fallback for a cool-down wait (waitDurationInOpenState = 15s) before admitting limited HALF_OPEN probe requests.

Hedged Requests and Model-Tier Cascading

Two distinct latency-and-cost levers complement circuit breaking:

  1. Hedged requests: Instead of waiting passively for a stalled p99 request to hit a 30s timeout, the gateway fires a backup call to a secondary endpoint only if the primary has not emitted a first token or completed within the local p95 threshold (thedget_{\text{hedge}}), cancelling whichever loses. Firing a hedge at p95 increases average request volume by only ~5% while sharply compressing p99 latency—provided hedging is disabled automatically whenever the retry budget or circuit breaker signals upstream saturation.
  2. Model-tier cascading: A lightweight fast model (say \$0.15 per 1M input and \$0.60 per 1M output) processes incoming requests first; only outputs failing deterministic confidence, Pydantic schema, or verifier checks escalate to a flagship model (say \$3.00 per 1M input and \$15.00 per 1M output).

Consider 100,000 daily classification/extraction tasks averaging 1,000 input and 200 output tokens each:

  • Sending 100% to the flagship model costs 100,000 * (1,000 * $3.00 + 200 * $15.00) / 1e6 = $600.00/day.
  • Cascading 82% resolved cleanly by the fast tier plus 18% escalated to the flagship tier costs 100,000 * (1,000 * $0.15 + 200 * $0.60) / 1e6 = $27.00 for the initial pass plus 18,000 * $0.006 = $108.00 for escalations, totaling \$135.00 per day (77.5% savings) with negligible quality loss.

OpenTelemetry GenAI Attribution

Using OpenTelemetry GenAI semantic conventions (gen_ai.system, gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens), every router hop records latency, retry count, circuit-breaker state, and USD cost onto one distributed trace so teams measure cost per verified outcome rather than opaque API invoices.

Trade-offs

Selecting resilience and routing controls balances duplicate token spend, tail latency, and infrastructure complexity.

Control MechanismLatency Impact (p99)Extra Token SpendFailure IsolationPrimary Risk if Misconfigured
Exponential Backoff + Full Jitter (K <= 2)Adds 0.5–4s on transient failuresOnly failed retry attemptsProtects against brief blipsAmplifies outage if retry rate isn't capped
Sliding-Window Circuit BreakerFast-fails in < 2ms when openZero wasted tokens on broken upstreamPrevents cascading thread/queue exhaustionPremature trips if window size is too small
p95 Hedged RequestCuts p99 tail spikes significantly+5% baseline call overheadMasks single-replica tail stallsWorsens rate-limit saturation if unguarded during brownouts
Fast -> Flagship Model CascadeLowers median latency on 75–85% of trafficCuts total spend 50–80%Isolates complex cases on flagship tierWeak escalation classifier silently lowers accuracy

Failure modes and misconceptions

  • Hedged requests firing during upstream 429 outages: Hedging helps independent single-node tail latency, not global capacity exhaustion. Always suppress hedging when circuit breakers warn of elevated 429 or 503 rates.
  • Retrying deterministic 400 schema or context-overflow errors: Re-sending an invalid payload or an oversized prompt three times wastes latency and money on guaranteed failures. Classify HTTP/API errors strictly into retryable (429, 500, 503, timeouts) vs terminal (400, 401, 403, schema invalid).
  • Measuring cost per raw API call instead of cost per verified success: Switching to a cheaper model that drops completion success from 96% to 72% inflates human review costs and multi-turn retries, increasing total system cost.
  • Unattributed OpenTelemetry traces hiding retry waste: Logging only the final successful call hides the two timed-out attempts and three router misses that tripled actual span cost. Emit child spans for every attempt tagged with gen_ai.usage.input_tokens and cascade.tier.
  • Silent safety regression on degraded fallbacks: Routing a sensitive compliance task onto an unvalidated fallback model when the primary circuit opens can violate original safety or structured-schema guarantees.

Decision scenario

A legal-clause extraction API handles 150 req/s at peak with a p99 latency SLA of 2.5s and a monthly LLM budget ceiling of \$8,000. During a recent regional rate-limit event, unlimited retries pushed outbound traffic to 480 req/s while costs spiked 2.4x on failed timeouts. Rebuild the gateway with three controls: implement a 100-call sliding-window circuit breaker opening at 45% failures for 15s to divert traffic to a secondary provider region, enable p95 hedging (t_hedge = 1.4s) exclusively when breaker failure rate stays below 5%, and route documents under 4,000 tokens through a fast tier escalating only low-confidence Pydantic failures to the flagship model—emitting gen_ai.usage.* OTel attributes on every attempt.

Implementation example

This Python LLM gateway router integrates sliding-window circuit breaking, retry-storm suppression, fast-to-flagship cascading, and OpenTelemetry-compatible usage accounting.

python
import time
from collections import deque
from dataclasses import dataclass
from typing import Any, Callable
​
@dataclass
class AttemptSpan:
tier: str; input_tokens: int; output_tokens: int; cost_usd: float; ok: bool
​
class SlidingWindowBreaker:
def __init__(self, size: int = 100, fail_rate: float = 0.45, cooldown_s: float = 15.0) -> None:
self.win, self.fail_rate, self.cooldown_s = deque(maxlen=size), fail_rate, cooldown_s
self.opened_at: float | None = None
​
def allow(self) -> bool:
return self.opened_at is None or (time.monotonic() - self.opened_at >= self.cooldown_s)
​
def record(self, ok: bool) -> None:
self.win.append(ok)
if self.opened_at is not None: self.opened_at = None if ok else time.monotonic(); return
if len(self.win) >= 20 and (1.0 - sum(self.win) / len(self.win)) >= self.fail_rate:
self.opened_at = time.monotonic()
​
def route_with_cascade(
prompt: str, call_fast: Callable[[str], tuple[dict[str, Any] | None, AttemptSpan]],
call_flagship: Callable[[str], tuple[dict[str, Any] | None, AttemptSpan]], breaker: SlidingWindowBreaker,
) -> tuple[dict[str, Any], list[AttemptSpan]]:
spans: list[AttemptSpan] = []
if breaker.allow():
res, span = call_fast(prompt); spans.append(span); breaker.record(span.ok)
if res is not None and res.get("confidence", 0.0) >= 0.85: return res, spans
res, span = call_flagship(prompt); spans.append(span)
if res is None: raise RuntimeError("Fast cascade and flagship fallback exhausted")
return res, spans

Knowledge check

Reflect before revealing the guide

Why must hedged requests be gated by circuit-breaker health metrics during upstream brownouts, and what does cost per successful task capture that token sticker price misses?

Prerequisites & Related Concepts (4)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next