Skip to main content

Claude API Prompt Caching: A Practical Cost-Saving Guide

On this page
  1. Prompt caching reuses the stable prefix, not the previous answer
  2. Pay for the first write, then evaluate repeated reads
  3. Send two requests through APIONE and inspect the usage
  4. Prepare a small working folder
  5. Recognize a write followed by a read
  6. Put cachecontrol after the reusable material
  7. Read the usage buckets before calculating the bill
  8. Calculate with your own group prices
  9. Troubleshoot the observed result
  10. Start with one frequent workflow and keep the working configuration
  11. After caching, review prompts and calibrate reasoning effort
  12. Sources
  13. FAQ
  14. Can I stop sending the fixed background after caching it?
  15. Why can the first cached request cost more?
  16. Does a cache hit guarantee a 90% reduction in the full bill?
  17. Should I choose five minutes or one hour?
  18. How do I check caching through APIONE?

A code-review assistant can send the same project conventions with every file it checks. A document assistant can attach the same long background to each new question. Those materials are useful, but they do not necessarily change between requests. As volume grows, repeated input becomes a separate opportunity for cost optimization.

Prompt caching lets a supported workflow reuse a stable prefix. The first request creates a cache entry; later eligible requests pay the cache-read rate for that part of the input. New questions and new code can still follow the prefix. Start with a frequent workflow containing substantial repetition, rather than removing context that the model actually needs.

This guide uses the Claude Messages API and the APIONE Anthropic-compatible endpoint. The calculations use Sonnet 5.5 standard provider rates as a reference and a fixed illustrative workload. Check the selected APIONE model and group for the actual settlement rates.

Prompt caching reuses the stable prefix, not the previous answer

Consider an assistant that receives coding conventions, API rules, and a different source file on every call. The first two inputs may remain unchanged throughout the day. Keep them at the start of the request and place a cache boundary at the end of that reusable content. The current file or question can appear afterward.

The reused material represents processing of the prefix. It does not substitute an old answer for a new question. The same project instructions can support many different reviews, while the model continues to process new input and generate a fresh response. Output still has its own charge.

Tool definitions can also be stable input in an agent workflow. Keep their ordering and descriptions consistent where the application uses the same tools. Conversation history grows over time, so choose cache boundaries that reflect that structure instead of treating the entire changing request as an immutable prefix.

A stable Claude prompt prefix is written once and reused with different questions

Figure 1: Prefix reuse is not a file-storage API. The client still supplies the relevant content in the required request structure.

The workload determines the opportunity. Repeated questions against a fixed business document can benefit from prefix reuse. A different document used only once offers less repetition to exploit. Do not add irrelevant text merely to raise a cache-hit ratio; organize the information the task already needs.

Pay for the first write, then evaluate repeated reads

Cache writes, reads, and ordinary input are separate billing items. Claude's pricing documentation also lists model-specific read discounts. A remembered discount from an older model should not be applied across every active model.

For Sonnet 5.5, the reference rates per million tokens are $2 for ordinary input, $2.50 for a five-minute cache write, $4 for a one-hour write, $0.10 for a cache read, and $10 for output. The following arithmetic uses those rates. The same method works with the actual prices shown for an APIONE group.

Assume a fixed 50,000-token prefix, 1,000 new input tokens, and 2,000 output tokens on each of 20 requests. Without caching, each call costs $0.102 for input plus $0.020 for output, or $0.122. Twenty calls cost $2.44.

With a five-minute cache, the initial prefix write costs $0.125. Including the changing input and output makes that first call $0.147. Suppose the following 19 requests all read the same prefix within the valid window. Each then pays $0.005 for the prefix and $0.027 for the complete request. The total is $0.147 plus 19 times $0.027, or $0.66.

Example showing separate savings for the reusable prefix and the full request bill

Figure 2: The complete workload falls from $2.44 to $0.66, approximately 73%. The repeated prefix alone falls from $2 to $0.22, an 89% reduction. These percentages describe different scopes.

The first request can therefore cost slightly more. It creates the reusable entry, and later reads determine whether that investment pays off. Looking only at the first write understates the opportunity. Looking only at the read discount overstates savings on a bill that also contains output.

Under the same workload, one initial one-hour write followed by 19 successful reads produces a $0.735 total. A longer validity window has a higher write price. It may suit requests separated by longer intervals, but evaluate actual request timing before selecting it. The longest window is not automatically the lowest-cost configuration.

Send two requests through APIONE and inspect the usage

