Prompt Caching for RAG

Cut cost and latency by caching stable system prompts and large documents.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 11 · Lesson 5 of 6 · Intermediate

Prompt Caching for RAG

Cut cost and latency by caching stable system prompts and large documents.

Every RAG request re-sends text the model has seen before: the same system prompt, the same few-shot examples and, in chats, the same growing conversation. Prompt caching lets the API store the processed form of a prompt prefix and reuse it on later requests. Cached input tokens are read at a fraction of the normal input price and are processed faster, which cuts both cost and latency.

How caching works

  • Caching works on a prefix of the request, in this order: tools, then system prompt, then messages.
  • You mark the end of the part to cache with cache_control. The first request writes the cache (at a small premium over the normal input price); later requests with an identical prefix read it at roughly a tenth of the normal input price.
  • The cache lives for 5 minutes by default and is refreshed every time it is used. A 1-hour lifetime is available for traffic with longer gaps, at a higher write price.
  • The match is exact: changing any byte in the prefix (a timestamp, a reordered list) means a cache miss for everything after that point.
  • Prefixes shorter than a model-dependent minimum (from about 512 to 4,096 tokens) are not cached.

What to cache in a RAG system

Part of the promptCacheable?Why
Long system prompt with rules and examplesYesIdentical for every request
Tool definitions (agentic RAG)YesIdentical for every request
A fixed document set (long-context approach)YesThe same documents every time
Conversation history in a chatYesEach turn extends the previous prefix
Retrieved chunks for a new questionRarelyThey differ for each question

Caching the system prompt

cached_rag.py
import anthropic

client = anthropic.Anthropic()

SYSTEM_PROMPT = open("system_prompt.txt", encoding="utf-8").read()   # rules + few-shot examples

def answer(question: str, sources_xml: str):
    response = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=2000,
        output_config={"effort": "low"},
        system=[{"type": "text", "text": SYSTEM_PROMPT,
                 "cache_control": {"type": "ephemeral"}}],          # cache everything up to here
        messages=[{"role": "user", "content": f"{sources_xml}\n\nQuestion: {question}"}],
    )
    u = response.usage
    print(f"cache write={u.cache_creation_input_tokens} read={u.cache_read_input_tokens} "
          f"uncached={u.input_tokens}")
    return response.content[0].text

Run it twice within five minutes. The first call shows a cache write; the second shows a cache read for the system prompt, with only the sources and question billed at the full rate.

Caching a conversation

In a chat, each request contains the whole conversation so far. With automatic caching, you set cache_control at the top level of the request and the API caches up to the last cacheable block, so each turn reuses the previous turns.

def chat_turn(history: list[dict], user_content: str) -> str:
    history.append({"role": "user", "content": user_content})
    response = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=2000,
        output_config={"effort": "low"},
        cache_control={"type": "ephemeral"},        # automatic caching of the growing prefix
        system=SYSTEM_PROMPT,
        messages=history,
    )
    text = "".join(b.text for b in response.content if b.type == "text")
    history.append({"role": "assistant", "content": text})
    return text

Silent cache killers

If cache_read_input_tokens stays at zero across repeated requests, something in your prefix is changing. Common culprits:

  • the current date or time, a request ID or a user's name in the system prompt (put these in the user message instead),
  • dictionaries serialised as JSON without sort_keys=True,
  • a tool list built in a different order on each request,
  • switching models (caches are per model),
  • a prefix below the minimum cacheable length.

How much does it save?

Suppose a support assistant has a 3,000-token system prompt with examples, 2,000 tokens of retrieved chunks and a 50-token question, and receives a steady stream of questions. Without caching, every request pays for 5,050 input tokens at the full rate. With the system prompt cached, about 60% of the input is billed at the cache-read rate (roughly a tenth of full price), so input cost falls by more than half, and time to first token drops too. In long chats the savings are larger, because the history grows while only the newest turn is uncached.

Design for the cache

Order every prompt from most stable to least stable: tools, system prompt, fixed examples, conversation history, retrieved sources, and finally the question. Anything variable that sits before stable content forces cache misses.

Key takeaways

  • Prompt caching reuses an identical prompt prefix for a large discount and lower latency.
  • Cache the system prompt, tools, fixed documents and conversation history; retrieved chunks usually change.
  • Verify with the cache_read_input_tokens usage field.
  • Keep variable data such as dates and IDs out of the cached prefix.