Introduction

Quality that arrives late or blows the budget never survives contact with production. After contracts, decoding, style, context, tools, validators, and ops are in place, the final lever is performance economics: designing routes to meet latency SLOs and a target $/accepted output without sacrificing acceptance or safety. This article deepens the playbook—budgets as first-class config, sectioned generation with hard stops, claim-pack centric context, caching layers that actually save tokens, small→large routing, and observability wired to business metrics. We’ll move beyond generic “optimize tokens” advice and show where to cut, how to bound p95/p99, and what to measure so tradeoffs are explicit rather than accidental.

A key theme: treat cost and speed as design constraints, not postmortems. That means setting budgets before you write copy, encoding them beside your contract, and failing builds that exceed them. When speed and cost are part of the contract, tuning becomes a methodical search for higher first-pass CPR at lower tokens/accepted—not an endless back-and-forth over wording.


The Problem Cost Engineering Must Solve

Teams that defer performance see the same failure curve. Runaway prompt headers creep from 200 to 600 tokens as rules accrete; context dumps balloon because retrieval isn’t eligibility-first; one-shot longform induces overrun and spiky p95/p99; retry storms appear when validators catch real problems but the system resamples entire artifacts instead of fixing a section. Costs rise linearly with words and quadratically with chaos.

The second class of failures is invisible waste. You regenerate boilerplate on every call; you re-retrieve the same facts instead of caching shaped claim packs; you escalate to a large model “just in case” without a measured win-rate; you run selectors on variants you never use. None of these look like outages, but they erode margins and breach SLOs under load. Cost engineering is the discipline of replacing these habits with explicit budgets, isolation (by section), deterministic stops, and caches with freshness contracts—so both spend and tail latency become predictable.


Design Principles

  1. Budget first, then design inside the box. Write token and latency caps alongside the contract. Features fit budgets; budgets don’t chase features.

  2. Sections over monoliths. Generate per section with caps and stop sequences. This isolates failures, flattens tails, and enables parallel validation.

  3. Optimize CPR × tokens, not vibes. The best policy is the one that increases first-pass constraint pass-rate while reducing tokens/accepted. A 10% token cut that causes 20% more resamples is a net loss.

  4. Cache by meaning, not by page. Cache templates, style/policy bundles, and shaped claims keyed by topic/region/freshness—not raw PDFs.

  5. Default small, escalate when earned. Route to a small model until uncertainty/risk justifies a larger one; measure escalation ROI explicitly.

  6. Log what you optimize. Store artifact hashes, section tokens, stop-hit flags, repair counts, and $/accepted so rollbacks and postmortems trace causes, not symptoms.

These principles shrink the design space: you’ll reach stable, cheap configurations faster because each change is constrained, measurable, and reversible.


Budgets (copy/paste baselines you can enforce)

Token budgets (per request):

Latency SLOs (per route):

Quality gates (release criteria):

Encode these as machine-readable config. CI fails with a clear reason: which budget, by how much, and in which section.


Decoding Policies and Their Cost Impact

Sampling is your throttle. Narrative wants diversity; structure wants discipline. Practical defaults that lower retries:

Tune where errors occur, not globally. If “Proof” fails citations often, lower its top-p/temperature only there; don’t punish “Overview.” Track tokens/accepted by section and resample rate; tighten sections that carry most failures and you’ll see cost drop without style penalties.


Sectioned Generation: Deterministic Latency at Scale

One-shot generation couples everything: a long sentence in “Proof” blows the whole request. Sectioning decouples.

Operational advantages:

Implementation notes: enumerate section IDs/order in the contract; specify caps and stop tokens. Validators enforce the outline to catch accidental spills or missing sections before display.


Caching That Actually Saves Money

Caching random strings helps little; caching stable structure and shaped meaning pays immediately.

  1. Template/Style/Policy cache (config): 100% hit-rate; zero risk. Store by version hash.

  2. Claim-pack cache (context): cache shaped, timestamped claims for hot topics keyed by topic+region+freshness_window. Invalidate on source updates or window expiry. This avoids re-retrieval and cuts context tokens by 30–60% vs raw passages.

  3. Boilerplate generation cache: disclosures, legal footers, standard CTAs generated with low diversity. Store by input hash; never regenerate.

Measure caches by hit-rate × tokens saved and impact on $/accepted. If a cache shows high hits but doesn’t move $/accepted, it’s in the wrong layer (or not trimming enough tokens).


Routing & Model Mix

The cheapest output is the one you don’t escalate. Use a small model (SLM) as default and escalate when justified.

When to escalate:

How to measure:


Throughput Tricks (without breaking quality)

Always monitor p95 and p99 when enabling throughput features; users experience the tail, not the median.


Measurement & Dashboards (production-facing, actionable)

Per route and release, track:

Alerts: CPR −2 pts, p95 +20%, $/accepted +25%, cache hit-rate −15% WoW, or stop-hit ratio −10% in any section.


Optimization Playbook (do in order; stop when metrics flatten)

  1. Trim the header. Replace verbose rules with references (style/policy IDs). Expect 10–20% token savings.

  2. Replace raw context with claim packs. Shape to atomic, dated claims. Expect 20–40% context savings and higher citation pass-rates.

  3. Add section caps + stops. Overrun disappears; p95 typically drops 15–30%.

  4. Tighten decoding on failure-prone sections. Lower top-p/temperature where validators fail; repairs/accepted falls quickly.

  5. Cache claim packs for hot topics. Invalidate by freshness windows; measure tokens saved per request.

  6. Introduce speculative decoding on long sections. Validate that CPR holds; keep an easy off-switch.

  7. Tune routing thresholds. Reduce unnecessary escalations; confirm win-rate delta remains positive.

  8. Prune variants. If your selector’s lift plateaus, cut N; save tokens and time.

Each step should show a monotonic improvement in tokens/accepted, p95, or $/accepted with stable CPR; if not, revert.


Worked Example (composite)

Baseline (blog route): CPR 91.8%, p95 1280 ms, tokens/accepted 1,850, repairs/accepted 0.42, $0.84/accepted.

Interventions:

Canary (10%, stratified):


Implementation Checklist


Conclusion

Cost and speed aren’t mysteries; they are properties you design. By declaring budgets up front, generating by section with hard stops, feeding claims not pages, caching meaningfully, and routing small-by-default, you turn $/accepted output and p95 latency into levers rather than outcomes. The result is a stack that ships quickly, scales smoothly, and remains affordable even as usage grows. Pair these mechanics with the governance from Parts 1–7, and you have a full, auditable operating model for prompt-driven systems that is robust to model changes and real-world load.