Building-block guide · Performance and cost

Cost and latency engineering

How to make agents cheaper and faster without losing quality: token budgets, effort controls, caching, batch, streaming, parallelism, cascades, speculative decoding, the right latency metrics and FinOps unit economics enforced at the gateway.

Draft for review · researched 30 Nov 2026

Contents
  1. At a glance
  2. Scope and where it sits
  3. When to use what
  4. Decision criteria
  5. Reference patterns
  6. Recommended defaults
  7. Anti-patterns
  8. Sizing and cost notes
  9. Security and compliance hooks
  10. Test and eval checklist
  11. Related plan sections and inventory
  12. Unverified or needs review
  13. Sources

At a glance

  • Optimise quality first, then cost and latency, and measure all three against a fixed eval. The KPI is cost per successful task at a fixed pass rate, not cost per token [11]. A cheaper run that fails more often is more expensive.
  • Take the free wins first: prompt caching with a frozen prefix, trimmed tool outputs, capped output length and streaming. These cut cost or perceived latency without changing what the model can do [2][6][9].
  • Set effort deliberately. Effort is a behavioural signal that shapes thinking, text and tool calls, not a hard cap; max_tokens is the hard cap [1]. Default to the model's documented default and step down only with eval evidence.
  • Move anything that can wait 24 hours to a batch API (50% off at three major providers) [3][4][5].
  • Enforce budgets at the gateway, not in prompts: per key, team, user and run, with hard stops for runaway loops and alerts at +25% cost per resolved task (plan section 15) [12].
  • Measure latency as TTFT and time per output token at p50 and p95, plus end-to-end task duration, using the OpenTelemetry GenAI metrics [10].
  • Use cascades and smaller models only behind evals. Research shows large savings (up to 98% in FrugalGPT, more than 2x in RouteLLM) but only for workloads where the cheaper model's failures can be detected [16][17].

Scope and where it sits

This guide covers the levers that change what an agent costs per task and how long users wait: token and turn budgets, effort and thinking controls, batch processing, streaming, parallel tool calls, speculative decoding in self-hosted serving, smaller-model cascades, context trimming, the latency metrics to track, FinOps unit economics and budget enforcement.

In the 10-layer reference architecture (plan section 4) it touches:

Layer Cost and latency responsibility
2 Agent gateway and edge security Budgets, rate limits, spend alerts, kill switch
3 Orchestration Turn limits, effort per step, parallel branches, deadlines
4 Agent runtime and durable execution Total-deadline timers, retries without duplicate spend
5 Model layer and routing Model tier, batch versus online, caching, cascades
6 Context engineering Context budgets, trimming, compaction, cache layout
10 Observability and AgentOps Token and latency metrics, cost attribution, anomaly detection

In the Anatomy of an AI Agent crosswalk this is Metabolism (system 10: FinOps and cost per successful outcome), with Cortex (system 1: model portfolio and routing) and Working memory (system 3: context budgets and caching) supplying most of the levers.

Related guides: Caching covers prompt, semantic and tool caches in depth; Model selection and routing covers model tiers, routers and fallbacks; Prompt assembly and context engineering covers context budgets and compaction; Orchestration and multi-agent covers fan-out costs; Agent runtime and durable execution covers retries and timers; Observability and tracing and Evaluations cover the measurement this guide depends on.

When to use what