Copy the precise supported Claude model ID from the APIONE model directory, then use the Anthropic-compatible protocol. With the Anthropic SDK, set the base URL to https://api.apione.ai. Do not append another /v1; the SDK constructs the Messages API path.

The example below marks a stable system content block with an explicit cache boundary. Prepare a UTF-8 file named project-context.txt containing useful project conventions or API documentation. Its token length must satisfy the selected model's cache threshold. Character counts are not token counts, so inspect the model's token accounting rather than guessing from file size.

import os
from pathlib import Path
import anthropic

client = anthropic.Anthropic(
    api_key=os.environ["APIONE_API_KEY"],
    base_url="https://api.apione.ai",
)
model_id = os.environ["APIONE_CLAUDE_MODEL_ID"]
context = Path("project-context.txt").read_text(encoding="utf-8")
system = [{
    "type": "text",
    "text": context,
    "cache_control": {"type": "ephemeral"},
}]

questions = [
    "Explain the project's error-handling conventions.",
    "Using the same conventions, what checks should a new endpoint add?",
]
for question in questions:
    message = client.messages.create(
        model=model_id,
        max_tokens=512,
        system=system,
        messages=[{"role": "user", "content": question}],
    )
    print(message.usage.model_dump_json())

Install the anthropic SDK, set the key and model ID in local environment variables, and run the script with the prepared file. Both calls reuse the same system content and change only the question. Sequential execution makes the initial write and following read easier to inspect than a burst of concurrent requests.

On the first call, inspect cache_creation_input_tokens. On the next, inspect cache_read_input_tokens. Those fields provide the starting evidence for calculating savings. If a client normalizes usage into another schema, reconcile that schema with the platform's usage and billing records instead of guessing from response speed.

The chosen model and delivery path must support the relevant fields. If behavior differs from the expected protocol, retain request identifiers and usage for investigation. Prove a short workflow before adding the configuration to an existing agent, so the source of any change remains easy to locate.

Prepare a small working folder

Download cache-demo.py and project-context.txt into the same folder. The script uses the configuration above and appends each response's usage to usage.jsonl. It records the model, request ID, timestamps, prefix hash and stop reason, without recording the API key, document body or answer. Inspect answer quality separately in your application.

Replace the context template with useful material you already reuse: review requirements, API definitions and test conventions. The supplied short Chinese template illustrates the structure and may be below the selected model's cache threshold. Add relevant project documentation rather than repeating filler text. Keep the file unchanged between the two calls.

With Python installed, open PowerShell in that folder:

python -m venv .venv
.\.venv\Scripts\python.exe -m pip install anthropic
$apiKey = Read-Host "Paste APIONE API Key" -AsSecureString
$env:APIONE_API_KEY = [System.Net.NetworkCredential]::new("", $apiKey).Password
$env:APIONE_CLAUDE_MODEL_ID = "replace-with-the-exact-supported-Claude-model-ID"
.\.venv\Scripts\python.exe .\cache-demo.py

The hidden key prompt avoids placing the literal key in shell history; the running process still receives it through its environment. Replace the model placeholder with the exact available ID. SDK retries are disabled for this diagnostic run. Successful execution makes two billable requests, prints their records and saves usage locally. Rename an existing usage.jsonl before starting a new comparison, so records from different experiments stay separate. Clear the session key afterward with Remove-Item Env:APIONE_API_KEY.

Recognize a write followed by a read

These simplified records are fabricated to explain the fields, not captured from an APIONE account:

{"round": 1, "usage": {"input_tokens": 1000, "cache_creation_input_tokens": 50000, "cache_read_input_tokens": 0, "output_tokens": 2000}}
{"round": 2, "usage": {"input_tokens": 1000, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 50000, "output_tokens": 2000}}

The first call writes a 50K prefix; the second reads it. Real counts can differ, and the first call can already read an entry left by earlier requests. Look for explainable cache reads rather than forcing a particular first-call pattern. A matching prefix_sha256 proves only that this local background text is unchanged. Tools, request structure, model and processing scope also affect reuse. For support, collect adjacent request IDs, times, model and usage; avoid sending keys or full business documents.

Put cache_control after the reusable material

Stable content belongs before changing content. For example, keep project rules and a fixed document in system content, with the current question in the later user message. Request timestamps, random identifiers, and arbitrary user input should generally stay outside the prefix you intend to reuse.

In explicit mode, a content block carries the cache marker and the prefix through that boundary becomes eligible for reuse. Tool definitions can use the documented boundary mechanism as well. Automatic caching uses a top-level setting and its own boundary-selection rules. Establish one clear approach before combining configurations in a complicated application.

