Prompt caching cost reduction comes from reusing an identical prompt prefix instead of paying to process that same input from scratch on every request. This guide walks through a production implementation, from measuring your baseline to checking cache usage, calculating savings and avoiding cache misses. It is most useful when many requests share long system instructions, reference material, tool definitions or conversation history. If you are assessing whether this belongs in a broader AI operating plan, start with our AI strategy and solutioning service.
Goal: reduce repeated input work without changing answers
Prompt caching is an inference optimisation. A model provider may retain the internal attention state computed for a prompt prefix, then reuse it when a later request starts with the same prefix. The model still reads the new part of the prompt and generates a fresh response. Caching does not mean storing and replaying an answer.
The practical target is not a particular discount percentage. It is a lower cost per useful task, with no deterioration in answer quality, latency, security or operational reliability. A cache can reduce the bill for repeated input tokens, but it does not discount uncached input, generated output or every model call. Provider rules, model support, token thresholds, cache duration and price multipliers differ. Check the current official Anthropic pricing documentation, OpenAI prompt caching guide and OpenAI API pricing before you set a business case.
This tutorial builds a small, provider-neutral implementation plan. You will finish with a stable prompt layout, instrumented requests, a repeatable test and a cost calculation you can take to finance or an engineering review.
What you need
Before changing production traffic, gather the following:
- A workload with repeated long inputs. Examples include document review, customer support agents with shared policies, code assistants with a common repository guide, and multi-turn workflows that resend conversation history.
- Access to request and response usage metadata from your model provider. You need input tokens, output tokens and cache read or cache write tokens where available.
- A representative test set of real requests, with sensitive information handled under your existing controls.
- A way to record model, prompt version, request timestamp, latency and cost estimate for each call.
- A rollback path. Keep the existing request construction available until the new version passes quality and cost checks.
If the workflow is an agent rather than a single model call, include tool definitions and tool results in your inventory. Our guide to AI agents and automation covers the wider production controls that sit around prompt design.
What prompt caching does not do
Do not treat caching as a way to make a poorly designed prompt cheap. If a prompt includes irrelevant documents, a cache may make their repeated processing cheaper, but the model can still be distracted by them. Caching also does not guarantee a cache hit: the prefix may be too short, change between requests, expire, or reach a different provider path.
It is also distinct from semantic caching. Prompt caching reuses model-side processing for an identical prefix, while semantic caching stores completed responses in an external system and may return a prior response for a sufficiently similar question. Semantic caching changes the answer path and needs its own correctness, privacy and invalidation design. Prompt caching still asks the model to answer the new request.
Step 1: establish a baseline before changing prompts
You need a baseline to tell whether the change saved money or simply shifted costs. Pick a workload that represents normal production use, not an unusually convenient demo. Include busy and quiet periods if request frequency changes across the day.
For each request, capture at least:
| Field | Why it matters |
|---|---|
| Model and provider | Cache behaviour and pricing vary by model and provider. |
| Prompt version | Lets you identify changes that break prefix reuse. |
| Input and output tokens | Shows how much of the bill comes from input versus generation. |
| Cache read and cache write tokens | Separates reused input from newly cached input, where exposed. |
| Request time and latency | Helps diagnose expiry patterns and time to first token. |
| Workflow outcome | Confirms that cheaper requests still complete the task correctly. |
Do not record full prompts in general application logs just to debug caching. Usage fields and a prompt version or prefix hash are often enough. If you need prompt samples, use an approved, access-controlled test environment and follow your data retention rules.
Calculate a baseline cost per completed task, not only cost per request. One task may use several model calls, retries or tool interactions. A lower cost per call can still mean a higher cost per task if caching changes cause more retries or lower answer quality.
Record the baseline for a representative window. For a workflow that processes documents, include the number of documents, number of model calls per document, average input tokens per call, output tokens and failure or retry rate. For an agent, separate the initial user request from subsequent calls that carry shared system context or growing history.
What you should see
You should be able to answer three questions before proceeding:
- How much input is repeated across requests?
- How frequently is that repeated context reused within the provider's cache window?
- What are the current cost and latency per completed task?
If you cannot answer these, instrument first. A cache setting without usage telemetry is a guess, not an engineering result.
Step 2: map your prompt into stable and changing sections
Prompt caching relies on reuse of a matching prefix. In practice, arrange the request from the most stable material at the beginning to the most dynamic material at the end. Any difference near the start can prevent reuse of the text that follows it.
Make an inventory of every part of the model request:
- Tool definitions and output schemas.
- Core system instructions and safety requirements.
- Shared reference material, such as a policy manual or product documentation.
- Tenant-specific or document-specific material.
- Conversation history or intermediate tool results.
- The current question, current time and other request-specific values.
For each part, mark whether it changes per deployment, tenant, document, conversation or request. Then decide where it belongs in the sequence. A typical layout looks like this:
| Order | Content | Expected change rate | Treatment |
|---|---|---|---|
| 1 | Tool schemas and response format | Rarely | Keep deterministic and early. |
| 2 | Core system instructions | Rarely | Version and keep stable. |
| 3 | Shared reference documents | Occasionally | Place after core instructions. |
| 4 | Tenant or case material | Per tenant or task | Add after shared context. |
| 5 | Conversation and tool history | Per session | Preserve when reuse is beneficial. |
| 6 | Current question and live values | Every request | Keep at the end. |
This is a starting pattern, not a universal provider specification. Some APIs expose explicit cache breakpoints. Others cache matching prefixes automatically. Follow the model's current request format and limits in its official documentation.
Keep request construction deterministic
Equivalent-looking content is not necessarily an identical prefix. Whitespace, punctuation, object ordering, serialisation and tool schema changes can alter the token sequence. Use a single prompt builder rather than assembling the system prompt differently across services.
For structured data, serialise objects consistently. Sort keys where the API accepts ordinary JSON objects, and avoid including values that change on every request in an early section. Keep a version identifier in your application metrics. You usually want a version change when instructions genuinely change, but not an accidental version bump from a deployment timestamp.
A common cache breaker is a live timestamp at the start of the system instruction. Move it to the request-specific tail unless the model truly needs it as part of the policy. The same applies to random IDs, request IDs, changing experiment labels and dynamic user details.
What you should see
Log a safe prefix fingerprint for the stable section, such as a cryptographic digest produced in your application. For repeated calls intended to reuse the same context, the fingerprint should remain unchanged. The fingerprint is a debugging aid. It is not a security boundary, a provider cache key guarantee or proof that the provider will return a cache hit.
Step 3: choose a cache boundary and provider behaviour
Some providers allow you to request caching explicitly at a selected boundary. Others detect eligible repeated prefixes automatically. The first implementation decision is therefore not simply whether to enable caching. It is where reusable content ends and dynamic content begins, and what the provider reports for that request.
Read the current API documentation for the exact model you plan to use. Verify:
- Whether caching is automatic, explicit or both.
- Minimum eligible prefix length and any constraints on cache placement.
- Cache duration, refresh behaviour and whether an extended duration costs more to write or retain.
- How the response reports cache reads and writes.
- Whether caching works with the API endpoint, tools, image inputs or batch mode you use.
- Whether the feature behaves differently across model versions or regions.
For example, the OpenAI prompt caching guide describes the provider's own caching behaviour and usage reporting. Anthropic's pricing documentation is the place to verify the model-specific cache read and write rates. Do not copy a multiplier from an old blog post into a current forecast. The pricing page and API schema for the model you actually call should be the source of truth.
If you use explicit breakpoints, place them after content that will be reused together. A breakpoint that is too early may omit valuable stable reference material. One that is too late may include volatile content that changes on every call. If the provider supports more than one boundary, start with the simplest design that reflects a real reuse pattern. Multiple breakpoints add operational complexity and should earn their place in measured results.
A worked cost calculation using normalized units
Here is a way to evaluate the economics without assuming a current dollar price. Suppose a workload sends 50,000 reusable prefix tokens and 2,000 changing tokens on each of 25 requests. Use the illustrative multipliers from the supplied research notes: one cache write costs 1.25 times the ordinary input rate, and a cache read costs 0.10 times that rate. These are example assumptions, not a current provider quote. Confirm actual rates against the official pricing page for your model.
Let one ordinary input token cost one unit. Without caching, the workload sends 52,000 input tokens 25 times:
- Uncached input: 52,000 × 25 = 1,300,000 token-equivalent units.
- Cached prefix write: 50,000 × 1.25 = 62,500 units.
- Cached prefix reads: 50,000 × 0.10 × 24 = 120,000 units.
- Changing suffix: 2,000 × 25 = 50,000 units.
- Cached total: 232,500 units.
Under those assumptions, input cost falls by about 82 per cent: (1,300,000 - 232,500) ÷ 1,300,000. The output cost is unchanged in this calculation because the number of generated tokens has not changed. The estimate also assumes all 24 reuse requests hit the cache. If some miss, calculate the actual result from usage metadata rather than applying this theoretical percentage to your forecast.
This model helps you see why prefix length and reuse matter. It also shows why an impressive discount on cached tokens is not the same as the same discount on the full invoice. Output tokens, dynamic input, retries, storage charges where applicable and cache writes all affect the total.
Step 4: implement a controlled request builder
Make the prompt layout an explicit part of your application rather than an informal convention. A small request builder should accept stable and dynamic fields separately, validate them, and produce a consistent request object.
A provider-neutral outline might look like this:
build_request(shared_tools, core_instructions, reference_context,
tenant_context, history, current_question):
tools = canonicalise(shared_tools)
system_prefix = concatenate(core_instructions, reference_context)
variable_context = concatenate(tenant_context, history)
request_tail = current_question
return provider_request(tools, system_prefix,
variable_context, request_tail)
The implementation should do more than concatenate strings. Define the expected order, normalise the formats you control, and make cache boundary placement visible in code review. Where the provider requires a cache-control marker, put it at the intended boundary and test the resulting API request. Do not invent a generic caching parameter. Names and placement differ across APIs.
Keep dynamic values out of the stable prefix. If the model needs today's date, add it to the tail or a later context segment. If a tool schema changes, record that as a new prompt version. If a reference document changes, update the version and accept that the new prefix may need a fresh write.
Avoid modifying content just to create a cache hit. For example, do not preserve outdated policy text because it is warm. Correctness and access control take priority over reuse. The cache is an optimisation of valid context, not a reason to serve stale context.
What you should see
In a local request inspection, the stable sections should appear in the same order and with the same serialisation on repeated calls. Dynamic values should appear only after those sections. The provider request should contain the intended cache instruction or qualify for automatic matching according to its documentation.
Step 5: test cache behaviour with a repeatable sequence
A single request cannot demonstrate a cache hit. Design a test that sends the same eligible prefix more than once, with the same model, endpoint and relevant request structure. Change only the question or other content you intentionally placed after the prefix.
Use a sequence like this in a non-production environment:
- Send a request with the target prefix and record usage metadata. This may create the cache entry or may not qualify, depending on provider rules.
- Send a second request with the same prefix and a different tail, within the provider's documented cache window.
- Record cache write tokens, cache read tokens, ordinary input tokens, output tokens and latency for both calls.
- Repeat after a prompt version change to confirm that changed stable content produces the expected new behaviour.
- Repeat after a delay that exceeds the documented cache duration to understand expiry in your workload.
- Run the same test with a dynamic timestamp or reordered schema in a test branch. Confirm that the change affects the cache indicators as expected.
Keep the test isolated from unrelated variables. Do not change model, region, endpoint, prompt layout and cache settings all at once. If the provider's cache is best-effort or load-dependent, repeat the sequence and record variation rather than assuming one hit proves reliable production performance.
Look for provider-reported usage fields, not an inference from latency alone. The research notes identify fields such as cache_read_input_tokens and cache_creation_input_tokens for Anthropic-style responses, prompt_tokens_details.cached_tokens for OpenAI responses, and total_cached_tokens for Gemini usage metadata. Treat those names as examples to verify against the current API schema. Names can change, and wrapper libraries may rename or omit fields.
What you should see
A successful repeat should show eligible tokens counted as cached reads, while the initial request or a changed prefix may show cache creation or ordinary input. Your exact response fields depend on provider and API version. If you see no cache usage, check eligibility, prefix length, request ordering, model support, time between calls and whether your integration preserves the same request structure.
Do not assume a miss means the model did not work. The response may be correct while the cache path is unavailable. Your application needs a normal uncached path and must not depend on caching for correctness.
Step 6: measure savings and latency in production
After a controlled test, release the change to a small share of traffic or a low-risk workflow. Compare matched requests where possible. Measure cost per completed task, not only cached-token share. Include failed calls, retries, output tokens and any tool calls in the total.
Track at least these operational measures:
- Cache read tokens divided by eligible input tokens.
- Cache write tokens and the number of writes per prompt version.
- Total input cost and output cost per completed task.
- Time to first token and end-to-end latency.
- Retry rate, task success rate and quality review results.
- Cache miss rate by model, region, tenant, prompt version and application instance.
Caching can reduce the time spent processing a long input prefix, so time to first token may improve for some workloads. It does not necessarily improve generation speed after the first token. End-to-end impact depends on how much time was spent processing the reusable part, network conditions, provider load and output length. Measure the actual workflow rather than promising a fixed latency improvement.
Use a before-and-after comparison with comparable traffic. If request volume, document size or model selection changed at the same time, separate those effects or you will not know what caused the result. For financial reporting, state the measurement window, the models tested and whether prices are from a current provider rate card or normalized units.
For teams building durable agents, combine cache metrics with tool-level traces, evaluation results and guardrail events. Our MCP server development service covers how model tools and connected systems fit into a production architecture. The exact caching implementation remains specific to the model API.
Step 7: address cache misses, isolation and failure modes
The most common failure is placing volatile data before reusable content. A timestamp, random value, changing user attribute or prompt version inserted near the beginning can change the whole prefix. Move those values later where possible, then confirm the effect in response usage.
Other common causes include:
- Inconsistent serialisation: Tool schemas or structured context are emitted in a different order between services or deploys. Canonicalise the content you control.
- Insufficient reuse: A batch job runs less frequently than the cache duration, so each request writes a new cache instead of reading a warm one. Model the actual schedule against the documented duration.
- Changing large context: Summarising or pruning conversation history on every turn can alter the prefix. Compare the cost of a stable growing history with the cost and quality impact of compaction.
- Model or endpoint changes: A cache created for one supported model or API path may not be reusable on another. Treat model routing as part of the cache design and check provider rules.
- Misreading usage: Cached tokens may be reported separately from ordinary input, or a client library may expose incomplete accounting. Inspect raw usage metadata in a controlled test.
- Unexpected writes: A new prompt version, document or tool schema can generate cache writes. Monitor writes alongside reads so that a cache-heavy workload does not hide an increase in creation cost.
Security needs deliberate treatment. Do not put one tenant's private data into a context that another tenant can access, and do not treat a tenant identifier, hash, cache hit or cache miss as an access-control mechanism. Enforce authorisation before building the request. Keep tenant-specific context separated according to your application and provider configuration, check the provider's current data handling terms, and test for cross-tenant exposure. A prefix hash is useful for comparing requests, but should not be presented as proof of isolation.
For regulated workflows, document what information enters the model, who can access it, which provider endpoint processes it, how logs are handled and how stale reference data is invalidated. Australian financial services and insurance teams should align this design with their broader security and operational risk obligations. See our pages on AI for financial services and AI for insurance for the wider sector context.
Step 8: set operating thresholds and a rollback plan
Once the canary is stable, define operating thresholds based on your own baseline. For example, alert when cache reads fall sharply for a high-volume prompt version, when writes rise unexpectedly, or when cost per completed task exceeds the agreed range. Do not choose a universal hit-rate target without considering reuse frequency, cache duration and the share of total cost represented by the prefix.
Include these checks in release and incident processes:
- A prompt change includes a version change and an expected cache impact.
- Deployment testing checks request order and usage metadata.
- Model or endpoint migrations run a cache and cost comparison.
- On-call dashboards show usage fields and latency by prompt version.
- Rollback restores the prior prompt builder or disables explicit cache markers where appropriate.
If a provider changes pricing or cache rules, update the calculation before changing traffic. The official pricing pages are the authoritative reference for current rates. A third-party explanation can help with intuition, but should not replace the provider's documentation. For example, AWS's overview of Bedrock inference cost choices explains that cost depends on more than one request setting; verify the specific caching behaviour and price in the current service documentation for your chosen model.
A practical 30-day rollout
Days 1 to 5: baseline. Select one repeated-context workflow. Add usage and latency logging, establish prompt versions and calculate current cost per completed task.
Days 6 to 10: restructure. Move stable content earlier and dynamic content later. Make serialisation deterministic. Review the proposed layout for security and correctness.
Days 11 to 15: test. Run repeated calls with a controlled prefix. Verify cache read and write indicators, expiry behaviour and output quality. Compare actual usage with the expected calculation.
Days 16 to 23: canary. Route a limited, representative share of production requests through the new builder. Watch cost per task, latency, cache usage, failures and quality.
Days 24 to 30: decide. Expand only if the measured economics and quality support it. Record the model, price source, test window, assumptions and rollback approach. If results are mixed, inspect misses and request patterns before expanding.
The schedule is a working template, not a delivery guarantee. A sensitive or complex workflow may need a longer test period, a formal risk review or additional evaluation.
Where PADISO fits
Prompt caching is one part of production AI engineering. We help teams assess where the savings are real, instrument model usage and build the surrounding agents and controls through our AI agents and automation service. The first step is to map one workload's repeated context, current usage and success criteria, then test a measured change before scaling it.
Next step
Choose one workflow with repeated long context and establish its cost per completed task before changing the prompt. If you want help deciding whether caching, model routing or a broader workflow redesign is the right next move, take the PADISO AI readiness test.