Option Use when Avoid when Cost and latency notes
Prompt caching Any agent with a stable prefix reused within minutes Prefix changes every call Reads at 0.1x base input or less; lower time to first token [6][7]
Output caps (max_tokens) and concise output instructions Always Never remove the cap; size it to the task Output tokens dominate generation time [9]
Effort or reasoning level Tuning the cost and quality trade-off per step Changing it per request inside a cached conversation Affects all tokens, including tool calls; not a strict budget [1]
Batch API Evals, backfills, document processing, nightly jobs Anything a user is waiting for 50% off; up to 24 h turnaround [3][4][5]
Streaming Any user-facing response Machine-to-machine steps where the full result is needed Cuts perceived latency; no cost change [2][9]
Parallel tool calls Independent reads (search, lookups) in one step Calls with ordering or side-effect dependencies Fewer round trips; same tokens [8]
Parallel sub-agents or branches Breadth-first research, independent sub-tasks Tightly coupled steps Lower wall-clock time, higher total tokens
Smaller model or cascade High-volume, well-evaluated tasks with detectable failures Novel or high-risk tasks without a good verifier Up to 98% saving in research settings [16]
Speculative decoding (self-hosted) Memory-bound serving at low to medium load High-throughput, compute-bound serving Lower inter-token latency, identical outputs [14][15]
Context trimming and compaction Long-running agents, verbose tool outputs Content still needed for the current step Fewer input tokens; can break the cache if done above the breakpoint
Non-LLM path Deterministic steps (formatting, lookups, validation) Tasks needing judgement Fastest and cheapest call is no call [9]

Notes:

  • Latency and cost often move together (fewer tokens helps both), but parallelism trades cost for latency and batch trades latency for cost. Decide which one the use case is buying.
  • Model choice is the biggest single lever. Prices across models differ by about two orders of magnitude [16]; the plan's rule is to baseline on the most capable model, then step down with evals (see Model selection and routing).

Decision criteria

  1. Is a person waiting? Yes: optimise TTFT and stream. No: use batch for anything that can wait up to 24 hours [3][4][5].
  2. Is the step deterministic? Yes: replace the model call with code, a lookup or a rule [9].
  3. What is the quality bar and how is it measured? No eval, no optimisation. Every change is judged on cost per successful task at a fixed pass rate [11].
  4. Where do the tokens go? Profile input, cached input, output and thinking per step from usage fields before choosing a lever. Uncached input points to caching or trimming; output and thinking point to effort and output caps; many calls point to parallelism or fewer steps.
  5. Can a cheaper model's failures be detected? Yes (a verifier, schema check, test or confidence score): cascade. No: route by task class with eval-backed rules instead.
  6. Is serving self-hosted? Yes: speculative decoding, prefix caching and batching settings are yours to tune [14]. No: use provider levers (caching, batch, effort, priority tiers where offered).
  7. What is the failure cost of a runaway? High: hard per-run token and turn limits plus a total deadline at the gateway and orchestrator, not just per-call timeouts [12][13].
  8. Who pays? Attribute cost to use case, team and tenant at the gateway so budgets can be enforced where the spend decision is made [11][12].

Reference patterns

1. Token budget hierarchy

Problem. Agents loop, retry and fan out. A per-call max_tokens does not stop a 400-call run.

How it works. Budgets nest, and each level has a hard stop and an alert:

Level Budget Enforced by
Call max_tokens, effort level Request parameters [1]
Step or turn Max tool calls per step, max output Orchestrator
Run Max model calls, max tokens, total deadline, max cost Orchestrator and runtime
User, key, team USD budget per period, TPM and RPM limits, max parallel requests Gateway [12]
Use case Monthly budget, cost per resolved task alert at +25% FinOps (plan section 15)

LiteLLM, for example, supports max_budget with budget_duration at global, team, team member, user, key and end-user level, rejects requests once exceeded, and adds TPM, RPM and parallel-request limits [12].

# Illustrative gateway budget (shape based on LiteLLM key settings [12])
key_alias: claims-triage-agent
max_budget: 400          # USD
budget_duration: 30d
tpm_limit: 200000
rpm_limit: 300
max_parallel_requests: 20

When to use. Every agent in production; pilots get looser thresholds but still a hard ceiling [11].

Pitfalls. Budgets that only alert do not stop loops. A per-attempt timeout is not a total deadline: LiteLLM's request_timeout applies per attempt [13], so retries and fallbacks can multiply wall-clock time unless the orchestrator owns a total deadline.

2. Effort and thinking ladder

Problem. Extended reasoning improves hard steps but multiplies output tokens and latency on easy ones.

How it works. Assign effort per step type, not per agent. On Anthropic models, output_config.effort takes low, medium, high, xhigh or max; the default is high on most models and medium on some newer ones; it affects text, tool calls and thinking, and is "a behavioral signal, not a strict token budget" [1]. Keep max_tokens as the hard cap. Typical ladder (practitioner default):

