Back to Tutorials
LLM Application Development
Intermediate

Caching LLM Calls: Stop Paying Twice

Run a support bot’s traffic through prompt caching and a semantic cache, and find the settings that save most of the bill and the ones that quietly cost more.

11 minInteractive: drag, click and try things as you read


Language models charge by the token, every time you call them, and most apps send the same tokens over and over: the same instructions, the same documents, often the same questions. Caching means keeping the result of work you’ve already paid for, so you don’t pay for it twice. A cache pays off only when the part you reuse really is the same: byte for byte for the provider’s prompt cache, and in meaning for a cache of answers. Here you’ll run a support bot’s traffic through both kinds and find the settings that save most of the bill, and the ones that quietly cost more.

Where the money goes#

Take the support bot for Hearth, a made-up smart-home brand. Every question a customer asks becomes one request to the model, and each request carries much more than the question:

  • Tool definitions, so the bot can look up orders: about 1,500 tokens.
  • Instructions on tone and what it may and mustn’t do: about 1,000 tokens.
  • The help centre, every article the bot answers from: about 20,000 tokens.
  • The customer’s name, plan and today’s date, and finally the question: about 100 tokens.

The answer is about 300 tokens. At Claude Opus 5.5’s list prices ($4 per million input tokens and $20 per million output tokens), that’s about 9 cents of input and well under a cent of output per question: $97 for every 1,000 questions. More than 90% of what you pay for is the same 22,500 tokens, sent again and again.

There are three ways to stop paying for repeats, from the simplest to the most subtle:

  • An exact-match cache stores each answer under the exact text of the request. An identical request gets the stored answer and never reaches the model.
  • A semantic cache stores answers under the meaning of the question, and reuses one when a new question is similar enough.
  • Prompt caching, offered by the model providers themselves, still answers every question fresh. What it saves is the work of reading the long, shared beginning of the prompt.

Prompt caching: pay once for the beginning#

Before a model writes a word, it processes every token of the prompt. With prompt caching, the provider keeps that processed state for a prompt’s beginning, called its prefix. When a later request starts with exactly the same tokens, the model picks up from the stored state instead of reading them all again. Answers start sooner, and you pay much less for those tokens.

With Claude you mark where the reusable prefix ends with cache_control. The API reads a request in a fixed order, tools first, then the system prompt, then the messages, and the prefix is everything up to your marker. The first request that sends it pays 25% extra to write it to the cache. Every request that finds it there pays just 5% of the normal price on Opus 5.5 (10% on most Claude models) to read it. An entry lasts 5 minutes, and each read restarts the clock. For entries that must survive longer gaps there’s a 1-hour cache, whose writes cost double the normal price.

One catch: the match is exact. A single character that differs anywhere in the prefix means a different prefix, and everything from that character on has to be processed, and written, again.

Predict first

To make the bot friendlier, a colleague moves the customer’s name and today’s date to the very top of the system prompt. At 100 chats an hour, how much does the cache save now?

Try it
A made-up support bot’s traffic, simulated in your browser: chats arrive at random, each with 1 to 3 questions a minute or two apart. Costs use Claude Opus 5.5’s list prices from Anthropic’s pricing page as of October 2026.

With the stable parts first and 100 chats an hour, every question reads the 22,500-token prefix from the cache, and 1,000 questions cost $12 instead of $97: 88% saved, for one line of code. Move the customer’s details to the top and the saving falls to 32% at any traffic level, because chats can no longer share anything. Put everything that never changes first and everything that changes after it, down to the date.

Now slow the traffic down. At 3 chats an hour the 5-minute cache often expires between chats, so only 63% of questions find it, and the saving drops to 47%. The 1-hour cache costs more to write but survives the gaps: 98% of questions read it, saving 84%. Switch it on with the details first, though, and you pay that double-price write for every chat. Caching then costs 3% more than not caching at all.

Other providers do the same: OpenAI, for example, caches long prompt prefixes automatically, with no marker needed. The details and discounts differ, but the rule about putting the stable parts first is the same everywhere.

Semantic caching: reuse the answer#

Prompt caching makes every call cheaper; a cache of answers skips the call entirely, output and all. An exact-match cache is safe but rarely hit, because people seldom type the same words. A semantic cache turns each question into an embedding, a list of numbers that captures its meaning, and reuses a stored answer when a new question’s similarity to an old one passes a threshold. The question is where to set it.

