Operations, Routing and Economics
An AI system can be correct in a demo and fail under traffic, provider changes, retry storms, stale caches or silent quality drift. This stage operates quality, latency, reliability and cost as one measured product frontier.
Section 7 of 8 · 12 units · about 56 hours
By the end you can Load-test the system through saturation and a provider outage, recover from a bad prompt or model release, and produce a privacy-safe trace-backed quality-latency-cost-reliability frontier with one robust improvement and one failed optimization.
Units
- End-to-end request budgets and accepted-quality goodput4h
- A GenAI trace schema with redaction, sampling and retention5h
- Online quality signals, delayed outcomes and silent regressions4h
- Exact cache identity and semantic cache false hits5h
- Cache invalidation, freshness, stampedes and outage behavior4h
- Policy routing, fallback and hedging under correlated failure5h
- Rate limits, admission control, retry amplification and load shedding5h
- Streaming, batching and tail latency at the application layer3h
- Task-level SLOs, error budgets, canary, shadow and rollback5h
- Prompt, model, schema and index lifecycle, and spend controls5h
- Load through saturation, a provider outage and recovery5h
- The quality, latency, cost and reliability frontier, and a negative optimization result6h
Build it
Mini project · about 18 to 24 hours
Task-aware operations with bounded routing and honest economics
Extend agentlab in ops/ with privacy-aware telemetry, scoped caching, policy routing and task-level release controls. Use deterministic CPU fakes without paid APIs to prove accounting and authorization before comparing accepted outcomes, resource use and recovery; optional observations from your local model remain separate.
- 1Extend the ledger with token-weighted admission, bounded queues, priority shedding and one retry owner. Check fake-clock quota races and atomic reserve/settle against independent fixtures and the pinned Cookbook
OfflineClientexample; retain duplicate-settlement, missing-usage, unresolved-hold and exhausted-budget regressions, failed attempts and human escalation. - 2Instrument
ops/against pinned GenAI conventions using OpenTelemetry SDK. Before evaluation, test parentage, non-duplicated usage, two-tenant export access, secret exclusion including upload hooks, and fake-clock retention. Retain sampling-independent counters and version-attributed quality panels; check delayed-label cohorts, workload slices and seeded silent regression against trusted outcomes. - 3Build scoped exact keys and semantic eligibility against independently labeled answer interchangeability. Retain key-mutation and privacy regressions, development threshold sweeps and held-out false-hit denominators for entity, negation, date and conversation changes; compare accepted-task utility against no caching, distinguishing prefix reuse from answer reuse.
- 4Add exact-key singleflight, expiry and invalidation generations. Against barrier-controlled fakes and clocks, test deletion and revocation during write-back, follower cancellation, loader failure and cache-outage admission; retain waiter outcomes and backend counts proving stale-content denial, fenced write-back and subsequent authorized recovery.
- 5Check routing, cascades, fallback and delayed hedging against independent policy tables; retain forbidden-target, partial-stream restart and independent/correlated-delay cases, charging losing work. Hedge only independent CPU fakes, never effects. Optionally check streaming and bounded batching against fake-clock timelines, retaining partial-output rejection and accepted-task timing.
- 6Bind each task to an immutable compatible prompt, model, schema, policy and index manifest. Test task SLOs, error-budget actions and multiwindow alerts against independent event counts; retain isolated shadow accounting, simultaneous-control canary simulation, missing-evidence holds and bad-candidate rollback with current deletion, permission and recipient-effect checks.
- 7Run the pinned Cookbook cost-quality dry run without hosted calls, labeling it simulated. Repeat fixed-model, routed and cached policies with identical held-out items, graders, budgets and scheduled arrivals through saturation, outage and cold/warm recovery; retain full-accounting frontier evidence and paired uncertainty, ablating negative results.
What you hand in
ops/tracing, cache, routing, admission, release manifests and cost ledger with independent deterministic regressions intests/.- Redacted task and attempt records, held-out cache labels, quality panels and repeated policy-frontier evidence in
reports/. - Canary, rollback and outage runbooks with recovery timelines, compatible artifact checks, an ablated negative result and evidence-linked decisions.
How to check it
- Self-grade with the rubric below
- OpenAI Cookbook pinned offline spending controller
Run only
OfflineClient; supplement its synchronous example with independent concurrent reservation, duplicate settlement and unresolved-charge tests. - OpenAI Cookbook pinned cost-quality dry run
Disable live API and judge calls; use matching helper revisions. Simulated scores never replace independent task outcomes.
How it's graded
Bounded accounting and authority
Pass: Independent fake-clock and accounting tests validate admission, concurrent reservations, unique settlement, unresolved holds and inherited budgets; target-specific denials prevent fallback bypass. Every logical task and reached attempt reconciles, including failures and escalation.
Great: Seeded retry multiplication, premature refunds and forbidden fallback fail before repair; policy and resource bounds survive correlated outages, cache loss and canceled losing hedges without treating unknown usage as free.
Privacy and cache correctness
Pass: Your schema, secret-canary, tenant-access and retention tests gate export; trusted cohort fixtures validate quality monitoring. Independently labeled cache tests report held-out false-hit denominators, while barriers verify invalidation, waiter termination and authorized recovery.
Great: Upload hooks and unsampled paths remain secret-free; semantic false hits stay distinct from freshness defects. Late writes, cancellation and rollback cannot resurrect revoked evidence, and monitoring separates missing outcomes from behavioral regression.
Release and recovery evidence
Pass: Independent event counts validate task SLOs and burn alerts. Simultaneous-control canary and isolated shadow tests reject bad artifacts, hold incomplete evidence and verify compatible rollback without duplicate effects; outage timelines retain unrecovered cases.
Great: Shared-dependency degradation triggers absolute task gates even when candidate and control agree; recovery includes backlog, pending spend and mature outcomes, with interventions recorded rather than hidden.
Comparable policy frontier
Pass: Repeated matched policy trials retain send lag, queue age, counted latency tails, goodput, spend and human work. Item records regenerate the quality-latency-cost-reliability-security frontier with paired uncertainty, cold/warm and fault slices, and an ablated negative optimization.
Great: A repeatable feasible gain is supported across relevant slices or its absence is explicit. Full accounting includes lookup, population, scoring, shadow, canceled and human work; fake capacity never becomes a local-model performance claim.
Resources
- Google SRE Book and SRE WorkbookGoogle
Read SRE book Chapter 21 Handling Overload ("Deciding to Retry": per-request and per-client retry budgets; client-side throttling
max(0, (requests - K * accepts) / (requests + 1))with K = 2, printed as an image; criticality) and Chapter 22 Addressing Cascading Failures (queue management, load shedding, retries with the 4^3 = 64 amplification, deadline and cancellation propagation). Then Chapters 3, 4 and 6 for error budgets, SLOs and golden signals, and Workbook Chapters 2 Implementing SLOs, 5 Alerting on SLOs (burn rates), 16 Canarying Releases and Appendix B (error budget policy). Skip SRE Chapter 10 and Workbook Chapter 17, which is about team workload. The numbers are examples to calibrate on your own workload. - AI Engineering Handbook - Production AIHandbook Academy
Read the chapters that carry the LLM-specific half: 2.6 Gateways and routing, 2.7 Prompt caching, 3.4 Prompt versioning, 8.6 Tracing, 8.7 Monitoring and dashboards, 10.3 Cost engineering, 10.4 Latency engineering, 10.5 Shipping changes, 10.6 SLOs and incident response and 10.7 AI infrastructure patterns. Prices and model names in them date from June 2026; recompute any cost with your own numbers.
- OpenTelemetry GenAI Semantic ConventionsOpenTelemetry
The opentelemetry.io GenAI pages now point here; pin this commit (status Development). Read
client-inference.md(inference span,gen_ai.usage.*: cache read and write tokens are subsets of input),gen-ai-spans.md(embeddings, retrieval,execute_tool, recording content only by opt-in) andgen-ai-agent-spans.md(invoke_agent). Emit a redacted span tree and assert required attributes and parentage. - Prompt Caching (OpenAI)OpenAI
Read "How caching works", "How prefix matching works", "Cache lifetime" and "Summary of model differences": GPT-5.6 and later use implicit and explicit breakpoints, report
cache_write_tokensbesidecached_tokens, and charge writes and reads differently; earlier models differ. Normalize a stored usage fixture; this is prefix reuse, not response reuse. - MeanCache: User-Centric Semantic Caching for LLM Web ServicesGill et al.
Read IV-A3 (true and false hits and misses), IV-B Figure 7, IV-C and IV-F (thresholds 0.83 for MPNet and 0.78 for ALBERT on its own data). Report false hits per served hit and per negative query, which have different denominators. Sweep a threshold on held-out labeled pairs before enabling any semantic cache.
- AlgoMaster AI Engineering - Production UnitsAlgoMaster
Read the free lessons
understanding-ai-application-costs(hidden costs, cost tracking, budgets) andarchitecture-patterns-for-ai-applications("Why Queues Matter"), then the owned premium lessons on caching, model selection and routing, rate limiting, reliability, monitoring and CI/CD for AI. For every recommendation, run one measured workload or fault case. - LLM Cost Optimization and Observability DesignEngineering Handbook
Read the LLM Cost Optimization chapter (price ladder and cost attribution), then LLM Evaluation and Observability at
/curriculum/ai-ml-system-design/llm-evaluation-observability/. Use the capacity and cost equations as hypotheses, validate them against your workload and record where system behavior differs. - Semantic Cache and Model Router Case StudiesEngineering Handbook
Read case study 8.37 (model router and gateway: routing strategies, failover before the first byte, hedging cost, budget reservation with soft and hard limits, a cost ledger) and case study 8.36 at
/curriculum/case-studies/semantic-cache/(threshold calibration, invalidation channels, singleflight, fail-open). Recompute their capacity tables: 8.36's embedding-cost and savings lines are off by orders of magnitude. Implement only the smallest cache and router needed for a three-policy comparison. - Prompt Caching (Claude)Anthropic
Read explicit breakpoints, automatic prefix checking, cache limitations (minimums differ by model), tracking cache performance and what invalidates the cache. Claude reports
input_tokensexcluding cache reads and writes, unlike OpenAI, so normalize both before recording one input total. - RouteLLM: Learning to Route LLMs with Preference DataOng et al.
Read Section 3.2 (call fraction, performance gap recovered, APGR, CPT) and Section 4.2. Replay the stored GSM8K outcomes in the repository (pinned 0b64fda) for a random-routing baseline. Its matrix-factorization router needs an OpenAI embedding key, and
evaluate.pypasses a model name where the model pair belongs. - FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving PerformanceChen, Zaharia and Zou
Read Section 3, Strategy 3 LLM cascade: escalate only when a scorer rejects the cheaper answer, and count the cost of every stage reached. Section 5 notes the scorer needs train and test from the same distribution.
- Using Load Shedding to Avoid OverloadAmazon Builders' Library
Read "Preventing work from going to waste", "Testing" (goodput should plateau, not collapse), "Visibility", "Prioritizing requests" and "Watching out for queues". Count accepted, quality-checked work as goodput, not fast rejections.
- Per-Run Spending ControllerOpenAI Cookbook
Read the article and run its code offline: count input tokens, reserve the most a response could cost, settle the actual usage, release the rest and stop before the next call would exceed the run budget. Port the reserve and settle rule to your gateway with exact arithmetic.
- Optimizing Agents for Cost and QualityOpenAI Cookbook
Run it with live calls off: a baseline, then controls, routing, caching and a split workflow, each accepted only if a small evaluation set still passes. The numbers are modeled; copy the study design, not the results.
- vLLM Automatic Prefix CachingvLLM
Read the introduction, enabling APC, example workloads and limits: prefix caching skips repeated prefill but does not shorten decoding. Measure cold and warm requests and a changed prefix on your local server, with the model, template and settings fixed; any local server with an equivalent feature works.
- The Tail at ScaleJeffrey Dean and Luiz André Barroso
Read printed pages 77 and 78 on hedged and tied requests and their limit when slowness is correlated across replicas. Never hedge a side-effecting tool call or two generations on one saturated GPU.
- Made With MLMade With ML
Read the online evaluation section only if the rollout card needs a classical-ML comparison; the course has no LLM application content.
- LiteLLM Routing, Reliability and BudgetsLiteLLM
Use the routing, fallbacks and cooldowns, budget reservation and fail-closed rate-limit sections as a reference design for your own small gateway. A fallback must recheck the caller's model access and budget against the actual target.
- RFC 2697: A Single Rate Three Color MarkerIETF
Use Sections 2 and 3 for the rate and burst definitions behind a token bucket. The RFC meter has two buckets; derive the one-bucket application limiter explicitly and weight it by tokens, not requests.
- Full Stack Deep Learning - LLM BootcampFull Stack Deep Learning
Read the LLMOps chapter summaries "Iteration and prompt management", "Testing LLMs: What works?" and "Evaluation metrics for LLMs". Skip the 2023 model-choice sections, which are out of date.