Step type Starting effort
Routing, classification, extraction low
Tool-heavy execution with clear instructions medium
Planning, debugging, multi-constraint reasoning high or above

When to use. Any agent with mixed step difficulty.

Pitfalls. Changing request settings mid-conversation can invalidate parts of the prompt cache on some providers, so set effort per sub-agent or phase and check the provider's invalidation rules [6] (see Caching). Low effort can reduce tool use and quality on tasks that need it; prove each step-down on the eval.

3. Batch lane for anything that can wait

Problem. Evaluations, enrichment and backfills run at online prices.

How it works. Route non-interactive work to batch endpoints. Anthropic: 50% off, up to 100,000 requests or 256 MB per batch, most finish within an hour, results kept 29 days, and batch can be combined with prompt caching (use the 1-hour TTL; hit rates 30% to 98%, best effort) [3]. OpenAI: 50% off, a 24-hour window, 50,000 requests and 200 MB per batch, separate rate limits [4]. Gemini: 50% of standard cost, 24-hour target, context caching supported [5].

When to use. Nightly eval suites, regression runs, document processing, synthetic data generation, back-office classification.

Pitfalls. Anthropic batch is not eligible for zero data retention [3]; check retention rules for regulated data. Bedrock does not support prompt caching with batch inference (see Caching). Batch jobs need idempotent result handling and expiry handling (Anthropic batches expire at 24 hours [3]).

4. Latency budget with streaming and parallelism

Problem. Users judge responsiveness by the first visible output, but agents add tool round trips before any answer.

How it works. Write a latency budget per interaction: gateway and auth, retrieval, each model call (TTFT plus generation), each tool call, guardrails. Then apply OpenAI's seven principles: process tokens faster, generate fewer tokens, use fewer input tokens, make fewer requests, parallelise, make users wait less, and do not default to an LLM [9]. Concretely:

  • Stream user-facing output and show progress during tool calls [2][9].
  • Let the model issue independent tool calls in parallel; return all tool_result blocks in one user message so the model keeps doing so [8].
  • Run guardrail checks in parallel with generation where the risk tier allows, and block before display or action.
  • Pre-warm caches before fan-out (see Caching).

When to use. Every interactive agent.

Pitfalls. Parallel tool calls on side-effecting tools need idempotency and ordering checks. Parallel sub-agents cut wall-clock time but add tokens; budget for it.

5. Verified cascade

Problem. Most requests are easy, but the expensive model handles all of them.

How it works. Try a cheaper model first; accept its answer only if a verifier passes (schema validation, tests, a scorer or a confidence threshold); otherwise escalate. FrugalGPT reports up to 98% cost reduction at equal quality, or 4% higher accuracy at equal cost, on its benchmarks [16]. RouteLLM's learned routers cut cost by more than 2x without quality loss and transferred when the models were swapped [17].

answer = small_model(task)
if verify(answer, task) passes: return answer          # most traffic stops here
answer = large_model(task, context=small_attempt_summary)
return answer

When to use. High-volume tasks with cheap, reliable verification (extraction to schema, code with tests, classification with calibrated scores).

Pitfalls. A weak verifier turns cost savings into silent quality loss. Escalation pays for both calls, so savings depend on the share that stops early. Each model has its own prompt cache [6], so escalation is a cache miss on the larger model.

6. Speculative decoding in self-hosted serving

Problem. Self-hosted models are slow per token at low load because decoding is memory-bound.

How it works. A cheap draft (a smaller model, extra prediction heads, n-grams or suffix matching) proposes several tokens and the target model verifies them in one pass. The original paper reports 2x to 3x faster decoding on T5-XXL with identical outputs [15]. vLLM supports EAGLE, MTP, draft-model, n-gram and suffix decoding methods and positions the feature for medium-to-low QPS, memory-bound workloads [14].

When to use. Latency-sensitive self-hosted endpoints with spare compute.

Pitfalls. vLLM positions it for medium-to-low QPS, memory-bound workloads [14], so gains can shrink under heavy load; benchmark on your own traffic and keep a switch to turn it off.

