Every conversation about "getting AI to answer questions about our documents" reaches the same fork in the road. Someone suggests building a RAG, with a vector databaseDatabase that stores embeddings and quickly finds those closest to a query, the basis of meaning-based search. Examples: pgvector in Postgres, Qdrant, Pinecone., embeddingsList of numbers that represents the meaning of a text. Similar texts produce nearby lists, which lets you search by meaning, not just matching words. and an indexing pipeline. Someone else points out that models now read 1 million tokens at once and asks: why not just paste everything into the prompt?
Both are right, in different cases. I run two RAGs in production, one to study my MBA classes and another to answer questions about an agency's website, and with both I've asked myself whether I built too much infrastructure. This article is the answer I wish I'd read first: what each technique is, what the papers actually measured, what it costs and how to decide.
What RAG Is
RAG means letting the model check the library before it answers. The model knows nothing about your internal handbook, so when a question arrives, a retriever finds the passages that look relevant and pastes them into the prompt along with the question. The model answers by reading only what came in.

The term comes from the paper "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks", by Patrick Lewis and eleven other authors, accepted at NeurIPS 2020 (arXiv). The idea was to combine two memories: the parametric one, which is what the model learned in training, and a non-parametric one, "a dense vector index of Wikipedia", queried by a neural retriever. With that, the model could answer with facts that weren't in its weights, and it beat the state of the art on three question-answering tasks.
Today's RAG has two phases:
- Indexing, once per document. You split the documents into chunksSplitting documents into smaller pieces before creating embeddings, so search returns only the relevant part and it fits in the model context., turn each chunk into a vector of numbers with an embedding model and store everything in a vector database.
- Querying, on every question. The question also becomes a vector, the database returns the k closest chunks, the system builds the prompt and the model answers, ideally citing where it got the information.
What CAG Is
CAG flips the logic: instead of searching on every question, you load the whole corpus into the context once and reuse that processing for every question that follows. There's no retrieval step, because the model is already looking at everything.
The name comes from the paper "Don't Do RAG: When Cache-Augmented Generation is All You Need for Knowledge Tasks", by Brian J. Chan, Chao-Ting Chen, Jui-Hung Cheng and Hen-Hsen Huang, published in December 2024 and accepted as a short paper at the Web Conference 2025 (arXiv). The method has three steps:
- Preloading. The documents go through the model once and the intermediate result of attention, the KV cache, is stored in memory or on disk.
- Inference. Each question is appended to the cache and the model answers without searching for anything.
- Reset. After the answer, the system truncates only the question's tokens and the cache goes back to its original state, ready for the next one.