Ordering matters in addition to text. Updating a tool definition, moving fixed instructions, or inserting new material into the prefix can change what remains reusable. Version the background file and place genuinely changing information after the boundary. That makes differences between consecutive requests easier to diagnose.

Keep fixed material before the cache boundary and changing request information after it

Figure 3: An input-organization example. Required changing information still reaches the model; it is not removed just to create a cache hit.

A short prefix may not meet a model's minimum cacheable length. Adding a marker alone is insufficient. After meeting that threshold, prefix consistency and timing still matter. Choose substantial background that the workflow already sends repeatedly instead of padding it with duplicated instructions.

The default five-minute window is measured from the start of a write or read request, and hits refresh it according to the service rules. Long response generation consumes part of that interval. Closely spaced interactions are a natural place to start; workflows with longer gaps may justify the one-hour option.

Where supported, an explicit one-hour content-block marker is {"type": "ephemeral", "ttl": "1h"}. Compare the higher write rate with the writes it can avoid. The right decision depends on your timing and reuse pattern, not simply the presence of a longer setting.

Read the usage buckets before calculating the bill

In the native Anthropic Messages API, input_tokens does not necessarily represent all input sent in the request. Ordinary input, cache creation, and cache reads are separate buckets. A call can read an existing prefix and create additional cached content at the same time.

For those native fields, total processed input equals input_tokens + cache_creation_input_tokens + cache_read_input_tokens. Other compatible APIs can report different totals. If an input field already includes cached tokens, adding the cache amount again would overcount usage.

Map ordinary input, cache creation, and cache reads to their respective usage fields

Figure 4: Bucket definitions follow native Anthropic usage. Reconcile another protocol before applying the same arithmetic.

Apply the matching price to each bucket. Creation tokens use the relevant five-minute or one-hour write rate; reads use the read rate; output remains separate. If a request mixes cache lifetimes, inspect the creation breakdown rather than applying one write rate to all newly cached tokens.

Add these fields to existing request logs along with the background version, request start time, and task identifier. Then compare the calculated structure with actual debits using APIONE's billing documentation. Provider list prices are a planning reference; the selected group and settlement rules determine platform charges.

A token-weighted observation can also help: divide cache-read tokens by total processed input tokens. That describes input reuse coverage, not bill reduction. Keep it separate from writes, output, and actual debit. During a cost comparison, preserve the task requirements and output budget. A response that omits required review findings should not be counted as a caching saving.

Evaluate both prefix cost and the full workload bill. If output dominates, caching can still improve input economics while producing a smaller reduction in the total. Reducing unnecessary long answers or avoiding revisions can complement caching without confusing the source of each saving.

A cache-read ratio helps track change, but it is not a bill-saving percentage. Keep two neighboring requests and compare system content, tool definitions, and message prefixes before checking model selection and timing. This leads to a concrete edit rather than repeated requests aimed at improving one dashboard number.

APIONE-style diagnostic checklist for system, tools, message prefixes, model, and cache timing

Figure 5: A diagnostic record structure, without borrowing operational readings from another interface.

Calculate with your own group prices

Download estimate-cost.py and prices.json. Fill all four null values with the selected group's ordinary-input, five-minute-write, read and output prices per million tokens, in one currency. A multiplier alone is insufficient without its underlying billing rules; an unknown price should remain unresolved rather than becoming zero.

.\.venv\Scripts\python.exe .\estimate-cost.py .\usage.jsonl .\prices.json

This script runs offline. estimated_with_cache prices the observed usage; estimated_without_cache prices the same total input at the ordinary-input rate while preserving output volume. This is a same-volume estimate, not a measured uncached control run or a replacement for the platform bill. Tool charges, fixed fees and other modifiers are excluded.

To check the calculator first, download example usage and example prices, then substitute those filenames. The 20 fabricated records produce 2.44 without caching and 0.66 with caching, saving 72.95%. Keep sample records out of production reporting. This calculator handles five-minute writes only and rejects reported one-hour writes; mixed TTLs or a different protocol require a matching calculation.

Troubleshoot the observed result