Setting Default Range or options Why
Primary KPI Cost per successful task at a fixed pass rate Cost per resolution, per document, per case Sourced [11]; plan 4B and 15
max_tokens Sized to the 99th percentile of good outputs for the step Never unlimited Hard cap; effort is not a budget [1]. Sizing is a practitioner default
Effort Model default; step down per step type with evals low to max Sourced [1]
Run limits Max model calls, max tokens, max cost and total deadline per run Set per use case and risk tier Practitioner default; plan 14A
Gateway budgets USD budget per key and team per period, plus TPM, RPM, parallel limits Global to end-user level Sourced [12]
Cost alert +25% cost per resolved task versus baseline Tighter for high-volume use cases Plan section 15
Runaway rate SLO Under 0.5% of runs hit a hard limit Per agent Plan section 15
Batch All non-interactive work Online only when a user or SLA waits Sourced [3][4][5]
Streaming On for all user-facing output Off for machine steps Sourced [2][9]
Parallel tool calls On Disable per tool for ordered or side-effecting calls Sourced [8]
Latency metrics TTFT, time per output token, request duration, task duration at p50 and p95 Add p99 for SLAs Sourced [9][10]
Cascade acceptance Only with a verifier measured on the eval set Rule, classifier or learned router Practitioner default, informed by [16][17]
Tool output size Truncate or summarise tool results above a fixed token budget before they enter context Per tool Practitioner default

Anti-patterns

  • Blanket use of the frontier model for every step. Fix: match model tier to task and switch at session, sub-agent or phase boundaries; Thoughtworks places blanket frontier usage on Caution [18].
  • Optimising cost per token. Fix: measure cost per successful task; a cheaper model with more retries can cost more [11].
  • Effort used as a budget. Fix: keep max_tokens and run limits as hard caps; effort is guidance only [1].
  • Per-call timeouts and no total deadline. Fix: the orchestrator owns a total deadline across retries and fallbacks [13].
  • Budgets that only alert. Fix: hard stops at the gateway for keys, teams and runs [12].
  • Interactive endpoints for offline work. Fix: batch lane for evals and backfills [3][4][5].
  • Dumping full tool outputs into context. Fix: filter, paginate or summarise in the tool; return only what the next step needs.
  • Trimming context above the cache breakpoint. Fix: trim or compact only the appendable tail, or accept a planned cache rewrite.
  • Cascades without verification. Fix: escalate on a measured verifier, and track escalation rate and downstream quality.
  • No cost attribution. Fix: tag every call with use case, team, tenant and run ID at the gateway; export in a FOCUS-aligned format where possible.

Sizing and cost notes

Worked example (illustrative prices and workload). Assume a model priced at $3 per million input tokens and $15 per million output tokens (illustrative, not a quoted price). An agent run makes 12 calls; each sends 20,000 input tokens, of which 16,000 are a stable prefix, and produces 800 output tokens. The pass rate is 80%.

Scenario Input cost Output cost Cost per run Cost per successful task
No caching 240,000 tokens = $0.72 9,600 tokens = $0.144 $0.864 $1.08
Prefix caching (write 1.25x once, reads 0.1x) [6] 48,000 uncached ($0.144) + 37,600 base-equivalent cached ($0.113) $0.144 $0.401 $0.50
Same run in batch (50% off) [3] about $0.20 about $0.25

Two observations. First, caching more than halves the run cost without changing quality. Second, the pass rate matters as much as price: at a 60% pass rate the cached run costs $0.67 per successful task.

Cascade arithmetic (illustrative). If a small model costs $0.04 per task and 70% of tasks pass its verifier, the expected cost is $0.04 plus 30% of $0.40 = $0.16, about 60% below the cached large-model run, provided the end-to-end pass rate holds.

Token variance. The plan's sizing research cites up to 30x variation in token use for the same task across implementations; FinOps guidance is to report outcome cost as a range rather than a point [11].

FinOps metrics. The FinOps Foundation lists cost per successful outcome (worked example $1,200 / 8,000 = $0.15), cost per inference, cost per million tokens, cache hit rate (example 60%), model fit (example 20%) and anomaly cost (example 3%), and names agent loops as an anomaly to watch [11]. Its guidance is to "measure the use case, not the token".