The reference code is on the authors' GitHub (hhhuang/CAG), using Llama 3.1 8B. The README itself states the rule that decides everything: "CAG requires the entire knowledge source to fit within the context windowMaximum amount of text, measured in tokens, that a language model can take into account at once, counting both input and output.".
The Naming Mix-up: Cache or Context?
If you search for "CAG", you'll find two different things under the same acronym.
- Cache-Augmented Generation is the one from the paper above: the whole corpus in the context, no retrieval.
- Context-Augmented Generation shows up in tutorials, like the one on GeeksforGeeks (updated in November 2025). There, the technique enriches each chunk with context (user intent, domain knowledge) before generating the embedding. Retrieval still exists. It's an improved RAG, very similar to Anthropic's Contextual Retrieval, which comes up further down.
In this article, CAG always means the cache one, which is the one with a paper, code and measurements. When someone tells you "let's use CAG", it's worth asking which of the two they mean.
Prompt Caching: The CAG You Already Use Without Knowing It
The paper works directly with the KV cache of an open model running on your own GPU. If you use an APIContract that defines how one program asks another for data or actions: which endpoints to call, what to send and what comes back. On the web, usually HTTP with JSON., you don't get that control, but you get something equivalent: the providers' prompt cachingModel provider feature that stores the repeated start of an already processed prompt, charging less and answering faster on later calls.. You send the same prefix (instructions and documents) across several calls, and the provider reuses its processing and charges much less for it.
| Provider | How to turn it on | Cache read | How long it lasts |
|---|---|---|---|
| Anthropic | cache_control on the block or on the request |
0.1x the input price (0.05x on Opus and Sonnet 5.5) | 5 min by default, 1 h optional |
| OpenAI | automatic above 1,024 tokens | up to 95% off | 30 min or more on current models |
| Google Gemini | implicit from 2.5 onward; explicit with cachedContents |
about 90% below the input price on 3.1 Pro | 1 h by default for explicit, with a storage cost |
Sources, checked in November 2026: Anthropic, OpenAI and Google. On Anthropic, writing to the cache costs 1.25x the input price (2x with the 1-hour duration), so the cache pays for itself from the second read on.
The window grew too: Claude 5.5, GPT-6.x and Gemini 4 accept around 1 million input tokens, according to each provider's model pages. In practice, a CAG over the API looks like this:
import anthropic
client = anthropic.Anthropic()
manual = open("support-handbook.md").read() # the fixed corpus
def perguntar(pergunta: str) -> str:
resp = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=800,
system=[
{"type": "text", "text": "Answer only based on the handbook below. If it's not there, say you don't know."},
{"type": "text", "text": manual, "cache_control": {"type": "ephemeral"}},
],
messages=[{"role": "user", "content": pergunta}],
)
print(resp.usage.cache_read_input_tokens) # tokens read from the cache
return resp.content[0].textThe golden rule is ordering: what doesn't change comes first, what changes comes last. A timestamp or an order id at the top of the prompt invalidates the cache on every call.
What the Papers Measured (and What They Didn't)
CAG won on quality in most tests, but not all of them. In the paper, CAG had the highest BERTScore in most SQuAD and HotPotQA configurations. On small HotPotQA it scored 0.7951 against 0.7676 for the best RAG with BM25. On large HotPotQA, with 64 documents and about 85 thousand tokens, it lost: 0.7407 against 0.7535. The authors say the advantage shrinks as the text grows.
The speed gain is against pasting everything without a cache, not against RAG. On large HotPotQA, CAG generated the answer in 2.26 s, against 92.08 s for sending the whole context without a cache. Dense RAG with the top 3 passages took 0.41 s of retrieval plus 0.93 s of generation. RAG was still faster. A lot of writing about CAG quotes the "92 seconds" and forgets that row of the table.
Long context tends to get more right, and RAG costs much less. A study presented at EMNLP 2024 compared the two approaches with Gemini 1.5 Pro, GPT-4o and GPT-3.5 Turbo (Li et al.). With enough resources, long context won on average by 7.6% on Gemini and 13.1% on GPT-4o. But about 63% of the questions got the same answer with both. Their proposal, Self-Route, lets the model decide: it tries RAG and only falls back to long context when RAG isn't enough. That cut cost by about 65% on Gemini and 39% on GPT-4o, losing little in quality.
The middle of the context is a blind spot. The paper "Lost in the Middle" showed that models get more right when the information is at the beginning or the end of the context, and do worse when it sits in the middle, including models built for long context (Liu et al., TACL 2024). For CAG, this means "fits in the window" doesn't guarantee "gets read carefully".
Side-by-side Comparison
| RAG | CAG | |
|---|---|---|
| Retrieval step | yes, on every question | no |
| Corpus size | practically unlimited | has to fit in the window, with room to spare |
| Updates | reindex only what changed | recompute the cache |
| Per-user permissions | filter in the search | one cache per access group, or none |
| Citing the exact passage | natural, you know what went in | possible, but the model has to point to it |
| Infrastructure | embeddings, vector database, pipeline | just the prompt and the provider's cache |
| Cost per question | low and stable | grows with the corpus, drops with the cache |
| Where it usually fails | retrieval doesn't bring the right passage | right passage lost in the middle of a lot of text |
When to Use Each One
Anthropic itself gives the yardstick in its Contextual Retrieval article: if the knowledge base is under 200 thousand tokens, roughly 500 pages, you can put everything in the prompt with prompt caching and skip RAG (Anthropic, 2024).
In my MBA study RAG, RAG made sense for two reasons the table shows: the corpus grows every week with class transcripts, PDFs and images, and I filter the context by subject, tag and period before asking. In the website one, the pages rarely change, and what helped me most was reindexing only what changed, by comparing each page's hash. If I were starting the website one today, I'd try a CAG first.
The RAG Ecosystem
RAG isn't a single piece. These are the choices that change the result the most:
- Chunking. The size and the cut of the chunks. Splitting in the middle of a sentence or separating an FAQ question from its answer is the most common mistake, and no expensive model makes up for it.
- Embeddings. The model that turns text into vectors. It has to be the same at indexing and query time; if you switch, you reindex everything.
- Vector database. If you already have Postgres, pgvector covers a lot of cases: it's at version 0.8.7, has HNSW and IVFFlat indexes and indexes up to 2,000 dimensions with the
vectortype. Qdrant, Pinecone and Weaviate are dedicated alternatives. - Hybrid search. Combining vector search with keyword search (BM25 or Postgres full-text) helps with proper names, codes and acronyms, which embeddings get confused by.
- Reranking. A second model reorders the candidates and only the best ones go into the prompt.
- Contextual Retrieval. Before the embedding, an LLMAI model trained on large amounts of text to predict the next word, which lets it chat, summarize, translate and write code. writes a sentence of context for each chunk ("this passage is from the returns section of the 2026 policy"). In Anthropic's tests, this cut retrieval failures by 35%; with contextual BM25, by 49%; adding rerankingSecond search stage where a more precise model re-scores the retrieved passages and reorders them by relevance, keeping only the best for the final model., by 67%.
- GraphRAG. Microsoft proposed using the LLM to build a knowledge graph and summarize communities of entities, for questions about the whole corpus ("what are the main themes?"), which chunk-based RAG answers poorly (Microsoft Research, 2024).
- Evaluation. RAGAS measures retrieval (context precision and context recall) and the answer (faithfulness, which is the share of statements supported by the context). Without a set of questions with expected answers, you don't know whether a chunking change made things better or worse.
A vector search in pgvector fits in a few lines of SQL:
-- the 5 passages closest to the question, by cosine distance
SELECT id, conteudo, 1 - (embedding <=> $1) AS similaridade
FROM trechos
WHERE usuario_id = $2 -- permissions go into the search
ORDER BY embedding <=> $1
LIMIT 5;
The Hybrid Path
Systems that work well are rarely pure. Three designs come up a lot:
- Cached fixed prefix + retrieval for the rest. Instructions, glossary and the main rules stay in the prompt with caching; detailed manuals and history come through RAG.
- Routing. Like Self-Route: the system tries the cheap path and only escalates to long context when the answer doesn't hold up.
- An agent that decides. The model gets a search tool and chooses when to query, how many times and with which terms. This is what many people call agenticUse of language models that plan, call tools and decide the next step on their own to reach a goal, instead of only answering a question. RAG. If that kind of autonomy is still new to you, the difference between an AI agent and a chatbot helps; and if the search is exposed as a tool for other assistants, the MCP vs API discussion comes in.
The CAG authors themselves point to the hybrid as the next step: "hybrid approaches that combine preloading with selective retrieval".
Pitfalls
- A cache that never hits. A date, the user's name or an id at the start of the prompt changes the prefix and wipes the cache. Check the tokens read from the cache on every response.
- A shared cache with personal data. In CAG, everyone using the same prefix sees the same corpus. Data that depends on permissions doesn't go there.
- A corpus that "fits" right at the limit. Fitting 950 thousand out of 1 million tokens isn't fitting. There's little left for the conversation, and the middle of the context gets read worse.
- RAG without evaluation. Changing the embedding model, the chunk size or k without a set of test questions is working in the dark.
- Assuming CAG is always faster. The first call pays for the full preload, and the paper shows RAG faster on the large corpus.
Tools to Try
- Ollama, to run an open model and an embedding model on your own machine, with no per-token cost.
- Hugging Face, to pick embedding and reranking models and look at the public leaderboards.
- Crunchy Postgres Playground, to practice SQL in the browser before setting up your own Postgres.
To see where RAG and CAG fit into the work of people building products with AI, read the types of AI engineering. And if all you want is to give documents to a ready-made assistant, with no code, a custom GPT already runs a managed RAG for you.
Quick check
Frequently Asked Questions
What does CAG mean in AI?
In most technical writing, Cache-Augmented Generation: the whole corpus goes into the context once and the processing stays cached for the next questions. Some tutorials use the same acronym for Context-Augmented Generation, which is RAG with extra context in each chunk.
Does CAG replace RAG?
No. It replaces RAG when the corpus is small, stable and the same for everyone. For a large, dynamic corpus or one with per-user permissions, RAG is still the option, and many systems use both together.
Which is cheaper, RAG or CAG?
It depends on volume. CAG removes the retrieval infrastructure, but sends the whole corpus on every call, even with the cache discount. RAG sends only a few passages, so it usually ends up cheaper when there are many questions about a large corpus.
Up to what corpus size is CAG worth it?
Anthropic suggests putting everything in the prompt when the knowledge base is under 200 thousand tokens, about 500 pages. Above that, test with real questions: the CAG paper shows the advantage dropping as the text grows.
Is prompt caching the same thing as CAG?
It's how you do CAG when you use a model through an API. The paper stores the model's KV cache directly; prompt caching does the equivalent on the provider's side and charges less for the reused tokens.
Does RAG eliminate hallucinations?
It reduces them, but doesn't eliminate them. If retrieval brings the wrong passage, the model answers confidently based on it. That's why it's worth measuring answer faithfulness and retrieval precision, for example with RAGAS.
Do I need a dedicated vector database to do RAG?
Not necessarily. If you already use Postgres, the pgvector extension stores the vectors in the same database and lets you filter by user in the query itself. A dedicated database starts paying off at much larger volumes.
What is agentic RAG?
It's when the model gets retrieval as a tool and decides on its own when and how to query, instead of the system always searching before each answer. It gives more flexibility, at the cost of more calls and behavior that's harder to predict.
References
- Patrick Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, NeurIPS 2020.
- Brian J. Chan, Chao-Ting Chen, Jui-Hung Cheng and Hen-Hsen Huang, Don't Do RAG: When Cache-Augmented Generation is All You Need for Knowledge Tasks, WWW '25, 2024/2025, and code.
- Zhuowan Li et al., Retrieval Augmented Generation or Long-Context LLMs? A Comprehensive Study and Hybrid Approach, EMNLP 2024.
- Nelson F. Liu et al., Lost in the Middle: How Language Models Use Long Contexts, TACL, 2024.
- Anthropic, Introducing Contextual Retrieval, 2024, and Prompt caching, accessed in 2026.
- OpenAI, Prompt caching, accessed in 2026.
- Google, Context caching in Gemini, accessed in 2026.
- Microsoft Research, GraphRAG: Unlocking LLM discovery on narrative private data, 2024, and Darren Edge et al., From Local to Global: A Graph RAG Approach, 2024.
- pgvector, version 0.8.7, accessed in 2026.
- Ragas, available metrics, 2025.
- GeeksforGeeks, Context-Augmented Generation (CAG), 2025. Introductory; uses the acronym for a different technique.
- Book: Chip Huyen, AI Engineering: Building Applications with Foundation Models, O'Reilly, 2025. Chapter 6, "RAG and Agents", is the best overview I know of on how to build and evaluate a RAG.