Predict first

Which pair of questions does an embedding model score as more similar: “how long does the doorbell battery last” and “how long does the doorbell take to charge”, or “how much does professional fitting cost” and “can someone install it for me”?

Try it
70 made-up questions to the Hearth bot, in the order they arrived, labelled by which answer each one needs. Similarities come from a real, freely available embedding model (all-MiniLM-L6-v2), computed in advance; the cache is replayed live at every threshold.

At 0.90 the cache reuses 6 answers, 4 of them for questions repeated word for word, and none is wrong. Lower the threshold and the savings grow: at 0.73, 21 of the 70 questions are answered from the cache, still with no mistakes. One step further, at 0.72, three customers asking how long the battery lasts are told how long it takes to charge. At 0.60 almost half the questions are answered from the cache, and 9 of those answers are wrong.

A semantic cache trades accuracy for savings, and the safe threshold depends on your own questions. Here the gap between “no mistakes” and “wrong answers” is a hundredth. With a different mix of questions, it would sit somewhere else. Set the threshold on a sample of your real questions labelled by hand, and keep checking the answers it serves.

  • Cache only answers that don’t depend on who’s asking. “Where is my order?” is the same text from every customer, but has a different answer for each, so even an exact match is wrong here unless the customer is part of the cache key.
  • Expire answers when the facts change. When the price of Hearth Plus changes, every cached answer that mentions it is wrong.
  • Log every reused answer with the question it came from, and review a sample each week.

In code#

Prompt caching with Anthropic’s Python SDK (pip install anthropic; needs an API key). The marker goes on the last block of the stable part, and everything that changes comes after it:

import anthropic

client = anthropic.Anthropic()
HELP_CENTRE = open("help_centre.md").read()   # the same for every customer

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    system=[
        {"type": "text", "text": "You are Hearth's support assistant. Answer from the help centre below."},
        {"type": "text", "text": HELP_CENTRE, "cache_control": {"type": "ephemeral"}},  # cache up to here
    ],
    messages=[{"role": "user", "content": "Customer: Priya, Hearth Plus. Today: 9 October.\n\nHow do I test the smoke alarm?"}],
)
print(response.usage.cache_creation_input_tokens, response.usage.cache_read_input_tokens)

The first call writes the cache; run it again within 5 minutes and cache_read_input_tokens shows the prefix being read instead. For the 1-hour cache, use {"type": "ephemeral", "ttl": "1h"}. And a minimal semantic cache with sentence-transformers (pip install sentence-transformers), free and local, showing the mistake from the figure:

import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")

class SemanticCache:
    def __init__(self, threshold):
        self.threshold, self.vectors, self.answers = threshold, [], []

    def get(self, question):
        if not self.vectors:
            return None, 0.0
        v = model.encode(question, normalize_embeddings=True)
        sims = np.array(self.vectors) @ v
        best = int(sims.argmax())
        return (self.answers[best] if sims[best] >= self.threshold else None), float(sims[best])

    def put(self, question, answer):
        self.vectors.append(model.encode(question, normalize_embeddings=True))
        self.answers.append(answer)

cache = SemanticCache(threshold=0.75)
cache.put("how long does the doorbell battery last", "About four months per charge.")
for q in ["doorbell battery life", "how long does the doorbell take to charge"]:
    answer, sim = cache.get(q)
    print(f"{q!r}: similarity {sim:.2f} -> {answer or 'ask the model'}")
# 'doorbell battery life': similarity 0.87 -> About four months per charge.
# 'how long does the doorbell take to charge': similarity 0.77 -> About four months per charge.

The second answer is wrong: charging takes about five hours. In production you’d store the vectors in a vector database and add expiry, but the threshold problem stays exactly the same.

What to remember

  • Most of an LLM bill is the same long prompt beginning sent again and again; prompt caching bills it at a small fraction of the price when it repeats exactly.
  • Put everything stable first and everything that changes (names, dates, questions) after the cache marker, and match the cache lifetime to your traffic.
  • Semantic caches skip the model call entirely but serve wrong answers once the threshold is too low; set it on your own labelled questions and cache only impersonal answers.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.