Claude Certified Developer · Professional
Module 8: Cost and latency at scale
Study notes written by Sanjay Shah. Not official Anthropic material. Facts marked "check before relying on it" may have changed.
On this page
Study notes, not official course material. Our take on official course 8 (cut cost and latency at fleet scale without losing quality). Facts checked 2026-11-25.
The video opens on a system prompt whose first line is Current time: 2026-11-25T02:14:07Z, next to a cache-hit gauge stuck at 0%. That one line made every request pay full price for a prompt that was otherwise identical every time. This module is about finding money and seconds like that, and proving you didn't pay for them with quality. The rule for the whole module: every optimisation reports cost, latency and quality together, or it doesn't count.
No prices appear here, only multipliers relative to a model's base input price. For the actual numbers, see the current pricing page.
What you'll be able to do
Measure cost per unit of work (per resolved ticket, not per request) and p50/p95 latency, split by tenant and prompt version.
Explain how the prompt cache matches prefixes, lay out a prompt so stable content comes first, and find the silent invalidators that keep the hit rate at zero.
Read the
usagefields correctly and work out when caching pays for itself, and which TTL to use.Pick an effort level and a model per route, and route by ticket category only where evals show quality holds.
Move work nobody is waiting for to the Message Batches API, and know what it can't do.
Set a context budget (top-k, thread length, tool-output size) and measure it with token counting.
Make answers feel faster with streaming, parallel tool calls and early retrieval.
1. Start from unit economics, not from the bill
A monthly bill tells you that you spent money, not where. Before changing anything, get a baseline from the Module 3 dashboard:
| Metric | Why it matters |
|---|---|
| Cost per resolved ticket | The unit the business cares about. A cheap request that needs three retries or an escalation isn't cheap. |
| Time to first token (TTFT) | What the user feels in a streaming chat widget. |
| p50 and p95 time to done | p50 is the typical wait; p95 is the angry customer. |
| Cache hit rate | Read tokens as a share of all input tokens. It's the single biggest lever in most apps. |
| Quality score | From the Module 4 eval suite. Without it, "cheaper" might just mean "worse". |
Split each of these by tenant and prompt version. Cedar's long, multi-turn tickets and alpine's one-line password resets have very different economics, and an average hides both.
Judge cost per completed task, not cost per request. A route that's 40% cheaper per call but escalates twice as often to a person, or needs a second turn to finish, can cost more in the end.
2. How the prompt cache works
Prompt caching is a prefix match. The API renders your request in a fixed order, tools → system → messages, and caches the exact bytes up to each breakpoint you mark with cache_control. A later request that starts with the same bytes reads those tokens from the cache instead of processing them again.
The one invariant everything follows from: any change to a byte in the prefix invalidates everything after it.
┌──────────────────────────────┐
│ tools (sorted, fixed) │ never changes
├──────────────────────────────┤
│ system prompt (frozen) │ never changes ◄─ breakpoint 1
├──────────────────────────────┤
│ tenant policy summary │ changes per tenant ◄─ breakpoint 2
├──────────────────────────────┤
│ conversation so far │ grows each turn ◄─ automatic (moves forward)
╞══════════════════════════════╡ ← cache line: nothing volatile above here
│ retrieved chunks, time, │ changes every request
│ the new question │
└──────────────────────────────┘Now the bug from the video. The broken prompt builder started the system prompt with the time:
// BROKEN: the first bytes change every second, so nothing after them can ever match
const system = `Current time: ${new Date().toISOString()}\n\n${SYSTEM_PROMPT}`;Because the timestamp sits at the very top, every request's prefix is different from its first line. The cache_control markers further down are still there, they just never find a match. There is no error; requests succeed and the bill is higher.
Silent invalidators to grep for
| Pattern in code that feeds the prefix | Why it breaks caching |
|---|---|
Date.now(), new Date() in the system prompt | Prefix changes on every request |
crypto.randomUUID() or a request id near the top | Same: every request is unique |
JSON.stringify(obj) where obj is built in varying key order | Same data, different bytes. JSON.stringify keeps insertion order. |
| The user's name or session id interpolated into the system prompt | One prefix per user; nothing is shared |
if (flag) system += ... | Every combination of flags is a separate prefix |
| A tool list built per user or per tenant | Tools render first, so nothing caches across users |
Fix each one by moving the dynamic part after the last breakpoint, making it deterministic (sort keys, sort tools by name), or deleting it if nothing needs it.
3. A cache-friendly request for the course app
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
// Built once at startup. Sorted so the bytes are identical on every request.
const TOOLS: Anthropic.Tool[] = [searchDocs, getOrder, issueRefund, escalate]
.sort((a, b) => a.name.localeCompare(b.name));
const SYSTEM_PROMPT = "..."; // frozen: no dates, no ids, no per-user text
export function buildRequest(
tenantPolicy: string, // stable per tenant
history: Anthropic.MessageParam[], // the conversation so far
chunks: Anthropic.DocumentBlockParam[],// retrieved for this question
question: string,
): Anthropic.MessageCreateParamsNonStreaming {
return {
model: "claude-opus-5-5",
max_tokens: 16000,
cache_control: { type: "ephemeral" }, // automatic breakpoint for the growing conversation
tools: TOOLS,
system: [
{ type: "text", text: SYSTEM_PROMPT, cache_control: { type: "ephemeral" } }, // shared by all tenants
{ type: "text", text: tenantPolicy, cache_control: { type: "ephemeral" } }, // shared within a tenant
],
messages: [
...history,
{
role: "user",
content: [
...chunks,
{ type: "text", text: `Current time: ${new Date().toISOString()}\n\n${question}` },
],
},
],
};
}What each piece does:
Breakpoint 1 on the frozen system prompt caches tools + system together. All three tenants share it.
Breakpoint 2 on the tenant policy caches up to the end of that tenant's block. All of alpine's tickets share it.
Top-level
cache_controlis automatic caching: the API puts a breakpoint on the last cacheable block and moves it forward as the conversation grows. In an agent loop, where the same ticket comes back to the API after every tool call, this is where most of the reads come from.The time moved to the end. It's still there for the model, but below the cache line.
That's three of the four breakpoints a request may have. Leave one spare.
Automatic or explicit?
Automatic caching alone is the right default for plain multi-turn chat. It's the wrong tool when the prompt ends in content that's unique to this request and won't be sent again, such as a one-off question with its own retrieved rows. The automatic breakpoint then lands after the unique tail, so you pay the write premium on bytes nobody reads back. The signature is cache_creation_input_tokens on every request while cache_read_input_tokens never covers the shared part. The fix: an explicit breakpoint at the end of the shared part, as with the two system blocks above. For agent loops, one explicit breakpoint on the static prefix plus automatic caching for the tail is the robust combination.
Prompts that are too short
Each model has a minimum cacheable prefix length. Shorter prefixes silently don't cache: no error, just cache_creation_input_tokens: 0. The minimum isn't the same across model generations (on 2026-11-25 the docs listed 512 tokens for the newest models, including claude-opus-5-5, and up to 4,096 for some older ones). If a small prompt shows zero writes, check the minimum before blaming the code.
4. Proving it works: the usage fields
Every response tells you what happened:
| Field | Meaning | Relative price (5-minute TTL) |
|---|---|---|
cache_creation_input_tokens | Written to the cache this request | 1.25× base input |
cache_read_input_tokens | Served from the cache | ~0.1× base input on most models; 0.05× on Claude Opus 5.5 and Claude Sonnet 5.5 |
input_tokens | Processed at full price | 1× |
A classic misreading: input_tokens is only the uncached remainder. Total prompt size is input_tokens + cache_creation_input_tokens + cache_read_input_tokens. If an agent ran for an hour and input_tokens says 4,000, most of the prompt came from the cache. Check the sum, not the single field.
A small helper for the dashboard:
// Input cost in "base input token" units. Multiply by the base price from the pricing page.
export function inputUnits(u: Anthropic.Usage, readMultiplier = 0.05 /* claude-opus-5-5 */) {
const created = u.cache_creation_input_tokens ?? 0; // assumes the 5-minute TTL (1.25x)
const read = u.cache_read_input_tokens ?? 0;
const total = u.input_tokens + created + read;
return {
units: u.input_tokens + 1.25 * created + readMultiplier * read,
hitRate: total ? read / total : 0,
};
}If you use the 1-hour TTL, usage.cache_creation splits writes by TTL so you can price them correctly (2× for 1 hour).
Make it a standing check, not a one-time look. The costliest caching failure is a regression: caching works when written, then months later someone adds a field to the system prompt and every request misses. Add an integration test that sends the same request twice and asserts that the second one has cache_read_input_tokens > 0, and put the hit rate on the dashboard with an alert.
When caching pays, and which TTL
Break-even with the 5-minute TTL: two requests. One write (1.25×) plus one read (~0.1×) is about 1.35×, against 2× uncached.
Break-even with the 1-hour TTL: three requests. The write costs 2×, so 2× + 0.1× + 0.1× = 2.2× against 3×.
A read refreshes the timer, at no extra cost. Requests sharing a prefix that start less than 5 minutes apart keep the 5-minute entry warm forever.
| Gap between requests that share the prefix | TTL |
|---|---|
| Under 5 minutes (busy tenant, agent loops) | 5 minutes: every request refreshes it, and writes are cheaper |
| 5–60 minutes (a customer who replies after 20 minutes) | 1 hour: the only case where the 2× write pays off |
| Over an hour | Neither helps much. Re-warm on a schedule, or accept the miss. |
Failure cases worth knowing
Fan-out in parallel. A nightly report sends ten requests with the same large prefix at the same moment. All ten pay full price, because a cache entry becomes readable only once the first response begins streaming. Send one, wait for its first token, then send the other nine.
Traffic split across workspaces. On the Claude API, caches are isolated per workspace. If alpine's traffic runs under two workspaces' API keys, the same prompt writes two separate cache entries. Check this before blaming the prompt.
A model switch. Caches are per model. Switching models mid-conversation means starting cold. That matters for routing (section 6).
A cold first request after deploy. The first real request pays the write and the slower prefill. To avoid that for a user-facing route, send a pre-warm request at startup with
max_tokens: 0and the breakpoint on the shared blocks (not on the placeholder message). It writes the cache and returns no output tokens. Skip pre-warming when traffic is continuous; the first real request does the same job.
5. Changing instructions without breaking the cache
Midway through a conversation, an admin switches cedar to "short answers" mode. The obvious change, editing the top-level system, changes the prefix in front of the whole conversation history, so every cached turn is processed again at full price.
On current models (Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5, among others) you can instead append a system message inside messages, after the history:
messages: [
...history,
{ role: "user", content: latestUserText },
{ role: "system", content: "Short-answer mode: keep replies under 60 words." },
],The cached prefix stays byte-identical, and the new instruction applies from that point on. It must follow a user message and can't be the first message. It's also the safer channel: text inside a user turn or a tool result can be forged by whoever writes that text, while a role: "system" message comes from you (Module 5).
What invalidates what
| Change | What you lose |
|---|---|
| Add, remove or reorder a tool | Everything: tools render first |
| Switch model | Everything: caches are per model |
| Edit the system prompt | The system cache and everything after it |
Change tool_choice or add images | The messages cache |
| Change thinking or effort settings | At least the messages cache (more on some models) |
| Append a new message | Nothing before it |
The practical rule: pin the model, the tools, and the thinking and effort settings per route. Don't vary them per request.
6. Effort, model choice and routing
Effort first
output_config.effort (low, medium, high, xhigh, max) trades thoroughness for tokens within one model. Lower effort means less thinking, fewer and more consolidated tool calls and terser output. The default is medium on claude-opus-5-5 and claude-haiku-5-5, and high on most other current models, so set it explicitly per route rather than relying on the default.
await client.messages.create({ ...params, output_config: { effort: "low" } }); // e.g. password-reset FAQsBefore you build a multi-model cascade, measure the top model at a lower effort on the same tasks. It often holds quality at a lower cost, and one model means one cache namespace. A cascade (small model first, big model if needed) gives up cache reuse between its models, and every escalation pays for two calls.
Routing by category, guarded by evals
Most tickets are easy. "How do I reset my password?" doesn't need the largest model. The routing pattern:
type Model = "claude-haiku-5-5" | "claude-sonnet-5-5" | "claude-opus-5-5";
type Category = "password_reset" | "how_to" | "billing_dispute" | "account" | "unsure";
type Answer = { text: string; passedGates: boolean }; // passedGates = the Module 1 checks
// Generated from the latest eval run: a category moves down a tier only if its score holds.
const ROUTES: Record<Category, Model> = {
password_reset: "claude-haiku-5-5",
how_to: "claude-sonnet-5-5",
account: "claude-sonnet-5-5",
billing_dispute: "claude-opus-5-5", // pinned: quality dropped on smaller models
unsure: "claude-opus-5-5",
};
const UP: Record<Model, Model> = {
"claude-haiku-5-5": "claude-sonnet-5-5",
"claude-sonnet-5-5": "claude-opus-5-5",
"claude-opus-5-5": "claude-opus-5-5",
};
export async function answerRouted(category: Category, run: (m: Model) => Promise<Answer>) {
const first = ROUTES[category] ?? "claude-opus-5-5";
const a = await run(first);
return a.passedGates || first === "claude-opus-5-5" ? a : run(UP[first]); // one step up, once
}The fallback signal is measured, not the model's own opinion: the answer failed the Module 1 gates (no citation, below-threshold sources, stop_reason not end_turn). A self-reported "confidence: 0.6" isn't calibrated, so don't route on it.
The failure from the video. Hard billing disputes were routed to the small model because "billing" looked like one category. The Module 4 gate ran the eval set per category and the billing_dispute score dropped well below baseline while overall quality barely moved. The average hid it; the per-category threshold caught it. The fix: split the category, pin billing_dispute to the larger model, and keep the route table generated from eval results, not edited by hand.
7. Batch the work nobody is waiting for
Some work has no user waiting: nightly ticket tagging, doc summaries for the index, eval runs. The Message Batches API runs ordinary Messages requests asynchronously at 50% of standard prices on every token, including cache reads and writes, so the discounts stack.
const batch = await client.messages.batches.create({
requests: tickets.map((t) => ({
custom_id: `${t.tenant}-${t.id}`, // your key for matching results
params: {
model: "claude-haiku-5-5",
max_tokens: 4000,
output_config: { effort: "low" },
messages: [{ role: "user", content: `Tag this support ticket with one product area:\n\n${t.text}` }],
},
})),
});
// Later, once client.messages.batches.retrieve(batch.id) shows processing_status === "ended":
for await (const r of await client.messages.batches.results(batch.id)) {
if (r.result.type !== "succeeded") { queueRetry(r.custom_id); continue; } // errored / canceled / expired
saveTags(r.custom_id, r.result.message);
}Facts to know (checked 2026-11-25):
Up to 100,000 requests or 256 MB per batch.
Most batches finish within an hour; the maximum is 24 hours. That's an expiry, not a promise.
Results stay available for 29 days.
Results come back in any order. Match them by
custom_id, never by position.A batch request can't set
stream,speed(fast mode),fallbacksormax_tokens: 0.
Two failure cases from real life:
Matching by position. A developer zipped the results with the input array. Tags landed on the wrong tickets, and nothing errored. Always key by
custom_id.Batching something user-facing. Someone moved "draft a reply" to batch to save money. Customers waited hours. Batch is for work that can wait a day, never for anything a person is waiting on.
8. A context budget
Tokens you don't send cost nothing and add no latency. Three budgets, each measured:
Retrieval top-k. Run the eval at k = 3, 5 and 8. If quality is flat from 5 to 8, use 5. Over-retrieval also gives the model more weak material to guess from (Module 1).
Thread length. Cedar tickets can run to 40 messages. Summarise older turns with a cheap model and keep the last few verbatim, but do it at a clear boundary (for example, start a new conversation from the summary). Rewriting history in place breaks the cache from the edit point, and on the newest models it can also invalidate earlier thinking blocks.
Tool-output size.
get_orderused to return the whole order record (addresses, item metadata, the audit trail). Return only the fields the agent needs, and cap long outputs with a clear "truncated, N more lines" note so the model knows something is missing.
Measure with the token-counting endpoint instead of guessing:
const { input_tokens } = await client.messages.countTokens({
model: "claude-opus-5-5",
system: SYSTEM_PROMPT,
tools: TOOLS,
messages,
});Track tokens per ticket on the dashboard next to cost per ticket. A creeping rise usually means a tool output or a retrieval change, not users writing longer tickets.
9. Make it feel fast
Users judge speed mostly by when text starts to appear, and by whether anything is happening.
Stream user-facing answers. Time to first token drops from "the whole answer" to "the first words":
const stream = client.messages.stream(buildRequest(policy, history, chunks, question));
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
res.write(event.delta.text); // push to the widget as it arrives
}
}
const final = await stream.finalMessage(); // full message, usage and stop_reasonOn Claude Opus 5.5 thinking is always on, and by default its thinking text isn't returned, so a stream can look like a pause before the first words. Lower effort on chat routes shortens that pause; showing a "thinking…" indicator makes it honest.
Run independent work in parallel. Start retrieval while classification runs instead of after it:
const [category, chunks] = await Promise.all([
classify(ticket.text),
embed(ticket.text).then((v) => retrieve(tenantId, v)),
]);Let the model call tools in parallel. When the model asks for
get_orderandsearch_docsin one turn, run them concurrently and return all thetool_resultblocks in one user message. Splitting results across several messages teaches the model to stop making parallel calls.Pre-warm the cache at deploy (section 4) so the first user doesn't pay the cold prefill.
Fast mode, only where it's measured to matter. Claude Opus 5.5 offers a fast mode (
speed: "fast") with up to about 2.5× the output speed at a premium price. It doesn't work with Batches. It's a last lever for a latency-critical route, after the free ones above.
10. The scorecard: all three numbers or it doesn't count
At the end of the lab, the same 60-ticket eval set and a replayed day of traffic produce one table (demo data, fictional):
| Before | After | Notes | |
|---|---|---|---|
| Cost per resolved ticket (index) | 100 | 46 | Caching, routing, batching, top-k 8 → 5 |
| Cache hit rate | 0% | 81% | Timestamp moved below the cache line |
| p50 / p95 time to done | 4.1 s / 9.8 s | 2.6 s / 6.1 s | Parallel retrieval, streaming |
| Quality score (M4 suite) | 0.91 | 0.91 | Within run-to-run noise |
billing_dispute quality | 0.88 | 0.88 | Kept on the larger model after the gate caught the drop |
If the cost column improves and the quality column drops, you haven't optimised, you've changed the product. Report all three, per category, every time.
Trade-offs
Caching vs flexibility. A frozen system prompt and fixed tools cache well but make per-tenant tweaks harder. Put per-tenant content in its own block after the shared one, and use mid-conversation system messages for mid-session changes.
5-minute vs 1-hour TTL. The 1-hour TTL keeps entries alive across gaps but doubles the write price. Choose by the gap between requests that share the prefix.
Routing vs one model at lower effort. Routing can cut cost on easy categories, but it adds a classification call, gives up cache reuse across models, and needs an eval per category. Try lower effort on one model first.
Batch vs synchronous. Half price, but up to 24 hours and no streaming. Only for work nobody is waiting on.
Smaller context vs quality. Every budget (top-k, summaries, truncated tool output) can remove the one fact an answer needed. Change one budget at a time and run the eval.
Fast mode vs cost. It buys output speed at a premium. Worth it only on a route where measured latency costs you something.
Common mistakes
Putting timestamps, request ids or user names at the top of the system prompt.
Building the tool list per user or in a non-deterministic order.
Reading
input_tokensas the whole prompt size and concluding caching isn't working (or is).Using automatic caching alone on requests that end in unique content, so every request pays a write that's never read.
Firing many identical-prefix requests at the same moment and expecting the later ones to hit the cache.
Editing the top-level system prompt mid-conversation instead of appending a system message.
Changing effort or thinking settings per request on the same route.
Routing on the model's self-reported confidence, or on an overall eval score that hides a weak category.
Matching batch results by position, or batching user-facing work.
Optimising cost without re-running the quality eval.
Remember
Stable first, volatile last. Nothing that changes per request goes above the cache line.
Check
cache_read_input_tokens, and remember thatinput_tokensis only the uncached remainder. Keep a standing test and a dashboard alert.Pin the model, tools, effort and thinking per route; mid-session changes go in an appended system message.
Try the best model at lower effort before building a cascade. Route down only where per-category evals hold, and fall back up on measured failures.
Batch is half price for work nobody is waiting on; key results by
custom_id.Stream, parallelise, pre-warm. Then report cost, latency and quality together.
Check before relying on it
Minimum cacheable prefix per model (512 tokens for
claude-opus-5-5and the other newest models on 2026-11-25, flagged in the docs themselves as "check before relying") and whether it has changed.Cache read multipliers (0.05× on Claude Opus 5.5 and Sonnet 5.5, ~0.1× on most other models on 2026-11-25) and the write multipliers (1.25× / 2×): confirm on the current pricing page.
Mid-conversation system messages: which models support them (Opus 5.5, Sonnet 5.5 and Haiku 5.5 among others, but not Sonnet 5, on 2026-11-25), and the placement rules.
Fast mode: model and platform support, the "up to 2.5×" figure and its price change often.
Message threads (beta
message-threads-2026-08-12) can make each request in a long loop smaller by letting the API keep the conversation for a short time; they can't be combined with compaction, Batches or token counting. A beta worth knowing exists; check before you depend on it.Batch limits (100,000 requests / 256 MB, 24-hour expiry, 29-day results) and which request fields a batch rejects.
Default effort per model (
mediumonclaude-opus-5-5andclaude-haiku-5-5on 2026-11-25).