Skip to content

RAG vs CAG: what each one is, how they differ and when to use them

Retrieval-Augmented and Cache-Augmented Generation explained with flow diagrams: how each works, what the papers measured, prompt caching, pgvector, costs and when to combine them.

Ramon Gomes 19 min read Level: Intermediate

Also available in: Español, Français, Português

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.

Person seen from behind in an old library, wearing a cardigan, pulling three yellowed index cards from a wooden card catalog drawer; next to them, a metal cart full of books
RAG is the card catalog: for each question, you go to the drawer and pull only the cards that seem useful. If the right card is in the wrong drawer, the answer comes out without it.

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:

  1. 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.
  2. 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.
RAG infographic in three panels: at the top, documents, chunks of 300 to 800 tokens, embeddings and a vector store; in the middle, a question, retrieval of the k most similar chunks and an assembled prompt; below, the LLM reads the retrieved chunks and produces an answer citing its source.
The left column runs once per document. The right one runs on every question, and retrieval is where everything can go right or wrong.

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:

  1. Preloading. The documents go through the model once and the intermediate result of attention, the KV cache, is stored in memory or on disk.
  2. Inference. Each question is appended to the cache and the model answers without searching for anything.
  3. 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.
Student's desk during an open-book exam: an open ring binder, handwritten notes marked with colorful sticky notes, an uncapped highlighter and a half-empty cup of coffee; the person writes, out of focus
CAG is the open-book exam for someone who studied beforehand: all the material is already open on the desk. It works as long as the binder fits on the desk.

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.".

CAG infographic in two panels: at the top, the whole corpus fits with room in the context window, is precomputed and stored in cache; below, each question joins the cache and goes through the LLM, which sees the whole corpus and answers quickly after the first access, without retrieval. If the corpus changes, the cache must be rebuilt.
The left side runs once. The right side runs many times over the same cache, which is why it's faster after the first access.

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:

python
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].text

The 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

Diagram with four questions in sequence for choosing between RAG and CAG: whether the corpus fits in the context, whether it changes all the time, whether each user only sees part of it and whether you need to cite the exact passage
Four questions settle most cases. If they all lead to CAG, start with it: there's less to maintain.

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 vector type. 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:

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;
Watercolor cartoon: a man in glasses, in a hurry, cuts a thick book into strips with giant scissors while a little robot tries to put the strips together like a puzzle and scratches its head
Rushed chunking: the whole book is there, but no strip has the complete sentence. The model will answer with whatever piece is left.

The Hybrid Path

Systems that work well are rarely pure. Three designs come up a lot:

  1. 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.
  2. Routing. Like Self-Route: the system tries the cheap path and only escalates to long context when the answer doesn't hold up.
  3. 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

1. What is the core difference between RAG and CAG?
Show answer

Answer: RAG retrieves passages on every question; CAG loads the whole corpus once and reuses it

CAG has no retrieval step. The corpus is already in the context and that processing is kept in the cache.

2. An assistant will answer questions about customer emails, and each user only sees their own. Which one?
Show answer

Answer: RAG, with permissions applied as a filter in the search

A corpus that grows every day and depends on permissions calls for RAG. With a shared cache, everyone sees the same corpus.

3. In the CAG paper, the speed gain was measured against what?
Show answer

Answer: Against sending the whole context on every call, with no cache

The big gain is over pasting everything without a cache. On the large corpus, RAG was still faster than CAG.

4. Why does putting the date or an order id at the top of the prompt hurt CAG over an API?
Show answer

Answer: Because the prefix changes on every call, so the cache is never reused

The cache only works for an identical prefix. What never changes goes first, what changes goes last.

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

Source: https://ramongomessilva.com.br/blog/rag-vs-cag-difference-and-when-to-use · Accessed on December 02, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. RAG vs CAG: what each one is, how they differ and when to use them. Ramon Gomes, 20 nov. 2026. Disponível em: https://ramongomessilva.com.br/blog/rag-vs-cag-difference-and-when-to-use. Acesso em: 2 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, November 20). RAG vs CAG: what each one is, how they differ and when to use them. Ramon Gomes. https://ramongomessilva.com.br/blog/rag-vs-cag-difference-and-when-to-use

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026ragvscag,
  author = {Gomes, Ramon},
  title = {{RAG vs CAG: what each one is, how they differ and when to use them}},
  organization = {Ramon Gomes},
  year = {2026},
  month = nov,
  date = {2026-11-20},
  url = {https://ramongomessilva.com.br/blog/rag-vs-cag-difference-and-when-to-use},
  urldate = {2026-12-02}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles