Skip to content
RankCore.AI
← All posts

RAG vs CAG: Retrieval-Augmented vs Cache-Augmented Generation, Explained

· RAG, CAG, LLM, KV Cache, AI Engineering

Every company that puts a large language model in front of its own documents runs into the same question: how does the model get to know your knowledge? The model was trained on public data up to a cutoff date. It has never seen your product manual, your HR handbook, your runbooks, or last week's pricing sheet. Something has to put that knowledge in front of the model at the moment it answers.

There are two main architectural answers today. RAG (Retrieval-Augmented Generation) searches for the relevant pieces of your knowledge every time a question arrives. CAG (Cache-Augmented Generation) loads all of your knowledge into the model once, saves the model's internal state, and reuses it for every question. This guide explains how each one works under the hood, what each one costs, where each one fails, and how to choose between them, with working code and a decision checklist at the end.

For the fundamentals of retrieval, embeddings, and vector search, start with our RAG explainer. This article assumes you know what an LLM prompt is and focuses on the trade-off between the two approaches.

A note on the name: CAG is Cache-Augmented Generation

Some infographics expand CAG as "Context-Augmented Generation". The term 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 (arXiv:2412.15605), accepted as a short paper at the ACM Web Conference 2025 (WWW '25). In the paper, the C stands for cache, and that is the important part: the technique is defined by reusing the model's precomputed key-value cache, not just by putting text in the context.

Part 1: How RAG works

RAG was introduced by Lewis et al. in 2020 and has since become the default way to ground LLM answers in private data. It has two phases.

Offline: indexing

  1. Load the source documents (PDFs, web pages, tickets, wiki pages).
  2. Chunk them into passages, typically a few hundred tokens each, often with some overlap so sentences are not cut in half.
  3. Embed each chunk with an embedding model, which turns text into a vector of numbers (for example 768 or 1,536 dimensions) where similar meanings land close together.
  4. Store the vectors with their text and metadata in a vector database or a search index (pgvector, Pinecone, Weaviate, Qdrant, Elasticsearch, OpenSearch and others).

Online: answering a question

  1. Embed the question with the same embedding model.
  2. Retrieve the top-k most similar chunks (often 3 to 20), optionally combined with keyword search (BM25) in a hybrid setup.
  3. Rerank the candidates with a cross-encoder or an LLM, if quality matters more than latency.
  4. Build the prompt: instructions + retrieved chunks + the user's question.
  5. Generate the answer, ideally with citations back to the chunks.
# Minimal RAG loop (pseudocode-level Python)
def answer_with_rag(question: str, k: int = 5) -> str:
    q_vec = embed(question)                       # 1. embed the question
    chunks = vector_db.search(q_vec, top_k=k)     # 2. retrieve
    chunks = rerank(question, chunks)[:3]         # 3. optional rerank
    context = "\n\n".join(c.text for c in chunks)
    prompt = (
        "Answer using only the context below. "
        "If the answer is not there, say you don't know.\n\n"
        f"Context:\n{context}\n\nQuestion: {question}"
    )
    return llm.generate(prompt)                   # 5. generate

What RAG is good at

  • Scale. The model only ever sees a handful of chunks, so the knowledge base can hold millions of documents. Index size is limited by storage, not by the model's context window.
  • Freshness. Updating knowledge means re-indexing the changed documents. No model retraining and no cache rebuild for the whole corpus.
  • Access control. Each chunk can carry metadata (department, customer, clearance level), and retrieval can filter on it, so a user only ever sees passages they are allowed to see.
  • Traceability. Because you know exactly which chunks were sent, you can show sources and audit answers.

Where RAG breaks

  • Retrieval latency on every question. Embedding the query, searching the index, and reranking all happen before the model writes its first token. In practice this adds tens to hundreds of milliseconds, more with rerankers or multiple retrieval rounds.
  • Retrieval errors become answer errors. If the right passage is not in the top-k, the model never sees it. It will either say "I don't know" or, worse, answer confidently from the wrong chunk. Most "RAG hallucinations" are really retrieval misses.
  • Chunking destroys context. A table split across two chunks, a pronoun whose antecedent sits in the previous chunk, or a policy whose exception is three pages later: retrieval sees fragments, not the document.
  • Multi-hop questions are hard. "Which of our plans includes the feature that the enterprise SLA requires?" needs facts from two places. One similarity search often returns only one of them.
  • System complexity. Chunkers, embedding models, a vector database, rerankers, query rewriting, evaluation sets, and re-indexing pipelines are all moving parts that need monitoring.

Part 2: How CAG works

CAG starts from a simple observation: modern LLMs have very large context windows. If your entire knowledge base fits inside that window, you do not need to search it. You can give the model all of it.

The naive version of that idea is "paste everything into every prompt", which works but is slow and expensive, because the model re-reads the whole knowledge base for every question. CAG removes that cost with the KV cache.

What the KV cache is

A transformer processes text token by token. In every attention layer, each token produces a key vector and a value vector. When the model generates a new token, it attends to the keys and values of all previous tokens. Recomputing those for the same prefix again and again is wasted work, so inference engines store them: that store is the key-value (KV) cache.

The expensive step of reading a long prompt is called prefill. For a 100,000-token knowledge base, prefill is where most of the time goes. Once prefill is done, the KV cache captures everything the model "knows" about that prefix.

The three steps of CAG

  1. Preload (offline). Put all knowledge documents into one prompt prefix: instructions plus the full documents.
  2. Precompute the cache (offline). Run a single prefill pass over that prefix and keep the resulting KV cache in memory or on disk.
  3. Answer (online). For each question, append only the question's tokens to the cached prefix and generate. The model pays prefill only for the few dozen question tokens, not for the knowledge base. Between questions, the cache is reset back to the knowledge prefix so one user's conversation does not leak into the next.

There is no embedding model, no vector database, no retriever, and no top-k to tune. The model sees every document in full, in order, for every question.

# CAG with Hugging Face transformers: precompute once, reuse per question
import copy, torch
from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache

model_id = "meta-llama/Llama-3.1-8B-Instruct"
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto")

knowledge = open("handbook.txt").read()
prefix = ("You answer questions using only the handbook below.\n\n"
          f"{knowledge}\n\n")
prefix_ids = tok(prefix, return_tensors="pt").input_ids.to(model.device)

# Steps 1 + 2: one prefill pass over the whole knowledge base
kv = DynamicCache()
with torch.no_grad():
    model(prefix_ids, past_key_values=kv, use_cache=True)

# Step 3: each question reuses a fresh copy of the cached prefix
def ask(question: str) -> str:
    cache = copy.deepcopy(kv)                     # reset to the knowledge prefix
    ids = tok(prefix + f"Question: {question}\nAnswer:",
              return_tensors="pt").input_ids.to(model.device)
    out = model.generate(ids, past_key_values=cache, max_new_tokens=256)
    return tok.decode(out[0, ids.shape[1]:], skip_special_tokens=True)

print(ask("How many vacation days do new employees get?"))

This is a simplified sketch: production code would apply the model's chat template and serve the cache from an inference engine instead of deep-copying it per request. The structure is the point: one expensive prefill, then cheap questions.

What the paper found

The authors compared CAG against RAG pipelines on question-answering benchmarks, including SQuAD and HotpotQA, using a long-context Llama 3.1 8B Instruct model. Their conclusion is that for applications with a constrained knowledge base, CAG achieved comparable or better answer quality than the RAG baselines with less system complexity, and that it eliminates retrieval latency and retrieval errors because nothing is retrieved at question time. Read the paper's numbers as evidence for bounded knowledge bases, not as a claim that retrieval is obsolete.

Where CAG breaks

  • It must fit. The whole knowledge base plus the question plus the answer must fit in the context window. 128K tokens is roughly 90 to 100 pages of English text, which is plenty for a handbook and nowhere near enough for a support archive.
  • Long-context quality is not free. Models do not attend equally well across very long inputs. Facts buried in the middle of a huge context can be missed more often than facts near the start or end. Test with your own documents at your real size.
  • Memory cost. The KV cache is large. See the calculation below.
  • Updates mean rebuilds. Change one paragraph and the cache for everything after that paragraph is invalid. In practice you recompute the cache, which is fine for weekly changes and painful for changes every minute.
  • Weaker access control. Every question sees every document in the cache. If different users may see different documents, you need a separate cache per permission group, or RAG.

Part 3: The KV cache memory math

The KV cache stores one key and one value vector per token, per layer, per key-value head:

bytes per token = 2 (K and V) × layers × kv_heads × head_dim × bytes per number

For Llama 3.1 8B (32 layers, 8 key-value heads thanks to grouped-query attention, head dimension 128) in 16-bit precision:

2 × 32 × 8 × 128 × 2 bytes = 131,072 bytes ≈ 128 KiB per token
Knowledge base sizeKV cache size (Llama 3.1 8B, bf16)
10,000 tokens (≈ 8 pages)≈ 1.25 GiB
50,000 tokens (≈ 38 pages)≈ 6.1 GiB
100,000 tokens (≈ 75 pages)≈ 12.2 GiB
128,000 tokens (≈ 95 pages, full window)≈ 15.6 GiB

That is on top of the model weights (about 16 GB for an 8B model in bf16). Larger models have more layers and bigger caches. This is why CAG suits a single, shared knowledge base served to many users: you pay the memory once and amortize it over every question. Quantizing the cache to 8-bit roughly halves these numbers.

Part 4: CAG with hosted APIs (prompt caching)

You do not need to run your own GPU to use the CAG idea. Major LLM APIs offer prompt caching: when consecutive requests share the same long prefix, the provider reuses the processed prefix instead of reading it again, which lowers latency and bills cached input tokens at a discount.

The design rule is the same as CAG:

  1. Put the static knowledge first, in an identical prefix on every request (same text, same order, byte for byte).
  2. Put the variable part (the user's question, the conversation) after it.
  3. Keep the prefix stable. Any change early in the prefix invalidates the cache from that point on.

Two differences from self-hosted CAG matter. Provider caches are short-lived by default (minutes, often extendable) and are managed for you, so a quiet endpoint may pay the full prefill again. And you still pay per request for the full context window in terms of rate limits and capacity, even when the tokens are discounted. Check your provider's current documentation for cache lifetimes, minimum prefix sizes, and pricing.

Part 5: Side-by-side comparison

RAGCAG
Knowledge sizeMillions of documentsMust fit in the context window
Work per questionEmbed + search + (rerank) + generateGenerate only
Retrieval errorsPossible: wrong or missing chunksNone: model sees everything
LatencyRetrieval adds a step before the first tokenNo retrieval step; fast once cached
FreshnessRe-index changed documentsRebuild the cache
InfrastructureEmbeddings, vector DB, retriever, rerankerLong-context model + cache storage
Per-user permissionsMetadata filters per chunkOne cache per permission group
Multi-hop questionsHard: facts may not be retrieved togetherNatural: all facts are in context
MemoryIndex on disk; small promptsLarge KV cache in GPU memory
CitationsChunk IDs come for freeAsk the model to quote sections

Part 6: When to use which

Choose CAG when

  • The knowledge base is bounded: a product manual, an HR handbook, an API reference, a contract, a course syllabus, a policy library of a few dozen documents.
  • The knowledge is stable: it changes daily or weekly, not every minute.
  • Everyone may see everything in it.
  • Questions often need facts from several places at once, where retrieval tends to miss.
  • You want the simplest system to operate.

Choose RAG when

  • The corpus is large: support tickets, wikis, document archives, e-commerce catalogs, legal databases.
  • The data changes constantly: inventory, prices, news, logs.
  • You need per-user access control at the document level.
  • You must cite exact sources for compliance or audit.

Combine them (hybrid)

Many production systems use both. A common pattern is to cache the core and retrieve the rest:

  • Put the stable, always-relevant material (system rules, product overview, glossary, top FAQs) in a cached prefix.
  • Retrieve long-tail or fast-changing documents with RAG and append them after the cached prefix for each question.

Another pattern is coarse retrieval plus CAG: use search to pick the right document set (for example one customer's contract bundle), then load that whole set into context instead of a few chunks, and cache it if the same set is queried repeatedly.

Part 7: How to evaluate the choice

Do not decide on architecture alone. Measure with your own data:

  1. Build a test set of 50 to 200 real questions with expected answers and the document sections that support them. Include multi-hop questions and questions with no answer.
  2. Measure answer quality: exact or semantic correctness, faithfulness to the source, and whether the system correctly says "not in the documents".
  3. For RAG, measure retrieval separately: how often the supporting chunk is in the top-k (recall@k). Low recall means fix retrieval before blaming the model.
  4. Measure latency: time to first token and total time, at your expected concurrency.
  5. Measure cost: GPU memory or API spend per 1,000 questions, including cache rebuilds or re-indexing.
  6. Test at your real size. CAG at 20,000 tokens and CAG at 120,000 tokens can behave very differently.

Part 8: The same question, both ways

Imagine a 60-page employee handbook (about 80,000 tokens) and this question:

"I joined in March and work part-time. How many vacation days do I get this year?"

The answer depends on three passages: the vacation allowance table in section 4, the part-time proration rule in section 7, and the first-year proration rule in an appendix.

With RAG (top-k = 4): the query embedding is closest to the vacation table and to a FAQ entry about requesting time off. Those two plus two loosely related chunks reach the model. The part-time rule uses different wording ("reduced-hours contracts") and does not score in the top four. The model answers with the full-time allowance, prorated for March. That answer is fluent, sourced, and wrong. Fixing it means query rewriting, hybrid keyword search, a larger k, a reranker, or multi-step retrieval: more parts to tune.

With CAG: all 80,000 tokens are already in the cached context. The model sees the table, the part-time rule, and the appendix together and combines them. Time to first token is short because only the question's few dozen tokens need prefill. The trade-off is the roughly 10 GiB KV cache held in memory for an 8B model and a rebuild whenever HR edits the handbook.

Now scale the scenario up: the same company wants the assistant to also answer from 40,000 support tickets and every customer contract. That is hundreds of millions of tokens, changing daily, with strict per-customer permissions. CAG is no longer possible; RAG with metadata filters is the right tool, and the handbook can stay in a small cached prefix alongside it. That is the hybrid design from Part 6 in practice.

Common mistakes

  • Using RAG for a 30-page handbook. You pay for a whole retrieval stack and still get chunking errors. Try CAG or a cached prompt first.
  • Using CAG for a living knowledge base. If the content changes hourly, constant cache rebuilds erase the latency win.
  • Assuming the context window is the usable limit. Leave room for instructions, the question, the answer, and conversation history.
  • Forgetting to reset the cache between users. Reusing a cache that already contains another user's question leaks data and confuses answers.
  • Ignoring permissions. One shared cache means one shared audience.
  • Skipping evaluation. Both approaches fail quietly. Only a test set tells you which one fails less for your data.

Recap

QuestionAnswer
What does RAG do?Searches your knowledge for each question and sends the best chunks to the model
What does CAG do?Loads all knowledge into the context once and reuses the precomputed KV cache
What is the KV cache?The stored keys and values from attention for every token already processed
CAG's main limit?Everything must fit in the context window, and updates require a rebuild
RAG's main risk?Retrieval misses: the right chunk is not retrieved, so the answer is wrong
Rule of thumbSmall, stable knowledge → CAG. Huge, changing data → RAG. Often: both

RAG and CAG are not rivals so much as two ends of one dial: how much knowledge you put in front of the model, and when you pay to process it. Measure your corpus size, your update rate, and your permission model, and the right setting usually becomes obvious.

Key terms

  • Prefill: the step where the model reads the whole prompt before writing; CAG pays it once.
  • KV cache: stored attention keys and values for every processed token.
  • Context window: the maximum tokens a model can attend to in one request.
  • Top-k: how many chunks RAG retrieves per question.
  • Reranker: a second model that reorders retrieved chunks by relevance.

Sources: Chan, Chen, Cheng, and Huang, Don't Do RAG: When Cache-Augmented Generation is All You Need for Knowledge Tasks, WWW '25, arXiv:2412.15605; Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, NeurIPS 2020.

Follow @rankcore.ai for daily lessons, and read more on blog.rankcore.ai.

Want to go deeper?

Our step-by-step video courses turn these ideas into results.

See courses

Comments

Sign in or create a free account to join the discussion.

No comments yet — be the first.