Latency. OpenAI's guide gives no fixed token-to-latency ratio; measure on your own traffic [9]. Anthropic recommends measuring baseline latency and TTFT and choosing the model, shortening prompts and outputs and streaming as the main levers [2].

Security and compliance hooks

Threat OWASP mapping Controls
Runaway loops, denial of wallet, resource exhaustion LLM10 Unbounded Consumption [19]; ASI08 Cascading Failures [20] Nested budgets, hard stops, total deadlines, anomaly alerts, kill switch
Prompt injection that triggers expensive fan-out or tool storms LLM01 Prompt Injection; ASI01 Goal Hijack; ASI02 Tool Misuse [19][20] Per-run tool-call limits, parallelism caps, approval for high-cost actions
Cost-driven downgrades that weaken safety LLM09 Misinformation [19] Guardrails and evals run on every model tier and effort level; no bypass for cheap paths
Batch data retention exposure LLM02 Sensitive Information Disclosure [19] Check ZDR and retention per batch endpoint; Anthropic batch is not ZDR eligible [3]
Budget bypass through unmanaged keys ASI03 Identity and Privilege Abuse [20] All traffic through the gateway; provider keys held only by the gateway

Data protection. Cost telemetry should carry IDs, not prompt content. Keep prompts out of cost exports unless the observability policy allows it.

Audit evidence to keep. Budget configuration per key and team, budget-exceeded and kill-switch events, cost per successful task reports per release, eval results for every cost-driven change, and anomaly investigations.

Governing plan sections. 10 (threat model for denial of wallet), 10A (agent identity used to attribute spend), 10B (policy can require approval for high-cost actions), 11 (retention constraints on batch and logging), 13 (registry records budgets and risk tier), 14 and 14A (autonomy levels set run limits), 15 (FinOps SLOs and alerts) and the ROE (to be defined, plan section 12), which may set cost or latency bounds for regulated outcomes.

Test and eval checklist

ID Stage Check Pass criteria Priority
COST-01 Design Unit of value and KPI defined Cost per successful task, pass rate and latency SLO agreed Must
COST-02 Design Latency budget per interaction written Budget covers gateway, retrieval, model, tools and guardrails Should
COST-03 Design Batch-eligible work identified Every non-interactive job mapped to batch or justified Should
COST-04 Build Every call tagged with use case, team, tenant, run ID 100% of gateway calls attributed Must
COST-05 Build max_tokens set on every call No unbounded calls in code scan Must
COST-06 Build Run limits implemented Max calls, tokens, cost and total deadline enforced in orchestrator Must
COST-07 Build Gateway budgets configured Budget, TPM, RPM and parallel limits per key and team Must
COST-08 Test Token profile captured Input, cached input, output and thinking per step recorded on eval set Must
COST-09 Test Cache hit rate on replay At or above target for stable-prefix agents Should
COST-10 Test Effort step-downs proven Pass rate within agreed tolerance at lower effort Must
COST-11 Test Cascade verifier accuracy False-accept rate within tolerance on labelled set Must
COST-12 Test Runaway simulation Injected loop stops at hard limit; alert fires Must
COST-13 Test Budget exceeded behaviour Request rejected with clear error; user sees graceful message Must
COST-14 Test Load test at peak p95 TTFT and task duration within SLO; no rate-limit cascade Must
COST-15 Test Parallel tool calls safe Side-effecting tools excluded or idempotent Should
COST-16 Test Speculative decoding benchmark (self-hosted) Latency gain at target load with identical outputs Could
COST-17 Release Cost and quality report per release Cost per successful task and pass rate versus baseline signed off Must
COST-18 Release Batch retention checked Batch endpoints meet data retention rules for the data class Should
COST-19 Run Dashboards for cost and latency Cost per successful task, TTFT, TPOT, cache hit rate per agent Must
COST-20 Run Anomaly alerts Alert at +25% cost per resolved task and on token-per-minute spikes Must
COST-21 Run Monthly FinOps review Top agents by spend reviewed; actions logged Should

