Cost and Latency Optimization at Scale
Cost modeling by cost per task, routing and cascades across the Claude model family, prompt caching strategy and diagnostics, batch versus realtime, per-tenant budgets, and latency engineering (TTFT, TTLT, streaming, effort).
- Cost Architecture at Scale: cost modeling and forecasting, model routing and cascades, caching strategy, batch vs realtime, per-tenant budgets
- Latency Engineering: time-to-first-token vs total latency, streaming, parallel tool execution, cache checkpointing, effort tuning
Domain overview
Domain 6 "Cost and Latency Optimization at Scale" accounts for 8% (about 5 of the 60 scored items). The Exam Guide splits the domain into two skill areas:
- Cost architecture: cost modeling and forecasting at fleet scale, routing and cascades across the Claude model family, caching strategy and cache diagnostics, batch-versus-realtime economics, and per-tenant budgets.
- Latency engineering: distinguishing time-to-first-token (TTFT) from total latency, then applying streaming, parallel tool execution, cache checkpointing, and effort-level tuning.
Items typically present a usage table, prices, or p50/p90 measurements and ask which lever is correct. The guiding principle: evals and a quality bar first, optimization second; a cheaper or faster configuration that falls below the quality bar is not a candidate.
Cost modeling and forecasting
The unit of measure is cost per completed task
Compare models on cost per completed task, not price per token, "because you pay for completed tasks". A failed task still consumes tokens, plus retries and downstream costs. You also need to price the tail: in one WideSearch run of 20 tasks, 2 tasks accounted for 43% of the cost.
Each request has five token types at five prices: uncached input, 5-minute cache write (1.25× the input price), 1-hour cache write (2×), cache read, and output. Read them from usage:
total_input = cache_read_input_tokens + cache_creation_input_tokens + input_tokens
cost = Σ (tokens of each type × price of each type)
cache_hit_rate = cache_read_input_tokens / total_input
input_tokens is only the portion after the last breakpoint. With the advisor tool or compaction, also check usage.iterations.
Exam trap
Do not estimate tokens from character counts or from older models. The same text costs about 30% more tokens on newer models (Claude 4.7 onward; the evals course notes this for Claude Sonnet 5 and Claude Opus 5). Always read the actual usage block.
Why agent loops get quadratically expensive
Each agent turn resends the entire, growing conversation. A 40-turn task sends the first turn 40 times, so without caching, cost grows roughly with the square of the number of turns. That is why prompt caching is the first lever. The order of levers in the cost optimization cookbook is:
- Baseline eval.
- Prompt caching.
- Cut input tokens.
- Agent loop efficiency.
- Cut output tokens.
- Batch API.
- Only then, model and effort selection.
Worked example: Meridian
A Claude Sonnet 5 call with 780 input tokens × $2/MTok = $0.0016, plus 41 output tokens × $10/MTok = $0.0004, totals $0.0020. Cost per completed task = cost of the whole run ÷ number of completed tasks:
| Model | Tasks passed / 50 | Run cost | Cost per completed task |
|---|---|---|---|
| Claude Haiku 4.5 | 42 (84%) | $0.0380 | $0.0009 |
| Claude Sonnet 5 | 50 | $0.0984 | $0.0020 |
| Claude Opus 5 | 50 | $0.2323 | $0.0046 |
With a 90% accuracy floor, Haiku 4.5 is not a candidate even though it is cheapest, so choose Sonnet 5, the cheapest model that clears the floor. A fleet-level forecast is cost per task × volume: for Acme, "At a million claims a year, every cent off cost per task will save us ~$10K". Do not mix batch prices with standard prices in the same comparison.
Routing and cascades across the Claude model family
Choosing model tier and effort
The current family, from lowest to highest: Claude Haiku 5.5, Claude Sonnet 5.5, Claude Opus 5.5, Claude Fable 5.2 (frontier). For most agent workloads, start with Claude Opus 5.5 at the default effort (medium), and tune effort before changing models.
| Configuration (SWE-bench Pro subset) | Solve rate | Cost per solved task |
|---|---|---|
Sonnet 5.5 high (default) |
87.6% | $0.11 |
Opus 5.5 low |
87.4% | $0.12 |
Opus 5.5 medium (default) |
92.8% | $0.22 |
Fable 5.1 high |
92.3% | $1.19 |
- Opus 5.5 tokens cost twice as much as Sonnet 5.5 tokens, but at
lowOpus 5.5 solves about as many tasks as Sonnet 5.5 at only slightly higher cost. - Upgrade the model version before optimizing anything else: Opus 5 → Opus 5.5 is 78% cheaper per solved task.
- The default effort is
highon most models, andmediumon Opus 5.5 and Haiku 5.5. Claude Haiku 4.5 does not accept the effort parameter.
Cascades: run cheap first, rerun the failures
When the outcome is verifiable (tests, a verifier), the cheapest policy is to run every task at a low setting and rerun only the failed tasks at a high setting. On Opus 5.5:
low, then rerun the failures athigh: about 97% of tasks solved, about $0.17.- Run everything at
high: 95.3%, $0.29.
The tradeoff is that you need a failure signal and accept extra latency on the tasks that must be rerun.
Multi-model: advisor, orchestrator, subagents
- Advisor tool: a cheap model drives and consults Opus when needed. Cost is about 2.1× with a 1.7-point gain on coding. It works best when there is a cheap gating signal, such as a payout threshold or a fraud band.
- Orchestrator: Opus 5.5 coordinates Sonnet 5.5 subagents. This is about one third cheaper for workloads larger than one context window.
- Routing to cheap subagents: in the cookbook, splitting the work across 5 Haiku subagents plus Sonnet was about 90% cheaper but missed one claim because an exception in a rule was lost. Routing must always go through evals, and a multi-model configuration must beat the whole tier × effort curve, not just a single point. Before fully switching, run it in shadow on a slice of traffic.
Exam trap
"Switch to a cheaper model mid-session" sounds economical but is often more expensive. The cache is model-specific, so switching models means rewriting the entire prefix. Switch models through a subagent handoff, or at compaction time, when you take a cache miss anyway.
Prompt caching strategy and cache diagnostics
Mechanics you need to know
- Byte-exact prefix match in the order
tools→system→messages. - Breakpoints: up to 4
cache_controlpoints. Automatic caching setscache_controlat the top level and uses one sliding breakpoint. - Writes and reads: the cache is written only at a breakpoint, while a read looks back at most 20 blocks.
- Minimum length: 512 tokens for Opus 5.5, Sonnet 5.5, and Haiku 5.5; 4,096 for Haiku 4.5. Below this length caching does not raise an error, it simply does not write: both
cache_creation_input_tokensandcache_read_input_tokensare 0. - TTL: 5 minutes by default, refreshed for free on every read;
{"type": "ephemeral", "ttl": "1h"}is available as an option.
| Model | Input | 5-minute write | 1-hour write | Cache read | Output |
|---|---|---|---|---|---|
| Claude Opus 5.5 | $4 | $5 | $8 | $0.20 | $20 |
| Claude Sonnet 5.5 | $2 | $2.50 | $4 | $0.10 | $10 |
| Claude Haiku 5.5 (≤100K) | $0.10 | $0.125 | $0.20 | $0.01 | $0.50 |
(Prices per MTok. Cache reads on Opus 5.5 and Sonnet 5.5 are 0.05× the input price, below the general 0.1× rate. On Haiku 5.5, once a prompt exceeds 100,000 tokens every token costs 5× as much, so compact before that threshold.)
Scenario example
A 100,000-token prefix on Claude Opus 5.5. Each uncached request costs $0.40 for the prefix. A 5-minute cache write costs $0.50 once, and each later read costs $0.02. For 10 requests within the TTL: no caching costs $4.00; caching costs $0.50 + 9 × $0.02 = $0.68. If you switch to a 1-hour TTL mid-conversation, the whole prompt is rewritten at $0.80 instead of $0.02 for a read. So choose the TTL at the start of the conversation.
Choosing the TTL
- Calls a few seconds apart: use the default 5 minutes, about 19% cheaper than 1 hour on Sonnet 5.5.
- About 1 in 20 gaps falls in the 5-minute to 1-hour range: use 1 hour. Break-even is about 1 in 30; at 1 in 10, 5 minutes is 54% more expensive.
- Gaps over 1 hour are common: the 1-hour cache expires too, so keep 5 minutes.
- An alternative is a keep-alive with
max_tokens: 0, sent within 4 minutes of the start of the previous request.
What breaks the cache
| Change | Cache invalidated | How to keep the cache |
|---|---|---|
| Adding, removing, or editing a tool definition | Everything | Define all tools up front; use defer_loading stubs or tool search |
| Timestamp or status line at the top of the system prompt | Everything after it | Put changing text at the end of the latest user turn |
| Editing the system prompt mid-session | system + messages | Use a mid-conversation system message (editing the system prompt is 25–50× more expensive) |
Changing top-level effort or thinking configuration |
Messages cache lost (thinking: always; effort: possibly); depending on the model, system and tools too | Use per-message effort (changing the top level is 20–40× more expensive) |
Toggling speed: "fast" on or off |
system + messages | Do not change speed mid-session |
| Changing models | Everything, because the cache is model-specific | Subagent handoff, or switch at compaction |
tool_choice, images |
messages | Keep stable within the session |
If you must make a change, do it at a natural stopping point, such as the first request after compaction.
Diagnostics
- A good hit rate: real-world agent loops read a median of 84% of input from cache, and the top 10% reach ≥94%. Below about 80%, look for what is breaking the cache.
- Cache diagnostics: the API compares consecutive requests and reports where the prefixes start to differ.
- Parallel requests: a cache entry is usable only after the first response begins, so send one request first and then the rest.
- Monitoring: "Monitor your cache hit rate like you monitor uptime". The Claude Code team alerts on hit rate and declares a SEV when it drops.
- Rate limits: cache reads do not count toward ITPM. With a 2,000,000 ITPM limit and an 80% hit rate, you can process about 10,000,000 input tokens per minute.
Key point
When the cache hit rate is low, read usage request by request. A large cache_creation_input_tokens on every request means the prefix keeps changing. Both fields at 0 means the prompt is below the minimum length or no breakpoint is set.
Batch versus realtime
| Criterion | Messages API (realtime) | Message Batches API |
|---|---|---|
| Price | Standard price | 50% off all usage, stacks with caching |
| Timing | Synchronous | Most finish in under 1 hour; expires after 24 hours (a deadline, not an SLA) |
| Scale | Bound by rate limits | ≤100,000 requests or 256 MB per batch; does not consume Messages API rate limits |
| Not supported | — | stream, speed (fast mode), fallbacks, max_tokens: 0 |
| Caching | Stable | Best-effort, 30%–98% hit rate; use identical cache_control and consider a 1-hour TTL |
| Agents | Client-side tool loops run normally | Client-side tool loops cannot run, so each request is a single turn; server tools still loop on their own |
Use batches for eval suites, backfills, and nightly processing, that is, work that can wait. Use custom_id to match results, because ordering is not guaranteed.
Exam trap
"Move the chat agent to batch to save 50%" is wrong when users are waiting, or when the agent needs a client-side tool loop. Batches also cannot be combined with fast mode.
Per-tenant budgets
- One workspace per tenant or tenant group. Each workspace has its own spend limit and rate limits (RPM, ITPM, OTPM), which can be set through the Rate Limits API. Organization-wide limits always apply. You cannot set a spend limit on the default workspace.
- Distinguish three different errors:
- Hitting a self-set spend limit: HTTP 400
invalid_request_error, message "You have reached your specified workspace API usage limits". - Hitting the organization spend cap: 429
rate_limit_errorwitherror_code: enforced_spend_limit_reachedand noretry-after. Retrying is pointless. - An ordinary rate limit: 429 with
retry-after.
- Hitting a self-set spend limit: HTTP 400
- Per-task ceilings: the Claude Managed Agents session budget (
stop_reason: budget_reached),max_tokensas a backstop the model cannot see, and a task budget as a signal the model uses to pace itself. - Measure per tenant: attribute each request's
usageto its tenant to compute cost per task. Batches can slightly exceed a workspace spend limit.
Key point
A workspace spend limit is a backstop, not an optimization tool. It caps losses; cost per task must be reduced through caching, token cuts, and model/effort selection.
Latency engineering
TTFT, TTLT, OTPS
- TTFT: time to first token.
- TTLT: time to last token.
- OTPS: output tokens per second.
From the latency cookbook:
TTLT ≈ calls × TTFT + output tokens ÷ OTPS + additional client/server overhead
Choose the metric by product. A phone line optimizes p90 TTFT (baseline 0.70 s), while a chat agent optimizes p50 TTLT (baseline 6.1 s).
Levers and measurements from the sources
| Lever | Affects | Evidence in the sources |
|---|---|---|
| Shrinking the prompt | TTFT | 17K → 200K tokens adds about 0.5 s, i.e., about 0.25 s per 100K |
| Caching | Mostly cost | Short prompt: −85% cost ($0.25 → $0.04), latency barely changes; long prompts gain more on TTFT |
Pre-warm (max_tokens: 0) |
First-request TTFT | 1.0 → 0.8 s with a 146K-token prompt |
| Parallel subagents (Haiku 5.5) | Turns × TTFT | 9.5 → 5.7 s; lookup turns 6.8 → 1.5 s |
| Prefetching always-needed data | Number of turns | p50 −13% |
| Programmatic tool calling | Output tokens, number of turns | Saves about 11 s |
| Asking for short answers | Output ÷ OTPS | 46.4 → 4.9 s; thinking about 2,100 → 300 tokens |
Effort low (Opus 5.5) |
Thinking, output | p50 −13%; at high, p50 +7%, p90 +12% |
Fast mode (speed: "fast") |
OTPS | Up to 2.5× OTPS at 2× the price; the gain is mainly in OTPS, not TTFT |
A fast model does not guarantee a fast task. Haiku 5.5 writes 581 tokens/s, Sonnet 5.5 236, Opus 5.5 153. But Haiku writes more tokens to reach the same result. For the same N output tokens, writing time is in the ratio N/581 : N/236 : N/153.
Streaming, parallel tools, and cache checkpointing
- Streaming reduces perceived latency. With tool use, the loop can run each tool as soon as its tool call finishes streaming, without waiting for the whole response; fine-grained tool streaming is earlier still. Thinking with
display: "summarized"puts text on screen 22.1 s sooner. - Parallel tools: independent steps run at the same time, so the task waits only for the slowest step.
- Cache checkpointing in long agent loops: place breakpoints on the system prompt, the first user turn, and the latest user turn. Run background compaction instead of threshold-based compaction: the longest wait drops to 4.9 s instead of 21.4 s.
- Limits:
max_tokensis a hard stop the model cannot see (stop_reason: "max_tokens"). Combine it with signals the model can see (a task budget, an elapsed-time clock) so the model can wrap up cleanly. - Platform and region: latency also depends on whether you call the API directly or through a cloud platform, and on the region.
Scenario example
A voicebot has a p90 TTFT of 0.70 s and must get below 0.65 s while keeping a 95% quality bar. The prompt is 146K tokens and traffic arrives in bursts. Priorities: pre-warm the cache at startup or on a timer within the cache lifetime, using the same model, thinking, and effort as real requests. Next, cut unneeded prompt content (about 0.25 s per 100K tokens), and consider effort low and fast mode, then re-measure at p90. Switching to a model with higher OTPS does little for TTFT, because OTPS mainly determines TTLT.
Key point
Fix the loop before changing the model: fewer turns, parallelism, prefetching, shorter output. Most of the time is spent on output. A faster configuration is only eligible if it still meets the quality bar.
(Sources: CCDV-P Exam Guide, Domain 6; Claude Cookbooks: Cost Optimization on the Claude API; Claude Cookbooks: Latency Optimization on the Claude API; Claude Docs: Optimizing for cost and intelligence; Claude Docs: Prompt caching; Claude Docs: Batch processing; Claude Docs: Rate limits; Claude Docs: Streaming messages; Claude Blog: Lessons from building Claude Code: Prompt caching is everything; Anthropic Academy: Introduction to evals — When to use what model)
Quick summary
- Compare models and configurations on cost per completed task; failed tasks are still billed, and price the tail.
- Five token prices: input, 5-minute write (1.25×), 1-hour write (2×), cache read, output; total input = read + creation +
input_tokens. - Without caching, agent loop cost grows roughly with the square of the number of turns, so enable caching first.
- Start with Opus 5.5 at the default effort, tune effort before changing models; cascade: run at
low, rerun failures athigh. - The cache matches a byte-exact prefix (tools → system → messages); writes happen only at breakpoints; reads look back 20 blocks; below the minimum length, caching silently does nothing.
- Cache breakers: tool definitions, dynamic text at the top of the prompt, changing models, changing top-level effort/thinking/
speed. - Median hit rate is 84%; below about 80%, find the break using
usageand cache diagnostics. - Use a 1-hour TTL when about 1 in 20 gaps falls between 5 minutes and 1 hour; choose the TTL at the start of the conversation.
- Batch: 50% off, 24-hour deadline, stacks with caching; no
stream,speed, or client-side tool loops. - The organization spend cap returns 429
enforced_spend_limit_reachedwith noretry-after; a self-set spend limit returns 400. - TTLT ≈ calls × TTFT + output ÷ OTPS; voice optimizes p90 TTFT, chat optimizes p50 TTLT.
- Pre-warming with
max_tokens: 0lowers first-request TTFT; fast mode raises OTPS (up to 2.5×, at 2× the price); shorter output cuts TTLT sharply.