Prompt Caching and Cost Optimisation

Ma Mahalakshmi V Updated 16 Sep 2026
7 min read ·Lesson 57 of 224

Why the Same Prefix Keeps Getting Billed

A great many real applications send requests that share a large, unchanging prefix from one call to the next — Unit 11's agents send the same system instructions on every single turn of a run; Unit 9's file-search-enabled assistant resends the same lengthy tool definitions with every call; a customer support application built on Unit 6's structured outputs sends the same detailed formatting instructions on every request, with only the customer's specific message actually changing. Without any special handling, the platform reprocesses that entire shared prefix from scratch on every request, even though its content — and therefore the computation needed to process it — is identical to the previous call. Prompt caching is the mechanism that avoids repeating this redundant work, and understanding it changes how you should structure a prompt, not just how much a request costs.

What Prompt Caching Actually Does

When a new request's beginning matches the beginning of a recent previous request closely enough, the platform can reuse the internal computation already done for that shared portion instead of redoing it, which is both faster and considerably cheaper for the portion that was reused.

system_instructions = """You are a customer support assistant for Acme Corp.
Always respond in a professional, empathetic tone. Never make promises about
refund amounts without checking the order database first. Format all monetary
values with two decimal places and a dollar sign...""" * 20  # a long, static block

def handle_support_message(client, customer_message: str):
    return client.responses.create(
        model="gpt-5.6-terra",
        input=[
            {"role": "system", "content": system_instructions},
            {"role": "user", "content": customer_message},
        ],
    )

Note: Whether prompt caching is automatic, what minimum prompt length triggers it, how long a cached prefix remains eligible for reuse, and how cache hits are reported can all vary by SDK version and platform configuration. Confirm the current caching behavior against the current official documentation before relying on a specific threshold or savings figure.

Here, system_instructions is identical on every call to handle_support_message(), while customer_message is the only part that actually changes — this is exactly the shape of prompt that benefits from caching, since the large static portion can be reused across every customer interaction instead of being reprocessed each time.

Checking Whether a Request Actually Hit the Cache

A response typically reports how many of its input tokens were served from cache, which is the only reliable way to confirm caching is actually happening rather than assuming it based on prompt structure alone.

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[
        {"role": "system", "content": system_instructions},
        {"role": "user", "content": "Where is my order?"},
    ],
)

cached_tokens = getattr(response.usage, "cached_tokens", 0)
total_input_tokens = response.usage.input_tokens
print(f"{cached_tokens} of {total_input_tokens} input tokens were served from cache")

Note: The exact field name reporting cached token counts (cached_tokens here, or an equivalent under a different name) and where it appears on the usage object can vary by SDK version. Confirm the current field name against your installed SDK version's documentation.

Measuring this directly matters because caching eligibility depends on details — exact prefix match, recency, minimum length — that aren't always obvious from reading the prompt alone; an application that assumes it's benefiting from caching without ever checking cached_tokens might be paying full price for every request without realizing it.

Structuring a Prompt to Maximize Cache Reuse

Caching works by matching an identical prefix — the shared beginning of a request — so the order in which content appears in a prompt directly determines whether caching can help at all.

# Cache-friendly: static content first, dynamic content last.
def build_cache_friendly_prompt(customer_message: str) -> list:
    return [
        {"role": "system", "content": system_instructions},  # identical every time
        {"role": "user", "content": customer_message},         # changes every time
    ]

# Cache-defeating: dynamic content inserted before the static block.
def build_cache_defeating_prompt(customer_message: str, timestamp: str) -> list:
    return [
        {"role": "system", "content": f"Current time: {timestamp}\n\n{system_instructions}"},
        {"role": "user", "content": customer_message},
    ]

build_cache_defeating_prompt() looks almost identical to the cache-friendly version, but inserting a changing timestamp at the very beginning of the system message means the prefix is different on every single call — even though 99% of the system message's content is unchanged, the part that matches for caching purposes is the literal beginning of the string, and that beginning now differs every time. This is a subtle but consequential mistake: any content that changes between calls needs to go after the static portion, never before or inside it, for caching to have any effect.

Prompt Caching Is One Lever Among Several

Caching reduces the cost of reprocessing an unchanged prefix, but it doesn't address every source of cost in an application, and treating it as the only lever worth pulling misses several others that are often more impactful.

OptimizationWhat It ReducesWhen It Applies
Prompt cachingCost of reprocessing an unchanged prefixAny prompt with a large, stable shared portion across calls
Choosing a smaller model for simpler tasksPer-token cost directlyA sub-task (Unit 8's tool-selection step, a simple classification) that doesn't need the largest model's full capability
Lower reasoning effort (Unit 3)Cost and latency from internal reasoning tokensA task that doesn't benefit from extensive internal reasoning
Capping max_output_tokensCost of runaway or unexpectedly long generationsAny request where an unbounded response isn't actually needed
The Batch API (Lesson 5)Per-token cost for non-time-sensitive bulk workLarge volumes of work with no immediate latency requirement
Trimming unnecessary contextInput token count directlyA prompt carrying more history or documents than the task actually needs

The most effective cost strategy for most applications combines several of these rather than relying on any single one — a support system, for instance, might use prompt caching for its shared instructions, a smaller model for an initial routing decision (mirroring Unit 11's triage agent), and the Batch API for a nightly summarization job that doesn't need an immediate response.

Trimming Context That Doesn't Earn Its Cost

Beyond caching what's already necessary, it's worth periodically checking whether everything currently being sent is actually needed — Unit 4's conversation state and Unit 9's retrieved documents both accumulate naturally over time, and neither automatically shrinks back down once it's no longer relevant.

def trim_conversation_history(messages: list, max_messages: int = 10) -> list:
    """Keep a system message (if present) plus only the most recent turns,
    rather than sending an ever-growing, mostly-irrelevant history."""
    system_messages = [m for m in messages if m["role"] == "system"]
    other_messages = [m for m in messages if m["role"] != "system"]
    return system_messages + other_messages[-max_messages:]

A long-running conversation that keeps every prior turn (as Unit 4's naive conversation-history examples did, before that unit introduced previous_response_id as an alternative) pays to reprocess an ever-larger amount of increasingly irrelevant context on every single turn — trimming to a bounded recent window, or relying on the platform's own conversation-state mechanism instead of resending full history yourself, keeps input size (and therefore cost) from growing unboundedly over a long session.

Common Mistakes

Placing dynamic content before or inside a prompt's static portion, defeating prompt caching entirely even though the majority of the prompt's content doesn't actually change between calls.

Assuming caching is happening without checking cached_tokens on the response, potentially paying full price for every request while believing costs are already optimized.

Treating prompt caching as the only available cost lever, missing larger savings available from model selection, reasoning effort, output length limits, or the Batch API for suitable workloads.

Sending an ever-growing, untrimmed conversation history on every turn, paying to reprocess increasingly irrelevant context as a session lengthens.

Best Practices

Structure prompts with static, shared content first and call-specific content last, preserving an identical prefix across calls so caching can actually take effect.

Measure actual cache hit rates from the response's usage data, rather than assuming a particular prompt structure is being cached without confirming it.

Combine multiple cost optimizations rather than relying on caching alone — model choice, reasoning effort, output limits, and batching each address a different source of cost.

Periodically trim conversation history and retrieved context to what the current turn actually needs, rather than letting input size grow unboundedly over a long-running session.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Prompt Caching and Cost Optimisation and get answers drawn from it.

Signed-in readers only.