Governing policies and procedures

From the CoE policy set (draft; control IDs on the policy crosswalk):

Unverified or needs review

  • The OpenTelemetry GenAI metrics are in Development status and may change name or shape [10].
  • The effort parameter's levels and defaults are Anthropic-specific; other providers use different names (for example reasoning effort) and semantics. Check per model in the approved list [1].
  • Whether OpenAI's batch discount stacks with prompt caching discounts was not confirmed on the pages read.
  • The 30x token-variance figure comes from the plan's sizing research (McKinsey) and was not re-checked for this guide.
  • Prices in the worked example are illustrative; replace them with contracted prices before using the numbers in a business case.
  • Whether changing effort or thinking settings mid-conversation invalidates the prompt cache was not confirmed for every provider; this guide recommends changing them only at phase boundaries as a precaution.
  • The +25% alert and the 0.5% runaway SLO come from plan section 15; the CoE lead to confirm they apply to all risk tiers.

Sources

  1. Effort, Anthropic (Claude Platform docs), https://platform.claude.com/docs/en/build-with-claude/effort, accessed 30 Nov 2026.
  2. Reducing latency, Anthropic (Claude Platform docs), https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/reduce-latency, accessed 30 Nov 2026.
  3. Batch processing, Anthropic (Claude Platform docs), https://platform.claude.com/docs/en/build-with-claude/batch-processing, accessed 30 Nov 2026.
  4. Batch API, OpenAI API docs, https://developers.openai.com/api/docs/guides/batch, accessed 30 Nov 2026.
  5. Batch API, Google Gemini API docs, https://ai.google.dev/gemini-api/docs/batch-api, accessed 30 Nov 2026.
  6. Prompt caching, Anthropic (Claude Platform docs), https://platform.claude.com/docs/en/build-with-claude/prompt-caching, accessed 30 Nov 2026.
  7. Prompt caching, OpenAI API docs, https://developers.openai.com/api/docs/guides/prompt-caching, accessed 30 Nov 2026.
  8. Parallel tool use, Anthropic (Claude Platform docs), https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use, accessed 30 Nov 2026.
  9. Latency optimization, OpenAI API docs, https://developers.openai.com/api/docs/guides/latency-optimization, accessed 30 Nov 2026.
  10. Semantic conventions for generative AI metrics, OpenTelemetry, https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-metrics.md, accessed 30 Nov 2026.
  11. FinOps for AI Overview, FinOps Foundation, https://www.finops.org/wg/finops-for-ai-overview/, accessed 30 Nov 2026.
  12. Budgets and rate limits (users, teams, keys), LiteLLM docs, https://docs.litellm.ai/docs/proxy/users, accessed 30 Nov 2026.
  13. Fallbacks, retries, timeouts and cooldowns, LiteLLM docs, https://docs.litellm.ai/docs/proxy/reliability, accessed 30 Nov 2026.
  14. Speculative decoding, vLLM project, https://github.com/vllm-project/vllm/blob/main/docs/features/speculative_decoding/README.md, accessed 30 Nov 2026.
  15. Fast Inference from Transformers via Speculative Decoding, Leviathan, Kalman and Matias, arXiv 2211.17192, https://arxiv.org/abs/2211.17192, accessed 30 Nov 2026.
  16. FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance, Chen, Zaharia and Zou, arXiv 2305.05176, https://arxiv.org/abs/2305.05176, accessed 30 Nov 2026.
  17. RouteLLM: Learning to Route LLMs with Preference Data, Ong et al., arXiv 2406.18665, https://arxiv.org/abs/2406.18665, accessed 30 Nov 2026.
  18. Blanket frontier model usage, Thoughtworks Technology Radar, https://www.thoughtworks.com/radar/techniques/blanket-frontier-model-usage, accessed 30 Nov 2026.
  19. OWASP Top 10 for LLM Applications 2025, OWASP GenAI Security Project, https://genai.owasp.org/llm-top-10/, accessed 30 Nov 2026.
  20. OWASP Top 10 for Agentic Applications, OWASP GenAI Security Project, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications/, accessed 30 Nov 2026.
↑