SymptomCheckNext action
Missing key or model environment variableWhich terminal launched PythonSet the variables in that same PowerShell session
Authentication failure or unavailable modelKey status, exact model ID and group accessVerify in the console rather than guessing model names
No cache fields at allRaw protocol usage and SDK representationResolve the field mapping before treating this as a miss
Both calls write without readsChanging content before the boundaryCompare requests and move dynamic input after the stable prefix
Both write and read counts are zeroModel threshold and parameter supportCount the real prefix and check configuration placement
Reads disappear after a delayRequest start times and cache lifetimeCompare the gap with the TTL before considering a longer window
Intermittent readsModel, project configuration and routing scopeKeep adjacent request IDs and usage for platform diagnosis

Two requests are enough for the initial check; a large burst adds little diagnostic value. A max_tokens stop reason also calls for an output-completeness check before comparing cost or changing the output budget.

Start with one frequent workflow and keep the working configuration

Choose a workflow with repeated background and changing questions, such as project-convention reviews or a fixed product-document assistant. Retain a representative task set, record its uncached behavior, and compare a cached configuration using the same materials.

Separate the initial write from later hits in the log. Measuring only successful reads leaves out setup cost. If the background changes during a test, keep that version's records separate. This makes the comparison useful for deployment rather than selecting one unusually favorable request.

Rollout sequence from a stable prefix to two-call verification and workload billing

Figure 6: A suggested rollout, beginning with your own requests before expanding the configuration.

When read usage remains zero, investigate in a useful order: prefix length, content identity, request interval, and parameter support. Repeated writes without reads can indicate a boundary placed after changing content. A model or processing-environment change also calls for a fresh observation set.

A relay platform manages integration and routing, but reuse still depends on the actual processing scope. APIONE's routing documentation describes conversation affinity for some models. Begin with a selected model and workflow and inspect usage; there is no need to invent a provider-pinning parameter. Request records help the platform investigate unexpected multi-turn behavior.

After deployment, maintain the fixed background as a versioned asset. Update it when business rules change, keep the request organization consistent, and observe new writes and reads. A clearly defined prefix makes costs easier to explain and gives the team a repeatable check when changing models or groups.

After caching, review prompts and calibrate reasoning effort

Caching addresses repeated input; prompt cleanup can reduce unnecessary work. The Anthropic cost-optimization guide puts these opportunities before choices that trade reasoning resources against task performance. Preserve delivery requirements while improving the structure, then compare lower-cost settings.

Prompts often grow as projects accumulate fixes. A fixed multi-round review for every question, or a full analytical report for a simple task, can introduce work that acceptance never required. State the outcome and keep necessary business constraints, error checks, and permission boundaries. Remove repetition that contributes no useful evidence.

Where the relevant Claude API skill is installed, /claude-api prompt-audit can review project prompts in Claude Code; /claude-api cost-optimize provides a broader pass. These are client workflow commands, not APIONE request parameters. The same review can be performed manually when that better fits the project.

Then compare reasoning settings. Tasks with unit tests or clear acceptance rules can trial a lower setting and send failed cases to a higher one. Include escalation calls in the final cost. Open-ended design work should retain a configuration that can complete the task rather than saving on an individual request and adding several revisions.

Change one factor at a time. Establish the cache baseline, revise prompts or effort, and only then decide whether to change models. Keep acceptance constant and compare the cost of an accepted result rather than simply the length of generated text.

Prompt caching lets useful context remain in place while reducing repeated input processing charges. Select a supported Claude configuration in APIONE, verify the usage with two calls, and then compare a representative workload bill. Once that path works, make it part of the normal application configuration rather than a one-off experiment.

Sources

FAQ

Can I stop sending the fixed background after caching it?

The normal Messages API still receives the relevant content in the request structure. Prompt caching is not a document-upload identifier that replaces the full input. Preserve a stable layout and inspect usage for reads.

Why can the first cached request cost more?

It creates the entry at the write rate. Later eligible calls read it at the lower read rate. Include the initial request when deciding whether the complete workflow benefits.

Does a cache hit guarantee a 90% reduction in the full bill?

No. Read discounts apply to eligible prefix tokens, while changing input and output still have charges. The example saves 89% on the repeated prefix and approximately 73% on the full workload. Your usage mix and group rates determine your result.

Should I choose five minutes or one hour?

Compare request spacing, response duration, and write costs. Frequent requests can start with the default window. Longer gaps may benefit from the one-hour option when reduced repeat writes justify the higher initial cost.

How do I check caching through APIONE?

Use a supported Claude request and inspect creation and read usage, then compare platform billing. A zero read on the first call may simply reflect creation. If reads remain zero, check the prefix threshold, identity, timing, and interface support.

One account for every leading AI model.

Chat, create, or build with one API.