Skip to content

    Certification

    CCDV-P M5: Cost and Latency Optimization at Scale

    Prompt caching, the Batch API, model routing, time to first token versus generation time, streaming, parallel calls and cost arithmetic with worked examples.

    By Published 24 min read

    Share

    This lesson is part of Claude Certified Developer — Professional. Enroll for free, then sign in, to read it in full.

    Cost and latency problems rarely show up in a demo. They show up when traffic grows a hundredfold and the invoice, or the p95 response time, stops being a rounding error. The discipline is the same as elsewhere in this course: measure first, change one thing at a time, and protect quality with an evaluation so that "cheaper" does not quietly mean "worse".

    NOTE

    Every price in this module is illustrative. The worked examples say "assume $X per million tokens" so you can follow the arithmetic. Real prices, cache multipliers and model names change; check Anthropic's pricing page before you plan a budget. The documented mechanisms (what is cached, what the Batch API trades away) are taken from the official pages listed at the end.


    5.1 Prompt caching: stable prefix first

    Prompt caching lets the API reuse the processed form of the beginning of a prompt across requests. It matches on an exact prefix, and the docs state the prefix order: tools, then system, then messages, up to the block you mark with cache_control.

    That order gives the one rule that governs everything: put stable content first and dynamic content last. Anything that changes on every request (a timestamp, a user id, the current question) must come after the breakpoint. A single changing token before the breakpoint makes every request a miss.

    Figure 1. Prompt layout: stable first, dynamic last

    Prompt layout for cachingTool definitions to System prompt; System prompt to Policy document; Policy document to Dynamic input (after breakpoint); Policy document to Prompt cache (read or write)CACHED PREFIXTool definitions: changes rarelyTooldefinitionschanges rarelySystem prompt: changes rarelySystem promptchanges rarelyPolicy document: breakpoint herePolicydocumentbreakpoint hereDynamic input: changes every callDynamic inputchanges everycallPrompt cache: exact prefix matchPrompt cacheexact prefixmatchafter breakpointread or write

    How to read this: the prompt is read left to right in the order tools, system, messages; everything inside the box is the exact prefix the cache matches, and the orange node on the right is the only part allowed to change.

    TIP

    Picture it: Pre-printed company stationery. The letterhead is printed in bulk because it never changes; only the blanks are filled in per letter. Print today's date into the letterhead and every sheet becomes unique, so the stack of pre-printed paper is worthless. (The cache is stricter than stationery: one changed character early in the prefix voids everything after it.)

    import anthropic
    
    client = anthropic.Anthropic()
    MODEL = "your-pinned-model-id"  # from your config, not hard-coded across files
    
    response = client.messages.create(
        model=MODEL,
        max_tokens=500,
        system=[
            {"type": "text", "text": "You answer questions about the Larkspur Outfitters returns policy."},
            {
                "type": "text",
                "text": POLICY_TEXT,  # large, identical on every request
                "cache_control": {"type": "ephemeral"},  # breakpoint after the stable part
            },
        ],
        messages=[{"role": "user", "content": user_question}],  # dynamic, after the breakpoint
    )
    print(response.usage.cache_creation_input_tokens, response.usage.cache_read_input_tokens)

    Facts from the docs that exam scenarios lean on:

    • The default cache lifetime is 5 minutes and is refreshed each time the cached content is used. A 1-hour lifetime is available at additional cost.
    • A minimum cacheable size applies, and it differs by model. A prompt shorter than the minimum is processed without caching and no error is returned, which is why a "cache that never hits" is sometimes simply a prompt that is too short. Look up your model in the docs table; do not assume.
    • You can set up to four explicit breakpoints. Place one at the end of each segment that changes at a different rate (for example, tool definitions, then a policy document, then conversation history).
    • The response usage reports cache_creation_input_tokens (written), cache_read_input_tokens (read) and input_tokens (only the tokens after the last breakpoint). Total input is the sum of the three. Watch these fields to know whether caching works.
    • Caching affects input processing only. Output tokens are never cached; they are billed and generated every time.
    • A cache entry becomes available only after the first response begins. If a hundred parallel workers start together with a cold cache, all hundred pay the write. Send one request first, wait for it to start, then fan out.

    Figure 2. "The cache did not help": check in this order

    flowchart TD accTitle: Diagnosing a cache that saves nothing accDescr: Start from a cache that did not change the bill. First check whether the marked block is above the minimum size for the model. If not, it is processed without caching and no error is returned, so enlarge the block or accept no caching. If it is large enough, check whether anything dynamic sits ahead of the breakpoint. If so, move it after the breakpoint. If not, read the usage fields: if cache reads are zero, look at lifetime and parallel cold starts; if reads appear, caching works and the remaining cost is output or uncached input. S["Bill did not change"] A{"Marked block above the model minimum size?"} B{"Anything dynamic ahead of the breakpoint?"} C{"Do usage fields show cache reads?"} A1["Too short: processed without caching, no error"] B1["Move timestamps, ids and the question after the breakpoint"] C1["Check the lifetime, prefix edits and cold-start bursts"] C2["Caching works: look at output tokens and uncached input"] S --> A A -->|"no"| A1 A -->|"yes"| B B -->|"yes"| B1 B -->|"no"| C C -->|"no reads"| C1 C -->|"reads present"| C2

    How to read this: take the questions from top to bottom; each problem branch ends in its own fix, and the last box is the good news, that caching works and the cost lives elsewhere.

    Exam angle. "We added cache_control and the bill did not change." Check three things in order: is the marked block above the minimum size for the model, is anything dynamic ahead of the breakpoint, and does usage show reads at all. Common trap: concluding that caching "does not work for large prompts" or adding more breakpoints without fixing the volatile prefix.

    NOTE

    On call, 3 a.m.: Ravi Menon at Cobalt Parcel turns on caching for a long courier-rules prompt and goes to bed pleased. In the morning the invoice looks the same and the usage fields show writes on every call and no reads. The first line of every prompt is Request id: 48213, a new number each time, so no two prefixes are ever equal. He moves the request id below the breakpoint and the next batch of calls reads the rules from the cache. Invented example.


    5.2 What invalidates a cache, and what it costs

    Because the match is a prefix, a change invalidates everything after the changed point. The docs list what breaks which part. In summary: changing tool definitions invalidates the tools, system and messages caches; changing the system prompt invalidates system and messages; toggles such as web search or citations affect system and messages; changing tool choice or adding or removing images affects the messages cache.

    Practical consequence: version your static prefix deliberately. Editing one sentence of a 20,000-token system prompt on a busy service means the next request writes the entire prefix again. Batch prompt edits into releases, and do not generate the prefix from something that varies per request (a rendered date, a randomised example order, a dictionary serialised in unstable key order).

    The cost model. Assume a write costs a premium over the normal input price and a read costs a fraction of it. The docs give the multipliers per model and lifetime (they differ by model); for the arithmetic below assume a write at 1.25x and a read at 0.1x the base input price, both illustrative.

    Worked example (illustrative prices). Assume input at $3 per million tokens and output at $15 per million. A service sends 1,000 requests inside one cache lifetime, each with a 20,000-token stable prefix, 400 dynamic input tokens and 300 output tokens.

    Item Per request Working
    No caching: input $0.0612 20,400 tokens x $3 / 1,000,000
    No caching: output $0.0045 300 x $15 / 1,000,000
    No caching, 1,000 requests $65.70 1,000 x ($0.0612 + $0.0045)
    Cached, first request $0.0807 write 20,000 x $3.75 / 1,000,000 = $0.075; dynamic $0.0012; output $0.0045
    Cached, each later request $0.0117 read 20,000 x $0.30 / 1,000,000 = $0.006; dynamic $0.0012; output $0.0045
    Cached, 1,000 requests about $11.77 $0.0807 + 999 x $0.0117 = $0.0807 + $11.6883

    The saving is about $53.93, roughly 82%. Notice the break-even: the write premium on the prefix is 20,000 x $0.75 / 1,000,000 = $0.015, and each read saves 20,000 x $2.70 / 1,000,000 = $0.054, so a single reuse within the lifetime already pays back the premium. A prefix that is rarely reused within the lifetime, by contrast, only pays the premium.

    Caching also relieves rate limits: tokens read from the cache do not count toward the input-tokens-per-minute limit (see module 2).


    5.3 Batch API: cheaper, slower, asynchronous

    The Message Batches API processes many requests asynchronously. According to the docs, usage is billed at 50 percent of standard prices, most batches finish within an hour, and a batch expires if it is not done within 24 hours. What you trade away is immediacy: there is no streaming and no response while a user waits.

    Use it for work nobody is waiting on: nightly classification, bulk summarisation, evaluation runs, backfills. Do not use it for an interactive chat turn or anything with a latency SLO in seconds.

    Figure 3. Two paths: real-time for people, batch for backlogs

    Real-time path and batch pathUser waiting to Messages API (streamed reply); Messages API to Claude model; Nightly job to Batch API (many requests); Batch API to Claude model; Claude model to Result store (collect later); Result store to Retry queue (not succeeded)User waiting: chat turnUser waitingchat turnMessages API: standard priceMessages APIstandard priceNightly job: nobody waitingNightly jobnobody waitingBatch API: 50% priceBatch API50% priceClaude modelClaude modelResult store: match by custom_idResult storematch bycustom_idRetry queue: errored, expiredRetry queueerrored, expiredstreamed replymany requestscollect laternot succeeded

    How to read this: the top path is a person waiting and gets an immediate stream; the bottom path trades immediacy for half price, and your code collects results later and re-queues anything that did not succeed.

    TIP

    Picture it: Express post versus freight. A parcel that must arrive tomorrow goes express at full price. A pallet of stock for next month goes by freight at half the cost, and nobody stands at the door waiting for it. The mistake is to put the birthday present on the freight lorry because it is cheaper.

    batch = client.messages.batches.create(
        requests=[
            {
                "custom_id": f"doc-{doc_id}",
                "params": {
                    "model": MODEL,
                    "max_tokens": 400,
                    "messages": [{"role": "user", "content": prompt_for(doc)}],
                },
            }
            for doc_id, doc in documents
        ]
    )
    
    # later: poll until processing_status == "ended", then stream the results
    for item in client.messages.batches.results(batch.id):
        if item.result.type == "succeeded":
            store(item.custom_id, item.result.message)
        else:
            retry_queue.append(item.custom_id)  # errored, canceled or expired

    Things to design for, all from the docs:

    • A batch is limited to 100,000 requests or 256 MB, whichever comes first. Match results to inputs by custom_id.
    • Individual results can be succeeded, errored, canceled or expired; the last three are not billed. Your job must re-queue them.
    • Request parameters are validated asynchronously, so test a request shape with the normal Messages API first.
    • Results are retained for a limited time (the docs say 29 days); download them.
    • Prompt caching works in batches, but hits are best effort because requests run concurrently and in any order. The docs suggest the 1-hour lifetime for batches with shared context.

    Worked example (illustrative prices). A nightly job processes 50,000 documents, each 2,000 input tokens and 500 output tokens. Assume $3 per million input and $15 per million output. Synchronously: input 50,000 x 2,000 = 100,000,000 tokens = $300; output 50,000 x 500 = 25,000,000 tokens = $375; total $675. At the 50% batch discount: $337.50, a saving of $337.50 with a longer, uncertain completion time.

    Exam angle. An overnight report job is run synchronously against a rate limit and keeps failing. The batch route removes the contention and halves the cost. Common trap: choosing the Batch API for a feature a user is actively waiting on, because "it is cheaper".


    5.4 Right-size the model and route by task

    Not every request needs the most capable model. A common design is a small, fast model for routine, well-bounded tasks (classification, extraction, short rewrites) and a larger model for hard reasoning, chosen by a router.

    The rule that makes this safe: an evaluation guards the swap. Measure quality on a golden set that includes the hard cases per segment, then lower the model only where the pass rate holds. Routing without an eval trades unmeasured quality for measured savings.

    Worked example (illustrative prices). Assume a larger model at $3 / $15 per million input / output tokens and a smaller one at $1 / $5. A typical request has 1,000 input and 400 output tokens.

    • Larger model: 1,000 x $3/1M = $0.003, plus 400 x $15/1M = $0.006, total $0.009.
    • Smaller model: $0.001 + $0.002 = $0.003.
    • If an eval shows 70% of traffic is easy enough for the smaller model: 0.7 x $0.003 + 0.3 x $0.009 = $0.0021 + $0.0027 = $0.0048, about 47% lower than $0.009.

    Every model change is a release: re-run the eval, and keep the previous setting to roll back to.

    Common trap: picking the smallest model everywhere because "the average score barely moved". Averages hide the hard segment; compare per segment.


    5.5 Latency: TTFT, generation time and streaming

    Total response time has two parts that have different causes.

    • Time to first token (TTFT): mostly the time to process the input prompt. It grows with input size and drops with a cache hit.
    • Generation time: the time to produce the output, roughly proportional to the number of output tokens.
    User complaint Cause Lever
    Long wait before anything appears Large prompt to process Trim or cache the prefix, smaller model
    Text appears quickly but takes ages to finish Long output Ask for shorter output, set sensible max_tokens, structured brief formats
    Looks frozen for a minute No streaming Stream so the user sees progress

    Streaming improves perceived latency only. The docs describe streaming as letting the user see output as it arrives; it does not make the model generate faster. Total completion time does not improve.

    Figure 4. Where the time goes in one streamed answer (illustrative numbers)

    sequenceDiagram accTitle: Time to first token versus total time accDescr: The user asks a question and the app sends the prompt to the model. The model first processes the prompt, which takes about 1.5 seconds in this illustrative example. The first token then reaches the user, so text starts to appear at about 1.5 seconds. The model keeps generating 600 tokens at 40 tokens per second, which takes 15 seconds, and the last text arrives at 16.5 seconds. Streaming moved the first text earlier but not the finish. autonumber participant U as User participant A as App participant M as Model U->>A: question A->>M: prompt Note over M: Process the prompt, about 1.5 s M-->>A: first token A-->>U: first text appears at about 1.5 s Note over M: Generate 600 tokens at 40 per second, 15 s M-->>A: remaining tokens stream A-->>U: last text arrives at 16.5 s

    How to read this: the first note is the wait before anything appears and the second is the time to produce the answer; streaming only moves the "first text" arrow earlier, never the last one.

    TIP

    Picture it: A restaurant brings bread to the table while the main course cooks. The diners are calmer and feel looked after, but dinner still ends at the same time. Streaming is the bread basket. To get dinner earlier you need a shorter menu item (shorter output) or a faster kitchen (smaller prompt, cache, smaller model).

    with client.messages.stream(
        model=MODEL,
        max_tokens=800,
        messages=[{"role": "user", "content": question}],
    ) as stream:
        for text in stream.text_stream:
            send_to_browser(text)

    Worked example (illustrative numbers). Assume 1.5 seconds to process the prompt and 40 output tokens per second. A 600-token answer takes 1.5 + 600/40 = 1.5 + 15 = 16.5 s in total. Streaming brings the first visible text to about 1.5 s but the finish stays at 16.5 s. Cutting the answer to 300 tokens gives 1.5 + 7.5 = 9 s. If instead the prompt was trimmed from 1.5 s to 0.9 s of processing, the finish only improves to 15.9 s. The long output is the real cost here.

    Streaming also matters for reliability on long requests (module 2): a stream can surface an error event after the 200 has been sent, so handle it.

    Exam angle. "Users say the answer is slow, so we enabled streaming and the p95 total time did not move." That is expected; streaming changes when text starts appearing, not when it ends. Common trap: reporting streaming as a total-latency fix.


    5.6 Fewer round trips: parallel calls and composite tools

    Each agent step costs a model call plus a tool call, and the whole context is processed again each time (cheaper if cached, never free). Two fixes cut steps.

    Parallelise independent steps. If a request needs the customer record, the order history and the warehouse stock, and none depends on another, fetch them concurrently. Latency becomes the slowest call, not the sum. Respect data dependencies: do not start the refund calculation before the order lookup returns.

    Mind tail latency. Parallel fan-out makes slow outliers more likely to hurt. If each call has a 1% chance of being slow, the chance that at least one of ten parallel calls is slow is 1 - 0.99^10 = 1 - 0.904 = about 9.6%. Use timeouts, hedged retries for idempotent reads, or return partial results for non-essential branches.

    Composite tools. If the model nearly always calls get_customer, then get_orders, then get_shipment in that order, expose one get_customer_overview tool that does the three lookups in code and returns the combined result. You remove two model round trips and the chance the model skips or misorders a step. Keep the composite narrow enough that its output is small and its permissions are no wider than before.


    5.7 Prune context and do the arithmetic

    Cost is dominated by tokens you send repeatedly. Trim what does not earn its place: drop stale tool results once they have been used, summarise older turns into a structured state (keep exact values such as ids and amounts verbatim), retrieve fewer and better chunks instead of many, and cap tool output size. Compaction can break caching, because rewriting earlier turns changes the prefix; compact in discrete steps rather than every turn.

    A cost review always uses the same checklist: tokens in and out per request, cache hit rate from usage, request volume, and the price per million for the model in use. Build the estimate from those four numbers, then compare against the measured bill. If they disagree, one of your assumptions is wrong; find it before optimising.


    5.8 Break-even needs the value of a completed task

    Price per call is the wrong denominator. What matters is the cost per completed task and what a completed task is worth.

    Worked example (illustrative numbers). A support assistant resolves a conversation without a human 60% of the time. Assume each conversation costs $0.12 in model usage, and a conversation the AI fails to resolve is handled by a person at $5.00. Expected cost per conversation: $0.12 + 0.40 x $5.00 = $0.12 + $2.00 = $2.12.

    A cheaper setup costs $0.04 per conversation but resolves only 35%: $0.04 + 0.65 x $5.00 = $0.04 + $3.25 = $3.29. The "cheaper" model is more expensive overall, because resolution rate dominates. This is also why savings from routing only count if the eval confirms the task still completes.

    NOTE

    On call, 3 a.m.: At Brightwell Support, Elena Costa swaps in a cheaper model that costs $0.04 per conversation instead of $0.12. Finance is delighted for a week. Then the human queue grows, because the cheaper setup resolves only 35% of conversations instead of 60%, and every unresolved one lands on a person at $5.00. The true cost per conversation has risen from $2.12 to $3.29. The cheap model was the expensive choice once the whole path was counted. Invented example.

    Exam angle. A scenario offers a model that is 70% cheaper per token and a lower success rate, and asks which option minimises cost. Compute cost per successful outcome, including the fallback path, before choosing. Common trap: comparing price per million tokens.


    5.9 Cost modelling and forecasting

    A forecast is a model of four things: request volume, tokens per request (split into uncached input, cache writes, cache reads and output), the price of each, and the cache hit rate. Build it from measured averages, state each assumption, and compare it with the real bill every month. When they diverge, one assumption is wrong; find which one.

    Worked example (invented prices and volumes). Assume $3 per million input tokens and $15 per million output tokens, a cache write at 1.25x and a cache read at 0.1x the input price. A service handles 1,200,000 requests a month. Each has 3,000 input tokens, of which 2,400 are a stable prefix, and 350 output tokens.

    • Uncached input: 600 x $3 / 1,000,000 = $0.0018.
    • Output: 350 x $15 / 1,000,000 = $0.00525.
    • Prefix at a perfect hit rate: 2,400 x $0.30 / 1,000,000 = $0.00072.

    Per request: $0.0018 + $0.00525 + $0.00072 = $0.00777, so the month is 1,200,000 x $0.00777 = $9,324. Without caching, input is 3,000 x $3 / 1,000,000 = $0.009, so a request costs $0.01425 and the month $17,100.

    Now stress the assumption. At an 80% hit rate, 20% of prefix tokens are written at $3.75 per million and 80% are read at $0.30: 2,400 x (0.2 x $3.75 + 0.8 x $0.30) / 1,000,000 = 2,400 x $0.99 / 1,000,000 = $0.002376. Per request: $0.0018 + $0.002376 + $0.00525 = $0.009426, the month $11,311.20, about 21% above the perfect-hit forecast. A forecast that shows a range for hit rate is more useful than a single figure.

    Two observations follow from these numbers. Output is about two thirds of the cost per request ($0.00525 of $0.00777), so output length is often the biggest lever once caching works. And request volume is a multiplier on everything: model growth explicitly (for example a 3x traffic scenario) and re-check capacity limits at the same time (module 2).

    Batch against real-time. Work that nobody waits on can move to the Batch API at half price. If 25% of requests could be batched at the same per-request cost, spend falls by about 0.25 x 0.5 = 12.5%, or $1,165.50 of the $9,324. Count only the share whose deadline allows waiting.

    Include the whole path. Retries, escalations to a larger model, evaluation runs and failed requests cost money too. Cost per completed task (5.8) is the number to forecast when quality varies.

    NOTE

    Exam angle. Expect arithmetic with a hit-rate or a volume change; show the per-request figure first, then scale. Common trap: forecasting from list price while ignoring cache misses, output share and retries.


    5.10 Routing and cascades

    Routing (5.4) picks a model before the call. There are two shapes, with different cost curves and risks.

    Router. A cheap classifier, rules, or a small model reads the request and dispatches it to a model tier. You pay the classifier on every request and the chosen model once.

    Cascade. Every request starts at the cheapest tier. A check decides whether the answer is acceptable; if not, the request escalates to the next tier. Escalated requests pay for both attempts and take longer.

    Figure 5. A cascade: cheap first, escalate on a failed check (illustrative prices)

    Cascade from a smaller tier to a larger tierRequest to Smaller tier; Smaller tier to Acceptance check (draft answer); Acceptance check to Answer (80% accepted); Acceptance check to Larger tier (20% escalate); Larger tier to Answer (second attempt); Acceptance check to Route log (every request)RequestRequestSmaller tier: $0.002 eachSmaller tier$0.002 eachAcceptance check: schema, testAcceptancecheckschema, testAnswerAnswerLarger tier: $0.010 eachLarger tier$0.010 eachRoute log: route and outcomeRoute logroute and outcomedraft answer80% accepted20% escalatesecond attemptevery request

    How to read this: every request pays for the smaller tier; only the red path pays again for the larger one. Wrong answers that the check accepts travel the top path and are never caught.

    TIP

    Picture it: A junior accountant handles every invoice, and a senior only sees those the checklist flags. Most invoices cost one person's time. A flagged one costs two people's time, and a mistake that passes the checklist never reaches the senior at all. The checklist is the whole design.

    Worked example (invented prices). A smaller tier costs $0.002 per request and a larger one $0.010. A check accepts 80% of the smaller tier's answers.

    • Cascade: $0.002 + 0.2 x $0.010 = $0.004 per request on average (every request pays $0.002; the 20% that escalate also pay $0.010).
    • Router with a $0.0002 classifier sending 60% to the smaller tier: $0.0002 + 0.6 x $0.002 + 0.4 x $0.010 = $0.0002 + $0.0012 + $0.0040 = $0.0054.

    Here the cascade is cheaper, but only if the acceptance check is trustworthy. A cascade's weak point is the answer that is wrong but accepted, because nothing escalates it. The check should be something measurable: schema validity, a grounding check against the sources (2.6), a deterministic test, or a confidence signal calibrated on a labelled set. The model's own stated confidence alone is a poor gate.

    Router Cascade
    Extra cost Classifier on every request Second attempt on escalations
    Latency One model call Escalated requests wait twice
    Main risk Misrouted hard cases Accepted wrong answers
    Best when Task difficulty is visible in the input A reliable cheap check exists

    Whichever you choose, evaluate per segment (5.4), log the route taken and the final outcome on every request, and watch the escalation rate: a rising share means the traffic changed or the smaller tier regressed. Keep a one-setting rollback to the single-model baseline.

    NOTE

    Common trap: counting a cascade's cost as the smaller model's price plus a fraction of the larger one, and forgetting that the escalated requests also paid for the failed first attempt.


    5.11 Cache diagnostics and checkpoints

    Reading usage on each response turns a cache from a hope into something you can diagnose. Compute the hit rate as cache_read_input_tokens divided by the sum of cache reads, cache writes and uncached input_tokens, and chart it per prompt version.

    What usage shows Likely cause Fix
    Zero reads and zero writes Marked block below the minimum size for the model, or no breakpoint Check the minimum size in the documentation; mark the right block
    Large writes on every call, zero reads A volatile element ahead of the breakpoint Move timestamps, ids and per-user text after the breakpoint
    Reads, then writes again at gaps in traffic Entry expired between requests (the default lifetime is short) Longer lifetime where it pays, or steadier traffic
    Reads collapse after a release The static prefix was edited, or tool order changed Batch edits; keep serialisation stable
    A burst of writes from parallel workers Cold cache; the entry is available only after the first response begins Send one request first, then fan out

    Checkpoints for latency. A cache hit shortens time to first token on a large prompt, because the prefix is not processed again. In a multi-turn conversation, the history grows by a few messages each turn. Put a breakpoint at the end of the most recent stable turn so the next request reads everything before it and processes only the new text. The documentation describes how far back the system looks for an earlier entry and how many breakpoints you may set; check both for long conversations.

    # end of each turn: mark the last stable block so the next turn reads the history
    messages[-1]["content"][-1]["cache_control"] = {"type": "ephemeral"}

    Two cautions. Rewriting earlier turns (compaction, context editing) changes the prefix and forces a new write, so do it in discrete steps. And a cache that is hit often is only a win if its writes are paid back: a prefix reused once per lifetime barely covers its premium (5.2).

    NOTE

    Exam angle. Read the usage fields in the stem and match the pattern to its cause before choosing a fix. Common trap: adding more breakpoints when the real problem is a changing prefix.


    5.12 Per-tenant budget enforcement

    In a multi-tenant product one customer, or one runaway agent loop, can spend the month's budget in an afternoon. A budget is only a control if it is enforced before the money is gone.

    Figure 6. A budget gate in front of every call

    Per-tenant budget gate with reservation and reconciliationRequest to Budget gate; Budget gate to Model call (within budget); Model call to Ledger (actual usage); Ledger to Budget gate (release reserve); Budget gate to Degrade path (over budget); Ledger to Alert (at 80%)Request: tenant, feature tagRequesttenant, featuretagBudget gate: atomic reserveBudget gateatomic reserveModel call: max_tokens cappedModel callmax_tokens cappedLedger: per tenantLedgerper tenantDegrade path: cheaper tier, queueDegrade pathcheaper tier,queueAlert: tenant and teamAlerttenant and teamwithin budgetactual usagerelease reserveover budgetat 80%

    How to read this: the gate reserves the worst-case cost before the call and the ledger replaces it with the real cost afterwards; the red path is the planned response when the budget is gone, so nothing fails silently.

    TIP

    Picture it: A petrol-station pre-authorisation. The pump holds a set amount on your card before you start, then charges the real amount and releases the rest. You cannot pump past what is held, and nobody finds out about the overspend a month later on a statement.

    Meter every call. After each response, compute cost from usage (uncached input, cache writes, cache reads, output) and a price table you maintain, and add it to a ledger keyed by tenant. Tag requests with tenant and feature so the cost can be split later.

    Check before the call, reconcile after. Before a request, estimate its worst case: input tokens plus max_tokens priced as output. Reserve that amount; after the response, replace the reservation with the actual cost. Concurrent requests need the reservation to be atomic, for the same reason as the seat in 2.8; otherwise ten parallel calls each see "budget remaining" and all proceed.

    UPDATE tenant_budget
    SET reserved = reserved + :estimate
    WHERE tenant_id = :tenant
      AND spent + reserved + :estimate <= daily_limit;
    -- rows_affected = 0: over budget, take the degrade path

    Graduated responses. At 80% of budget, alert the tenant and your team. Near the limit, degrade: a cheaper model tier, lower max_tokens, or the queue for batch processing. At the limit, stop with a clear message, not a silent failure. Agents need a cap per task (steps and tokens), since a loop is the usual way a single request becomes expensive.

    NOTE

    On call, 3 a.m.: Dana Whitlock runs the AI features at Pinecrest Labs. One customer's research agent gets stuck calling a failing tool again and again. Because every call goes through a budget gate, the tenant gets an alert at 80% of its daily limit, then the gate switches the agent to a cheaper tier, and at 100% it stops with a clear message. Without the gate the same loop would have run all night and shown up as a surprise on the invoice. In the morning Dana reads a short ledger instead of a large bill. Invented example.

    Differentiate. Different plans can get different budgets and different tiers, and interactive traffic can keep a reserve so that a bulk job cannot exhaust it.

    Budget enforcement is separate from rate limits (module 2): limits protect capacity per minute, budgets protect spend per period. You need both.

    NOTE

    Common trap: relying on a monthly invoice or a dashboard alert as the control. They report the overspend after it happened.


    5.13 Effort level and latency targets

    Some models and features let you set how much reasoning effort the model spends before answering. The exact setting names, the values and which models support them change, so check the current documentation. The principle is stable: more reasoning means more generated tokens, which are billed as output and take generation time. On a simple task that extra work adds cost and delay without improving the answer.

    Worked example (invented numbers). Assume 0.8 s to process the prompt and 50 generated tokens per second. A classification answers in 30 tokens.

    • At high effort the model produces about 700 reasoning tokens first: 0.8 + (700 + 30) / 50 = 0.8 + 14.6 = 15.4 s, and nothing useful appears until reasoning ends.
    • At low effort, about 100 reasoning tokens: 0.8 + 130 / 50 = 0.8 + 2.6 = 3.4 s.

    Streaming would not rescue the first case, because the visible answer starts only after the reasoning.

    Tune it the way you tune a model choice.

    1. Set the latency target from the user need: a time to first useful text for chat, a total time for a form submit, throughput for background jobs.
    2. Profile where the time goes: input processing, reasoning, output, tool calls.
    3. Lower effort per task type, not globally, and run the evaluation per segment. Keep the higher setting where the eval shows a real gain, such as multi-step planning or hard cases.
    4. Cap output with max_tokens and keep a rollback to the earlier setting.

    Effort is one lever among several. Caching cuts time to first token (5.11), parallel tool calls cut the number of sequential steps (5.6), and a smaller model cuts both cost and time (5.4). Choose the lever that matches the part of the profile that dominates.

    NOTE

    Exam angle. If most of the time goes to reasoning on a simple task, lowering effort for that task type, validated by a per-segment eval, is the answer. Common trap: reaching for streaming, or a global downgrade of every request, when one task type is over-spending.

    IMPORTANT

    Remember this:

    • Put stable content first and dynamic content last; the cache matches an exact prefix.
    • Batch is half price but asynchronous: use it only where nobody is waiting.
    • Streaming changes when text starts, not when it ends.
    • Compare options by cost per completed task, and check any cheaper tier with an evaluation per segment.
    • Reserve budget before the call and reconcile after it; an invoice is not a control.

    M5 Checkpoint

    You should be able to:

    • Order a prompt for caching (tools, system, stable documents, then dynamic content) and place breakpoints.
    • Diagnose a cache that never hits using the minimum size, volatile prefix content and the usage fields.
    • State what invalidates a cache and why edits to a static prefix should be batched into releases.
    • Compute cached versus uncached cost with a write premium and a read discount, and find the break-even number of reuses.
    • Choose between synchronous calls and the Batch API, and say what batching trades away.
    • Route by task with an evaluation guarding quality, and compare per segment.
    • Separate TTFT from generation time and explain why streaming changes only perceived latency.
    • Parallelise independent steps, reason about tail latency, and use composite tools to cut round trips.
    • Compare options by cost per completed task, not cost per call.
    • Build a cost forecast from volume, tokens per request, prices and hit rate, and show how a hit-rate range changes it.
    • Compute the cost of a router and of a cascade, including the double cost of escalated requests, and say what makes a cascade check trustworthy.
    • Read the usage fields to diagnose a cache by pattern, and place checkpoints to cut time to first token in a conversation.
    • Enforce per-tenant budgets with metering, atomic reservation, graduated degradation and per-task caps.
    • Tune reasoning effort per task type against a latency target, with a per-segment evaluation.

    Where to verify

    Documentation read while writing this module (check them for current prices, multipliers and minimum sizes, which this lesson deliberately does not quote):

    Enroll to keep reading

    Lesson 6 of 10 · Claude Certified Developer — Professional

    Prompt caching, the Batch API, model routing, time to first token versus generation time, streaming, parallel calls and cost arithmetic with worked examples.

    In the rest of this lesson

    • 5.5 Latency: TTFT, generation time and streaming
    • 5.6 Fewer round trips: parallel calls and composite tools
    • 5.7 Prune context and do the arithmetic
    • 5.8 Break-even needs the value of a completed task
    • 5.9 Cost modelling and forecasting
    • 5.10 Routing and cascades

    Enrolling is free. It unlocks every lesson in Claude Certified Developer — Professional, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Free: CCA Foundations cheat-sheet (PDF)

    The domains, the 3 universal rules, core concepts, and exam-day shortcuts — one page. Enter your email and it's yours, plus my weekly AI-architecture notes.

    No spam. Unsubscribe any time.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments