CCDV-P Study Guide
Free study guide for the Claude Certified Developer - Professional (CCDV-P) exam: 25 lessons, one per official skill, on running Claude systems in production. One chapter per exam domain, one page per lesson, in the order the official exam guide lists them.
6. Domain 6: Cost and Latency Optimization at Scale
6.1. 6.1 Cost architecture at scale: cost models, routing, caching, batch and tenant budgets
CCDV-P · Domain 6 · Lesson 6.1 · 21 min read
Find what drives a fleet's Claude bill in usage data, then fix it: model routing and cascades, cache diagnostics and TTL, batch economics and tenant budgets.
Why the bill grew twice as fast as the traffic
Velora Analytics sells a business-intelligence platform to 1,200 companies. Eleven features inside it call Claude: Ask Velora, an assistant that turns a plain-English question into a database query and an answer; Insight narratives, the paragraph of commentary above each dashboard; a weekly digest emailed every Monday; a formula helper; and seven smaller ones. Each tenant, one customer company with its own data and contract, runs through the same pipeline.
Between June and September, requests grew 1.6x. The Claude bill grew 3.4x, from $38,000 to $129,000 a month. Finance's first draft of next quarter's plan extended the line: another 3.4x. Marisol, the staff platform engineer who owns the Claude integration, refused to sign it. Something in the way the product called the API had changed.
One API call has a simple price: tokens in, tokens out, times a rate. A fleet's bill is that price summed over eleven features, several models, four kinds of input token and 1,200 tenants, and each can move on its own. A team that watches only the total guesses, usually by pulling the most visible lever. Cost architecture is the alternative. A cost model splits the bill into traffic, tokens per task and price per token, and you read it until the dominant driver shows. Then you apply the fix that matches that driver and forecast from the same model.
Build the cost model before you cut anything
When cost grows faster than traffic, which of the other two factors moved? Traffic is requests. Tokens per task is how many input and output tokens one unit of work consumes, every call of an agent loop included. Price per token depends on the model and on each input token's cache state: processed fresh, written to the prompt cache, or read from it. At Velora, cost per request rose 2.1x (3.4 divided by 1.6), so tokens per task, price per token or both had moved.
Prices are set per model and per cache state. These are the Claude API list-price ratios for three models of the current lineup, checked on the pricing page on 30 November 2026. The cache columns are multiples of the same model's base input price.
| Model | Base input, vs Sonnet 5.5 | Cache write (5 minutes / 1 hour) | Cache read | Output, vs its input |
|---|---|---|---|---|
| Claude Haiku 5.5 (prompts up to 100,000 tokens) | a twentieth | 1.25x / 2x | 0.1x | 5x |
| Claude Sonnet 5.5 | 1x | 1.25x / 2x | 0.05x | 5x |
| Claude Opus 5.5 | 2x | 1.25x / 2x | 0.05x | 5x |
Memorise the ratios, not the dollars, which you look up on the day you build the model. A cache write costs 1.25x base input for the 5-minute lifetime and 2x for the 1-hour one. A read costs a tenth of base input on most models, but only a twentieth on Opus 5.5 and Sonnet 5.5, so a cache-read multiplier copied from one model misprices another. The Batch API halves input and output, and the discounts stack.
Each response's usage object carries the counts the model needs: input_tokens (only the tokens after the last cache breakpoint), cache_creation_input_tokens (with a cache_creation breakdown by lifetime), cache_read_input_tokens and output_tokens. A request's cost is each count times its rate, summed. Marisol tagged every call with its feature and tenant, summed a month, and compared September with June.
| Feature | June | September | Change | What the data showed |
|---|---|---|---|---|
| Ask Velora | $14.0k | $58.8k | 4.2x | Traffic 2.1x; every question moved from Sonnet to Opus in July |
| Insight narratives | $9.0k | $36.9k | 4.1x | Traffic 1.6x; cache reads near zero since an August prompt change |
| Formula helper | $1.0k | $11.1k | 11x | One tenant's script calls it about 24,000 times a night |
| Weekly digest | $5.0k | $8.0k | 1.6x | In line with traffic; runs in realtime every Monday |
| Seven other features | $9.0k | $14.4k | 1.6x | In line with traffic |
Had everything grown with traffic, September would have cost about $61,000. Three lines explain the $68,000 gap, each with its own cause: the model, the cache state, one tenant's traffic. The digest, first proposed for savings because batch is easy, did nothing wrong.
Reading a fleet bill
A forecast is the same model run forward: per feature, expected traffic times tokens per task times the price for its model mix and cache state. Extending the total assumes July's model switch and August's cache break repeat every quarter. Forecasting per feature turns each assumption (growth, model mix, hit rate) into a number you can watch and revise.
Routing and cascades: the cheapest model that clears the quality floor
Why did Ask Velora move to Opus? In June two enterprise tenants complained about wrong answers to questions joining several datasets. The fix shipped in a day: every question, from "how many active users yesterday" to a five-table reconciliation, went to Opus 5.5. The complaints stopped, and the price doubled for the 88% of questions Sonnet had answered well.
The alternative is model routing: sending each request to the cheapest model that handles it. Routing rests on a quality floor, the minimum measured quality a feature must keep, fixed before the experiment and measured on a held-out evaluation set. Velora's floor for Ask Velora: 94% of 400 labelled questions answered correctly, and no worse than Opus on the 60 multi-dataset ones. Anthropic's guidance adds the yardstick: compare models on cost per completed task, not per token, because a failed task still bills its tokens, and then the retry.
Three routing shapes exist, and the requirement decides between them.
| Option | When it wins | What it costs |
|---|---|---|
| Fixed assignment (one model per feature) | The feature's tasks are uniform in difficulty | Nothing to run; wastes money when difficulty varies |
| Router (a cheap classifier picks the model up front) | Difficulty is visible in the request before any answer exists | A classification call per request; misroutes stay unseen unless measured |
| Cascade (cheap model first, escalate on a failure signal) | Code can reliably tell a bad answer from a good one | Escalated requests pay for both attempts, plus the extra wait |
A cascade fits Ask Velora because its output can be checked by code. Sonnet writes the query; Velora's validator parses it against the tenant's schema, runs it with a row limit and checks that the answer cites the result. Failing any check is the escalation criterion, and only then does Opus get the question. The model's self-rated confidence is not one: a wrong model is often confidently wrong, and a cascade that trusts the rating lets those failures through.
Ask Velora as a cascade
On the evaluation set, Opus alone scored 95.5%, Sonnet alone 91% and the cascade 95%, matching Opus on the multi-dataset questions because nearly all of them escalated. On September traffic, Sonnet for everything plus Opus for the 15% that escalate costs about $38,000 instead of $58,800. Two details matter at scale. The prompt cache is per model, so an escalation starts cold on Opus; escalate whole tasks, not turns mid-conversation. And the escalation rate is now a production metric: if it climbs toward 40%, the savings are gone.
Caching across a fleet: hit rate, dead writes and TTL
What went wrong in Insight narratives? Every request starts with the same 12,000-token prefix (writing instructions and Velora's metric glossary), then the tenant's dashboard data. In June, 85% of the feature's input tokens were cache reads. In August a developer added "Generated at {timestamp} for {tenant name}" to the top of the system prompt. A cache hit needs a byte-for-byte identical prefix, and the prefix now changed on every request.
Two metrics expose this, both computed from usage. Cache hit rate is the share of input tokens read from the cache: cache reads divided by reads plus writes plus input_tokens. The second catches the costlier failure: cache writes that never get read. A write costs 1.25x base input, so a prefix written on every request and never reused costs more than no caching at all. In September, Insight narratives showed a 3% hit rate and a fresh 12,000-token write on nearly every request.
| Signal in usage data | What it usually means | What to do |
|---|---|---|
| Reads high, writes low | The cache works | Keep it; alert when the hit rate drops |
| Writes high, reads near zero | The prefix changes per request, or reuse is slower than the TTL | Find the divergence with cache diagnostics; review the TTL |
| Reads and writes both zero | No breakpoint, or a prefix below the model's minimum cacheable length (no error is returned) | Mark the breakpoint; check the minimum for the model |
| Hit rate drops when a route changes | The cache is per model | Expect a re-warm; keep a conversation on one model |
Cache diagnostics finds the cause without guessing. You add a diagnostics object to each request, passing the previous response's id as previous_message_id, and the API compares the two requests' structure and reports the first divergence as a cache_miss_reason. Marisol ran it on two consecutive Insight requests and got system_changed, with cache_missed_input_tokens near 12,000. The fix is the one the docs give: make the system prompt a byte-stable constant and move the changing values into the user message, after the cached prefix. Other reasons point elsewhere: tools_changed for a reordered tool list, model_changed for a router switching models mid-conversation, messages_changed for edited history.
The last decision is the TTL, the cache entry's lifetime. The default is five minutes, refreshed free on every hit, so a prefix reused more often than that never needs more. The 1-hour TTL ("ttl": "1h" in cache_control) costs 2x base input per write and earns it when reuse gaps fall between five minutes and an hour. That fits Ask Velora's per-tenant schema prefix: most tenants ask every ten to twenty minutes, so a 5-minute entry expires between questions. Setting 1 hour everywhere is the opposite mistake: Insight narratives runs many times a minute, and a doubled write price buys nothing.
One fleet fact finishes the picture. On the Claude API, caches are isolated between workspaces, so a prefix shared by features in different workspaces is written, and paid for, once per workspace.
Batch or realtime: let the deadline decide
Every Monday at 06:00 the digest job fires about 11,000 realtime requests, one per subscribed user, and waits for each. Nobody reads a digest before 08:00. That is the signal for the Message Batches API: you submit many requests together, they are processed asynchronously, and input and output both cost half the standard price. Most batches finish in under an hour, but the only guarantee is 24 hours; a request not processed by then expires and is not billed. Results arrive in any order, matched by each request's custom_id, and stay downloadable for 29 days.
The deciding requirement is who waits for the answer, not how big the job is.
| Workload | Who waits for the answer | Mode |
|---|---|---|
| Ask Velora, Insight narratives | A person looking at the screen | Realtime |
| Weekly digest | Nobody until Monday 08:00 | Batch, submitted Sunday evening |
| Nightly grading of sampled answers | A dashboard the next morning | Batch |
| Backfilling narratives for a new metric | Nobody, within a few days | Batch, in slices |
Batch and caching stack. Batched requests run concurrently, so cache hits are best effort (30% to 98% in the docs), and the docs recommend the 1-hour TTL for shared context because a batch can outlast five minutes. For the digest, whose requests share a 6,000-token instruction prefix, that takes the line from $8,000 a month to about $4,000. It is worth doing, and it is the smallest of Velora's four levers: starting there would have saved $4,000 of a $68,000 gap.
Per-tenant budgets: meter in your gateway, enforce before the call
The formula helper's 11x was one tenant. A customer had wired the feature into a nightly script that called it about 24,000 times; their contract was a flat platform fee, and Velora's cost for them alone was $9,500 a month. Nothing in the stack had a limit per tenant.
Anthropic's controls stop at the organisation and the workspace. You can set a monthly spend limit for the organisation and custom spend and rate limits for each workspace; a workspace that reaches its spend limit gets HTTP 400 invalid_request_error on every request. Those are the right backstop for an application and the wrong tool for tenants. An organisation gets 1,000 workspaces by default against Velora's 1,200 tenants, a workspace limit stops everyone inside it at once, and the usage and cost reports group by workspace, API key, model or the user behind a request, never by your customer. Per-tenant budgets live in Velora's own gateway, the one service every Claude call passes through.
The gateway meters after each call, pricing the response's usage into the tenant's ledger, and enforces before each call, checking month-to-date spend against the tenant's budget. In the sketch, look at the order: the check runs before messages.create, so an over-budget tenant never spends, and the ledger prices the response's own usage, so cache reads and writes count at their real rates. The cache fields can be null and the cache_creation breakdown can be missing, so the code defaults them instead of crashing the gateway.
BASE = {"claude-sonnet-5-5": 2.00, "claude-opus-5-5": 4.00} # USD per million input tokens, checked on the pricing page
READ, W5M, W1H, OUT = 0.05, 1.25, 2.0, 5.0 # multiples of base input for these two models
def request_cost(model, u):
cc = u.cache_creation # split of writes by TTL; may be absent
w1h = (cc.ephemeral_1h_input_tokens or 0) if cc else 0
w5m = (u.cache_creation_input_tokens or 0) - w1h # no split: count writes as 5-minute
units = (u.input_tokens + (u.cache_read_input_tokens or 0) * READ
+ w5m * W5M + w1h * W1H + u.output_tokens * OUT)
return units * BASE[model] / 1_000_000
def call_for_tenant(tenant, feature, **params):
if ledger.month_to_date(tenant.id) >= tenant.hard_limit_usd: # ENFORCE before the call
raise BudgetExceeded(tenant.id, feature)
response = client.messages.create(**params)
ledger.add(tenant.id, feature, response.model, # METER with real usage
request_cost(response.model, response.usage))
return response
What happens at the limit is a product decision that code enforces. At 80% of a plan's budget, the account owner is notified. At 100%, the tenant degrades rather than stops: interactive features run on cheaper settings and scheduled work moves to batch. At 120%, scheduled and API-driven calls are refused with a clear message, while a person typing in the product still gets answers. A per-tenant rate limit on the formula helper's API closes the script hole, and each workspace spend limit stays as a backstop, sized well above the sum of tenant budgets.
Where each budget is enforced
The exam traps
- ✗ Forecasting next quarter by extending the total bill's growth. ✓ Forecast per feature from traffic, tokens per task and price. The total turns one-off changes into a trend.
- ✗ Cutting what is easy to change, such as batching one job, before splitting the bill. ✓ Split by feature, model, cache state and tenant, and fix the dominant driver. Easy savings leave the real cause running.
- ✗ Moving a whole feature to the most capable model because a hard slice failed. ✓ Route or cascade, accepted only when it clears the quality floor on a held-out set. Otherwise every easy request pays the premium.
- ✗ Escalating in a cascade when the model rates its own answer as uncertain. ✓ Escalate on a check code can run: the query parses, executes and supports the answer. Confidence ratings let confidently wrong answers through.
- ✗ Treating "caching is enabled" as caching that works, or setting the 1-hour TTL everywhere. ✓ Measure hit rate and unread writes per feature, and pick the TTL from the reuse gap. Dead writes cost more than no cache.
- ✗ Using workspace or organisation spend limits as tenant budgets. ✓ Meter per tenant in your gateway and enforce before the call. Platform limits stop every tenant behind them at once.
Put it together: cut a fleet bill and forecast the next quarter
You now have every piece: a cost model, a way to read it, and one control per driver. On September's traffic, Velora's four fixes (the cascade, a byte-stable prefix, a budget on the script tenant, a batched digest) bring the month from $129,000 to about $74,000. With 15% growth, the per-feature forecast is about $85,000 a month, against the roughly $440,000 that extending the line would have planned.
Latency engineering (6.2) uses caching and effort levels to cut the wait, where this lesson used them to cut the bill. Scale and throughput management (2.2) reads the same token counts against rate limits, where cache reads matter again because they do not count toward input-token limits.
Key takeaways
- ✓ A fleet's bill is traffic x tokens per task x price per token, and price depends on the model and on each input token's cache state.
- ✓ Split the bill by feature, model, cache state and tenant until one driver dominates, and forecast per feature rather than extending the total.
- ✓ Route each request to the cheapest model that clears a quality floor on a held-out set; a cascade escalates on a verifiable check, never on self-rated confidence.
- ✓ Judge caching by hit rate and by writes that never get read, find broken prefixes with cache diagnostics, and choose the 1-hour TTL only for reuse gaps between five minutes and an hour.
- ✓ Send work nobody reads within the hour to the Batch API at half price, stack it with caching, and rank it by the dollars it actually moves.
- ✓ Enforce tenant budgets in your gateway before each call, with platform spend limits as backstops only.
Practise this
Practice questions for CCDV-P are being written and are not in this course yet. Read this lesson on the web to answer its check questions, with every option explained: https://claude.termidy.com/learn/ccdv-p/cost-latency-optimization/cost-architecture-at-scale/.