You've built every lane. This final chapter is what makes the whole thing safe to run and safe to change: evals to prove quality moved the right way, and the cost/latency levers that decide whether any of it can actually ship. This is the trust & operations lane — the difference between a demo and a product.
A probabilistic system has a paralyzing property: you can't tell by looking whether a change helped. Tweak a prompt, upgrade a model, adjust retrieval — did quality go up or down? Without measurement you're guessing, and you'll discover regressions from angry users instead of a dashboard. Evals are the answer, but calling them "the AI-native test suite" undersells what they are architecturally. A unit test asserts a deterministic property of code you own. An eval estimates a rate — of a component you often don't own, whose behaviour the provider can change under a stable name — and every number it produces carries a confidence interval whether or not the dashboard shows one.
The strongest argument for investing early is not quality, it's optionality. Hosted models get deprecated on the provider's schedule, not yours; a cheaper model arrives that might handle 70% of your traffic; a competitor's model is better on your domain. Each of those is a migration, and a team without an eval suite either can't take it or takes it blind. The eval suite is the contract that makes the model a swappable dependency instead of a load-bearing assumption. Teams that skip it discover this the first time a forced deprecation lands and they have to re-derive, from user complaints, what "working" meant.
Build it as layers with very different costs, and run each at the cadence its cost allows. The mistake is a single end-to-end judged suite that is too slow and expensive to run on every PR, so it runs weekly and regressions ship between runs. Most breakage in a compound system is localised — retrieval stopped returning the right chunk, the planner picked the wrong tool, the output stopped parsing — and component evals catch it at a fraction of the cost and with a precise location.
An offline eval is a curated dataset of inputs paired with expected qualities, run against a candidate change and scored. Use deterministic checks where you can (exact match, contains, valid JSON, correct tool called) and softer scoring where you can't. The workflow mirrors CI: run the eval on every change, compare the score distribution to the baseline, and gate the ship on it. Start small — 50 hand-picked hard cases are enough to catch catastrophic regressions — and grow the set as you find failures.
Eval set
curated inputs + expected qualities
Run candidate
new prompt / model / retrieval
Score
rules + LLM-as-judge
Compare
vs baseline → ship or reject
Run it on every change. A prompt tweak or model upgrade that raises average score ships; one that regresses the distribution doesn't. Without this, you're changing a probabilistic system blind.
The part most teams get wrong is resolving power. A pass rate is a binomial estimate, and at 50 cases the 95% interval is roughly ±10 points — a prompt change that silently drops you from 85% to 78% is indistinguishable from noise. Teams then ship on "the number went up by 2", which at that size is a coin flip dressed as a metric. Three fixes, in order of leverage:
Work the paired case through, because it changes how big the suite needs to be. Take 300 items, baseline and candidate both at roughly 85%. Pooled, the interval on each is about ±4 points and a 3-point drop is invisible. Paired, you only look at the items that disagreed. Suppose 14 went pass→fail and 4 went fail→pass. McNemar's statistic with continuity correction is (|14 − 4| − 1)² ÷ (14 + 4) = 81 ÷ 18 = 4.5, above the 3.84 threshold for p < 0.05. The same 300 items that could not see a 3-point move in aggregate can see it when you count flips, because the 282 concordant items contribute no noise at all. The corollary is uncomfortable: if your suite is mostly items every model passes, it has very few chances to disagree, and it will report "no significant change" for regressions that matter. Curate for discrimination: an item that 100% of candidates pass is a smoke test, not an eval case, and it belongs in L0.
Slice floors need their own sizing. A 5% slice of a 1,000-item suite is 50 items, which is the ±10-point row of the chart above; a per-slice floor at that size will either never fire or fire on noise. The fix is stratified oversampling: build the suite so every slice you gate on has at least a few hundred items, and reweight to production mix only when you report the headline number. That makes the suite unrepresentative on purpose, which is correct — its job is to detect regressions where they are expensive, not to mirror traffic. Decide the minimum detectable effect first (say, "a 5-point drop on any gated slice"), then derive items per slice from it; teams that go the other way end up with a suite size chosen by how many cases someone had time to write.
Two slower failures. Overfitting the suite: after months of prompt-tweaking against the same 300 cases, the prompt is tuned to them — keep a held-out split you look at rarely, and treat a widening gap between tuned-set and held-out scores as the alarm. Suite staleness: the set was drawn from last year's traffic; the product has moved. If the eval pass rate is flat while online signals (7.4) decline, the suite no longer represents production — refresh it from recent traces, not from imagination.
Much AI output has no single right answer — a summary, an explanation, a tone. When you can't write an assert, use LLM-as-judge: a strong model scores the output against a written rubric ("is it accurate? grounded in the sources? complete?"). It's cheap and scalable, which is its whole value. But judges are biased — toward longer answers, toward the first option, toward their own style — so calibrate against human labels and treat the score as a proxy, not truth.
candidate answer
rubric
accurate? grounded? complete?
Judge model → score + reason
Powerful but imperfect: judges have biases (length, position, self-preference). Calibrate against human labels, use a strong judge, and ask for a reason — don't treat its score as ground truth, treat it as a cheap, scalable proxy.
How judges fail in production is more specific than "they're biased":
Once agreement is measured, use it; don't just report it. A binary judge is a classifier with a sensitivity (it marks good answers good) and a specificity (it marks bad answers bad), both measurable on the human-labelled set. The observed pass rate is biased by both, and the bias is correctable: true rate ≈ (observed + specificity − 1) ÷ (sensitivity + specificity − 1), the Rogan–Gladen estimator from epidemiology. With illustrative values — sensitivity 0.90, specificity 0.80, observed 80% — the corrected rate is (0.80 + 0.80 − 1) ÷ 0.70 ≈ 86%. Two consequences matter more than the number. A lenient judge (low specificity) compresses the gap between a good and a bad candidate, so a real regression shows up smaller than it is. And if the judge's error rates differ between baseline and candidate — the candidate is more verbose and the judge likes verbosity — the correction is wrong and so is the comparison. That is why a change of candidate style warrants re-checking judge calibration on a sample of the new outputs.
Also budget for it. Illustratively: 2,000 items × 3 samples × 2 orderings for pairwise × roughly 3,000 tokens of judge input (question, sources, two answers, rubric) is 36M judge input tokens per full run, before output. At strong-model prices that is a real line item per run, and a team running it on every PR across a dozen engineers is spending more on evaluation than on inference for a feature with modest traffic. The shape that works: L0 and L1 on every PR, a judged paired sample of a few hundred high-discrimination items on PRs that touch prompts or models, the full judged suite nightly and before release. Cache judge verdicts keyed by (item, candidate output hash, judge version, rubric version) — an unchanged output needs no re-judging, and on a typical PR most outputs don't change.
Offline evals can't cover everything real users do. Online evals watch production: explicit thumbs, implicit signals (did they retry, edit, or abandon?), and sampled human review. The enabler is tracing — every request carrying its retrieved chunks, tool calls, tokens, cost, and latency per span — so when quality drops you can see where in the pipeline it broke. The flywheel: failures caught in production become new offline eval cases, so the system compounds in quality instead of drifting.
Signals
· explicit thumbs (sparse, skewed negative)
· retries, edits, abandonment (implicit)
· sampled human review
Tracing (per request)
· retrieved chunks
· each tool call + result
· tokens · cost · latency per span
Failures found in production become new cases in the offline eval set — the flywheel that makes the system better over time instead of drifting.
The flywheel is real, but three properties of online signals are routinely misread. First, explicit feedback is sparse and self-selected. A small minority of sessions leave a thumb at all, and they skew toward the annoyed; a thumbs-down rate is a measure of who bothers to click as much as of quality, and it moves when you move the button. Use it to find failures, not to rate them. Second, implicit signals are ambiguous in sign. "No follow-up question" means either the answer was complete or the user gave up; "user edited the draft" means either it was wrong or it was a good starting point they personalised. Each implicit signal needs a one-time validation against labelled sessions before anyone puts it on a dashboard, and that validation expires when the UX changes. Third, and most expensive, trustworthy online signal is slow.
The arithmetic of that third point decides how you roll out. Sampled human review is the only online signal you can fully trust, and it is capacity-limited. Detecting a drop from 85% to 82% with conventional power (α = 0.05 two-sided, 80% power) needs roughly (1.96 + 0.84)² × 2 × p(1 − p) ÷ δ² ≈ 2,400 reviewed items per arm. At an illustrative 200 reviews a day per arm, that is twelve days during which a regressed canary is serving real users. A 10-point drop is visible in about a day; a 2-point drop takes most of a month. The rollout design follows directly: offline evals must catch everything above the size online review can see quickly, and online review is for confirming the absence of large surprises and for mining new eval cases, not for detecting small regressions.
That shapes the promotion ladder. Shadow first: run the candidate on mirrored production inputs, discard its output, and judge it pairwise against the incumbent on the same inputs — paired, so the variance argument from 7.2 applies and a few hundred items are informative. Shadowing an agent is only safe if its tools are stubbed or read-only; a shadow agent that can send email is a second production system. Then a canary at a small percentage gated on cheap, fast guardrail metrics — refusal rate, parse failures, tool-error rate, output length distribution, latency and cost per request — each of which moves within hours and correlates with the regressions you care about. Output-length and refusal-rate shifts in particular are early tells of a changed model; they're free to compute and they flag silent provider-side updates before any quality metric does. Only then ramp, with the slow human-reviewed metric as a trailing confirmation.
Tracing has its own economics that bite at scale. An agent trace that stores full prompts, retrieved chunks and tool results can easily be tens of kilobytes per request; at an illustrative 50 KB and 2M requests a day that is 100 GB a day of mostly sensitive text, with the retention, PII and access-control obligations that come with it. Keep span metadata (tokens, latency, cost, model version, prompt version, chunk ids) for everything, and full payloads by tail-based sampling: all errors, all negative feedback, all requests over the latency or cost budget, plus a small uniform sample for baselines. Head-based sampling at 1% throws away 99% of the failures you built tracing to find. And store chunk ids and index version, not only chunk text — "why did it retrieve this?" is unanswerable if the index has been rebuilt since.
With evals telling you where quality is, you spend the rest of the system's life balancing it against cost and latency. You can push any two hard; all three at once isn't free. The art is knowing which dial your product actually needs — a legal-research tool pays for quality, a high-volume support bot optimizes cost, an interactive assistant guards latency — and tuning deliberately instead of by accident.
Push quality
bigger model, rerank, more context, self-critique
Push cost down
smaller model, model cascade, semantic cache, shorter prompts
Push latency down
streaming, speculative decoding, parallel tools, smaller output
Latency deserves its own decomposition, because the model call is rarely one call. A typical request is a serial chain — guardrail, query rewrite, retrieval, a planner turn, a tool, the final answer — and each hop adds its full time-to-first-token (TTFT) before the user sees anything. The per-token mechanics are in Serving & Inference Infrastructure; at the architecture level, three rules hold. Stream the final answer so perceived latency is its TTFT, not its completion. Count hops before model speed — collapsing rewrite and planner into one call often beats any model swap. And output tokens are the expensive axis: decode is sequential, so a 400-token answer costs time roughly linear in its length, while a longer input mostly costs TTFT. Cap output length where the product allows.
Watch the tail, not the mean. The p99 of a five-hop chain is dominated by whichever hop has the fattest tail — usually a provider under load or an agent loop that took an extra turn. Tails compound across serial hops: if each of five independent hops has its own p99, the chance a request hits at least one of them is 1 − 0.99⁵ ≈ 4.9%, so the per-hop p99 is roughly your end-to-end p95. Budgeting each hop to "p99 under 1 s" does not give you an end-to-end p99 under 5 s; it gives you one in twenty requests paying a tail somewhere. Put a deadline on the whole request and a budget on agent iterations, propagate the remaining deadline to every hop so a late hop can pick a cheaper path, and decide in advance what the degraded answer is when the deadline hits.
The classic tail fix, hedged requests, needs adapting. Hedging a full generation — send a duplicate after the p95 and take whichever finishes first — doubles the cost of the most expensive calls and, because the two outputs differ, the "winner" is whatever was shorter, which is a quality bias. Hedge on time to first token instead: if the primary hasn't produced a token by its TTFT p95, send the duplicate (ideally to a different region or provider), keep whichever streams first, and cancel the other. You pay for a few percent of duplicated prefill, not duplicated decode, and you cut the tail that is usually queueing, not generation.
On cost, the unit that matters is cost per successful task, and per-token price is a poor proxy for it. Two effects dominate. First, agent loops re-send context: if turn t carries the system prompt S plus everything accumulated, input grows by roughly Δ per turn and total input over n turns is n·S + Δ·n(n−1)/2 — quadratic in turns. With illustrative S = 4k and Δ = 1.5k tokens, a 6-turn task consumes about 46k input tokens and a 10-turn task about 108k: 67% more turns, 130% more tokens. Prefix caching (7.6) changes the slope dramatically, because each turn's prompt is the previous turn's prompt plus a suffix — which is why agent prompts must be append-only; one timestamp or re-ranked tool list near the top invalidates the cache for every turn after it.
Second, success rate divides everything. Illustratively: a strong model completes 70% of tasks in 6 turns; a model at 40% of its token price completes 55% but, being weaker, loops for 9 turns. Tokens per attempt rise by about 1.9× (about 90k vs 46k input), so relative cost per success is 1 ÷ 0.70 ≈ 1.43 for the strong model and 0.4 × 1.9 ÷ 0.55 ≈ 1.4 for the cheap one — a wash on cost, with a 15-point worse success rate and 50% more latency. This is where the conventional "use the cheapest model that works" advice goes wrong: the cheap model's per-token saving is spent on extra turns and failures, and "works" was measured on single-shot evals that never saw the loop. Measure tokens-per-success and turns-per-success per model on the agent eval, not price per million tokens.
Two levers do most of the work. A model cascade routes easy queries (the majority) to a cheap model and escalates only the hard tail to a strong one — a large cost cut if the escalation rate is low and the escalation signal is trustworthy. A semantic cache serves near-duplicate questions from a prior answer, skipping the model entirely for repeat traffic. Neither is free — a cascade needs a routing decision and an escalation signal, a cache risks staleness — which is precisely why they're architecture decisions, tuned and measured with the evals from earlier in this chapter.
Query
Small model
confident? → answer
Strong model
handles the hard tail
Most queries are easy. Routing them to a cheap model and escalating only the hard minority can cut cost several-fold — provided the escalation signal catches the queries the small model gets confidently wrong.
Do the arithmetic before you build it. The small model runs on every query and escalated queries pay for both, so blended cost is cs + e·cl. With an illustrative 20:1 price ratio, a 10% escalation rate is ~6.7× cheaper than strong-only; at 30% it's under 3×; at 60% it's 1.5× — and at that point the doubled latency on escalated requests and the extra system to operate probably aren't worth it. Break-even is e = 1 − cs/cl, but the practical threshold is far lower.
The escalation rate is the number everyone tracks; the number that matters is the false-confident rate — queries the small model answered wrongly without escalating. Model self-reported confidence and token log-probs are poorly calibrated on exactly the hard inputs you need to catch, so a cascade that "saves 80%" can be quietly shipping a worse answer on a slice nobody measured. Evaluate the router as its own component: on a labelled set, measure accuracy of the small model on the queries it kept, and compare it to strong-only on the same queries. And re-check whenever either model changes — a new small model shifts its confidence distribution, and the threshold tuned last quarter is now wrong.
"how do I reset my password"
hit → return cached answer (no model call)
miss → call model, then cache
Matches on meaning, not exact string, so paraphrases hit too. The trade is staleness and the risk of serving a subtly-wrong cached answer — scope it to stable, high-repeat questions.
Before a semantic cache, take the cheaper and safer lever: prefix (prompt) caching. Most providers and self-hosted servers can reuse the computed state for an identical prompt prefix, discounting and speeding up the repeated input tokens. It's exact-match, so it cannot return a wrong answer; its only design requirement is that you put the stable parts (system prompt, tool schemas, few-shot examples, a shared document) first and the per-request parts last. Reordering a prompt is often the single highest-ROI cost change available, and it's invisible to quality evals.
A semantic cache is a correctness risk you're accepting for cost. The failure modes: negation and entity blindness — "cancel my order" and "don't cancel my order", or the same question about two different accounts, can sit very close in embedding space; cross-tenant leakage — a cache keyed only on the question serves user A's personalised answer to user B, which is a security incident, not a quality bug; and staleness — the cached answer outlives the policy or price it quotes. Key the cache by tenant and by the versions of the prompt, model and source data; restrict it to intents classified as generic; and track the hit rate honestly — on open-ended conversational traffic it's often low enough that the added risk isn't paid for.
Put the risk in the same units as the saving and the decision usually makes itself. Each hit saves one model call, say an illustrative $0.01. Each false hit — a cached answer served for a question it doesn't answer — costs whatever a wrong answer costs: a support contact, a refund, a churned user; call it $5. Break-even is a false-hit rate of 0.01 ÷ 5 = 0.2% of hits. Almost no similarity threshold on real paraphrase traffic is that precise, and you can't know your false-hit rate without labelling cache hits, which few teams do. So the semantic cache pays only where a wrong answer is cheap (suggestions, autocomplete, drafts a human edits) or where the answer space is closed enough that "near-duplicate" really means "same" (FAQ intents mapped to curated answers — at which point it's an intent classifier plus a lookup table, and should be built and evaluated as one). Also count the tax on misses: every request now pays an embedding call and an ANN lookup, which at a low hit rate adds latency to the majority to save it on the minority.
Most AI-native outages are not model failures. They are capacity failures: a provider quota measured in tokens per minute, a retry policy written for stateless HTTP, and a fallback path nobody evaluated. Provider limits are usually expressed on two axes — requests and tokens per minute — and the tokens axis is the one that surprises teams, because it is consumed by input as well as output. A feature launch that adds 8k tokens of retrieved context to every request can hit the token ceiling at a request rate that was comfortably inside it last week, with no change in traffic.
The failure then cascades in a predictable order. Requests near the ceiling get 429s. Each layer retries — the SDK, the orchestration framework, the agent's tool wrapper, the caller's HTTP client — and retries multiply rather than add: three layers each allowing 3 retries can turn one user request into (1 + 3)³ = 64 attempts in the worst case. The extra attempts consume the same quota, so the 429 rate rises, which triggers more retries. Meanwhile each retry of a long prompt re-bills its prefill and, in an agent, restarts a turn whose context is large. Latency goes from seconds to the client timeout, the client retries the whole request, and the provider sees a load multiple of real demand. The system is now spending most of its quota on requests whose users already gave up.
The mechanics that contain it are old distributed-systems practice applied with token awareness. Retry in exactly one layer and make the others fail fast. Use a retry budget (retries capped at, say, 10% of recent successful calls) rather than a per-request count, so retries vanish under sustained overload instead of multiplying it. Do client-side admission control on a token budget: estimate input tokens before sending, keep a local token bucket shaped like the provider quota, and shed or queue low-priority work (batch summarisation, backfills, offline judges) before it ever produces a 429. Evals are a classic hidden consumer here — a nightly judged suite sharing a quota with production will degrade production at night unless it has its own key or a lower priority. And propagate the deadline: a retry that cannot finish before the user's deadline is pure waste; don't send it.
Fallbacks deserve suspicion. "If provider A fails, route to provider B" is a quality change disguised as an availability feature. Prompts are not portable: tool-calling formats, system-prompt adherence, refusal behaviour and output-length habits differ across model families, and a prompt tuned for one can lose a meaningful share of quality on another. A fallback that has never been run against the eval suite is an untested deployment that activates only during incidents, when nobody is watching quality. Treat each fallback as a first-class target: its own prompt variant, its own eval gate, a scheduled game-day that routes a slice of real traffic through it, and a UI or response flag when a degraded path answered. The cheapest fallback is often not a different model at all but a degraded mode — retrieval results without synthesis, a cached answer, a queued "we'll email you" — whose quality is known.
Finally, the capacity model itself. Pay-per-token and reserved or self-hosted capacity have a break-even at a utilisation of roughly (reserved cost per hour) ÷ (per-token price × tokens per hour at full use). If that lands at an illustrative 40% and your traffic has a 4:1 diurnal peak-to-trough, capacity sized for the peak averages around 60% utilisation, which looks like a clear win for reserving everything. It isn't, because the decision is marginal: the base-load slice is busy nearly all day and clears break-even easily, but the top slice of capacity — the part that exists only for the peak — is busy a few hours a day, well under 40%, and is cheaper bought per token. The shape most teams converge on is reserved capacity for the base, pay-per-token for the peak and for bursts, and deferrable work (evals, batch enrichment, backfills) scheduled into the trough, where it is effectively free. Evaluate the reserved path's latency under load, not idle: a saturated self-hosted deployment has TTFT that climbs with queue depth, and the per-token math in Serving & Inference Infrastructure assumes batching that only exists when the queue is non-empty.
Where the conventional advice is wrong
Questions to ask in a design review
Step back and the seven chapters are one idea. An AI-native system puts a probabilistic core on the critical path, and your job as an architect is to bound it so the system around it is dependable even though the core isn't. You ground it with retrieval and vector search (the knowledge lane), serve it efficiently (the intelligence lane), orchestrate it — with tools and agents — behind guardrails, and prove and tune it with evals, cost, and latency controls (trust & operations). The model is the commodity. The system you build around it is the architecture — and it's yours.
Evals
Prove quality moved
Trace
See where it broke
Cascade
Biggest cost lever
Bound the core
The whole track
You've finished the track