RAG and CAG answer the same question from opposite ends. Retrieval-augmented generation searches an index at query time and puts the best few chunks in the prompt. Cache-augmented generation skips the search: the whole corpus sits in the prompt prefix, and the model reuses the KV cache instead of reading it again. The one-line difference: RAG decides what the model sees at query time; CAG decides once, at build time. KAG, the knowledge-graph variant that keeps appearing in the same searches, is in the table because it changes what the model can reason about, not just how fast it reads.
RAG vs CAG vs KAG at a Glance
That difference drives cost, freshness and access control. Start with the table, then read the section that matches your constraint.
| RAG | CAG | KAG | |
|---|---|---|---|
| What it does | Embeds the query, searches a vector plus keyword index, reranks, and sends 2k–8k tokens of chunks | Preloads a fixed corpus into a long prompt and reuses its KV cache across queries | Builds a knowledge graph from the corpus, then retrieves entities and relations alongside text |
| Cost at query time | Retrieval, rerank, then full-price input tokens for the chunks | Near-zero prefill on a cache hit and discounted cached input; a miss pays the full prefill | Graph traversal plus retrieval plus a longer reasoning prompt — the most expensive of the three |
| Freshness | Minutes: re-index the changed chunks and the next query sees them | Release cadence: one changed token invalidates the cache from that block onward | Slowest: extraction and graph alignment rerun, not just an embedding update |
| When it wins | Large, live, permissioned or auditable corpora | Stable corpus under ~500k tokens with a tight time-to-first-token budget | Multi-hop questions over numbers, dates, rules and relationships |
| Failure mode | The right chunk falls below the cutoff, and the model answers confidently from what is left | Cache misses after every edit, plus relevant facts lost in the middle of a long prefix | Extraction errors become authoritative-looking relations that are hard to trace |
What Each Approach Does Under the Hood
The table hides the mechanics, and the mechanics are where the costs come from.
flowchart TD
subgraph RAG ["Retrieval-Augmented Generation (RAG) Pipeline"]
direction TB
Q1["User Query"] --> E1["Dense + Lexical Embedding"]
E1 --> S1["Hybrid Search (Vector + BM25)"]
S1 --> R1["Cross-Encoder Reranker"]
R1 --> P1["Assemble Dynamic Context Chunks"]
P1 --> F1["Full Context Transformer Prefill"]
F1 --> O1["Streamed Output"]
end
subgraph CAG ["Cache-Augmented Generation (CAG) Pipeline"]
direction TB
Q2["User Query"] --> G2["Model Inference Gateway"]
G2 --> M2{"Match Prefix KV Hash?"}
M2 -->|Cache Hit| K2["Reuse GPU KV State (0ms prefill)"]
M2 -->|Cache Miss| W2["Compute & Store KV Cache"]
W2 --> K2
K2 --> I2["Incremental Delta Prefill (Query only)"]
I2 --> O2["Streamed Output"]
end
1. Retrieval-Augmented Generation (RAG)
RAG indexes the corpus twice: dense vectors for meaning and BM25 for exact tokens. At query time the system embeds the question, runs both searches, merges the candidates with reciprocal rank fusion, reranks them with a cross-encoder, and sends the best 2,000–8,000 tokens to the model.
Lewis and colleagues set the pattern in 2020 by combining a parametric model with a non-parametric index. The index is why it survived: you can fix a wrong fact at 2am without retraining anything. The cost is that you now own a retrieval pipeline, and that pipeline is a system in its own right — how to make retrieval production-ready covers chunking, filters, reranking, evals and the cost budget it needs.
2. Cache-Augmented Generation (CAG)
CAG is the newer term, named in a December 2024 paper by Chan and colleagues. Their method preloads all the relevant documents into an extended context and caches the model's runtime parameters, so inference needs no retrieval step at all. It works because the corpus is small enough to fit and stable enough to stay put.
- Warm the cache: the first request prefills 100k–500k tokens and stores the Key-Value attention tensors per layer in GPU memory.
- Match the prefix: later requests hash the same prefix and skip that prefill entirely.
- Run the delta: attention runs only on the new query, which is where the near-instant first token comes from.
The economics come from the provider. Anthropic's prompt caching bills cache reads at 0.1x the base input price on standard models and cache writes at 1.25x for the default five-minute lifetime, or 2x for an hour. The minimum cacheable prefix is 512 to 2,048 tokens depending on the model. OpenAI caches eligible prefixes automatically above 1,024 tokens and bills reused tokens at a reduced rate. If you run your own inference, vLLM's automatic prefix caching does the same job locally by hashing KV blocks.
3. Knowledge-Augmented Generation (KAG)
KAG is not a caching strategy. Ant Group's KAG combines a knowledge graph with vector retrieval and a logical-form reasoning step, so the model can follow relations instead of hoping the right paragraph contains the whole answer. The paper reports a 19.6% relative F1 gain on 2Wiki and 33.5% on HotpotQA over RAG baselines, and it shipped in Ant's e-government and e-health question answering.
You pay for that structure twice: once when you build the graph, and again every time the schema or the source data moves. A graph that is 90% right is more dangerous than a chunk that is missing, because the wrong relation reads like a fact.
The Cost and Latency Comparison
The table below is the engineering version of the summary: same three patterns, measured on the dimensions that show up in a design review.
| Evaluation Dimension | Retrieval-Augmented Generation (RAG) | Cache-Augmented Generation (CAG / Prompt Caching) | Hybrid RAG + CAG Pattern |
|---|---|---|---|
| Primary Knowledge Mechanism | Dynamic retrieval (vector similarity + BM25 + cross-encoder) | Static context preloading via KV-cache reuse (Anthropic, OpenAI, vLLM) | Cached core context + retrieved dynamic micro-chunks |
| Time To First Token (TTFT) | Moderate to high (300ms – 2,500ms for embedding, search and reranking) | Ultra low (under 150ms – 400ms on cache hits, bypassing prefix prefill) | Low (200ms – 600ms) |
| Corpus Scalability | Virtually unbounded (billions of tokens across distributed indices) | Bounded by context window and GPU memory (typically under 1M tokens) | Scalable base corpus with focused active caches |
| Input Token Economics | Linear per query, based on retrieved chunk volume (2k–8k tokens) | 75%–90% discount on cached reads; higher initial write and warmup cost | Optimized: bulk context cached at discounted rates |
| Cache Invalidation & Freshness | Instant: update the index record and the next query sees it | Complex: any change to the prefix invalidates every downstream KV block | Dynamic chunks handle updates; static rules stay cached |
| Multi-Tenancy & Access Control | Granular: metadata and SQL filters restrict chunks by user permission | Challenging: shared prefixes risk cross-tenant context bleeding | Shared public cache + user-isolated retrieved chunks |
| Citation Provenance | Deterministic: URL and line-range mapping to the source chunk | Stochastic: the model has to locate the reference inside a long context | Deterministic for retrieved citations |
| Infrastructure Overhead | High (embedding pipeline, vector DB, chunking, rerankers) | Low (model API or inference gateway, no vector DB) | Medium (standard retriever + cache headers) |
Two numbers decide most of this. The first is your cache hit rate: CAG at 98% hits is a different product from CAG at 70%, because every miss pays the full prefill. The second is recall@k on your own corpus. A retrieval pipeline that misses the right chunk has no latency advantage worth measuring.
Where Each Approach Breaks in Production
1. Invalidation Latency and Cache Churn
In RAG, updating a document means updating rows or re-embedding chunks. The index reflects the change within seconds.
In CAG, KV caches are position-dependent, and vLLM's documentation states the rule plainly: each block's hash covers every token before it, so a prompt that differs at one token recomputes that block and every block after it. High write velocity collapses your hit rate and turns every edit into a latency spike.
2. Multi-Tenancy and Data Isolation
Enterprise applications have to respect role-based access control. RAG enforces it at the retrieval layer with a filter like WHERE tenant_id = 'org_42' AND user_roles @> ARRAY['billing_admin'], so the model never sees unauthorized tokens.
CAG forces a worse choice: keep a separate cached prefix per tenant and pay for GPU memory that sits idle, or share a prefix and risk leaking one customer's context into another's answer. For most products, the second option is not a trade-off worth discussing.
3. The Lost in the Middle
Phenomenon
Models accept a million tokens, but they do not weight them evenly. Liu and colleagues showed accuracy follows a U-shaped curve: facts at the start and end of a long context get used, facts in the middle get missed. Dense search plus a cross-encoder cuts that risk by sending less, better context.
4. The Incident You Did Not Budget For
A retrieval outage and a cache-miss storm are the same class of failure: a dependency nobody modeled in the latency budget. Designing AI systems that fail predictably is the next read once you have picked a pattern, because neither RAG nor CAG removes the need for timeouts, fallbacks and a cost ceiling.
The Hybrid Pattern Most Teams Land On
High-throughput deployments rarely treat RAG and CAG as mutually exclusive. They route by knowledge scope: stable material goes in the cached prefix, volatile material goes through retrieval.
flowchart TD
UserQuery["User Request"] --> Gateway["API Gateway / Query Classifier"]
Gateway --> CheckScope{"Knowledge Scope?"}
CheckScope -->|"Static Domain Knowledge<br/>(API Specs, Architecture, SOPs)"| CAG_Path["CAG: Cached KV Prefix"]
CheckScope -->|"Dynamic Ephemeral Data<br/>(User Records, Live Telemetry)"| RAG_Path["RAG: Hybrid Search + Rerank"]
CAG_Path --> Assembler["Context Assembler"]
RAG_Path --> Assembler
Assembler --> LLM["LLM with Prefix Cache Support"]
LLM --> Stream["Streamed Output"]
In that architecture:
- The stable base (CAG): developer guides, API specs, conventions and personas sit at the start of the prompt, cached.
- The dynamic head (RAG): user records, session history and fresh documents are retrieved after the cache breakpoint.
The split also maps onto agents. An agent's stable operating rules belong in the cached prefix while its live observations come from retrieval, which is the memory split described in designing an agent's control loop, tools and state. You can see the same pattern in how teams wire agents into their workflows: persistent domain context, grounded decisions.
Cache Invalidation Strategy
Treat the cached prefix as a versioned artifact, not a mutable document. Rebuild it on a release cadence, never on individual edits. Keep volatile data out of the prefix so everyday churn cannot invalidate your KV state. Warm the new version before you shift traffic.
Multi-Tenant Notes
Cache only what every tenant may see. Permission-scoped data belongs in the retrieved head, filtered by tenant_id before it reaches the prompt. Per-tenant prefixes work, but GPU memory multiplies with tenant count, and that bill is the one teams underestimate.
A Working Prompt-Caching Implementation
This is the hybrid shape in Python: a cached documentation corpus, retrieved chunks appended after the cache breakpoint, and usage counters so you can see whether the cache is actually paying.
import os
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
MODEL = os.environ.get("CLAUDE_MODEL", "claude-sonnet-4-5")
def run_hybrid_query(static_corpus_text: str, dynamic_chunks: list[str], user_query: str) -> str:
"""
Cache the stable corpus once, then append retrieved chunks per query.
Keep the cached block first and byte-identical: any edit invalidates it.
"""
formatted_chunks = "\n\n---\n\n".join(dynamic_chunks)
response = client.messages.create(
model=MODEL,
max_tokens=1024,
system=[
{
"type": "text",
"text": "You are an enterprise technical copilot. Answer precisely from the documentation provided.",
},
{
"type": "text",
"text": static_corpus_text,
# Anthropic caches everything up to and including this block.
"cache_control": {"type": "ephemeral"},
},
],
messages=[
{
"role": "user",
"content": f"Live context:\n{formatted_chunks}\n\nQuestion: {user_query}",
}
],
)
usage = response.usage
print(f"Tokens written to cache: {usage.cache_creation_input_tokens or 0}")
print(f"Tokens read from cache: {usage.cache_read_input_tokens or 0}")
print(f"Uncached input tokens: {usage.input_tokens}")
return response.content[0].text
Watch the ratio between cache reads and cache writes for a week before you trust it. A prefix that changes on every deploy looks cheap in a demo and expensive in production.
When RAG, CAG and KAG Are the Wrong Default
RAG is the wrong default for a small, stable corpus. If your entire handbook fits in 300k tokens and changes monthly, a vector database, an embedding pipeline and a reranker add three failure points and no new knowledge. You are paying retrieval latency to find text the model could have read directly.
CAG is the wrong default the moment writes are continuous or access is not uniform. Per-tenant permissions, hourly document updates, deletion requests and audit trails that must name an exact document version all break the cached-prefix model. A cache that has to be rebuilt is a retrieval system with worse ergonomics.
KAG is the wrong default before retrieval works. If your RAG baseline cannot find the right chunk, a graph built from the same chunks will encode the same gaps, with more confidence. KAG earns its cost when the questions are genuinely multi-hop and your entities and relations are stable enough to extract.
All three are wrong when the question needs an action, not a document. What is our refund policy
is a knowledge question. Refund this order
is a tool call. MCP, APIs and function calling are the layer for the second kind, and no amount of context fixes a missing capability.
Two comparisons keep getting mixed into this one. A knowledge base is the stored corpus; RAG is the architecture that queries it, so owning one does not mean you have the other. And RAG versus GAN is not a real contest: a GAN generates data, while RAG grounds generation in retrieved evidence. Different problems, different tools.
The Decision Rule
Answer three questions in this order. The first one that fails sends you down the tree.
- Does the corpus fit? Under roughly 500k tokens, CAG is viable. Over that, RAG is the only option that scales, and KAG inherits the same index.
- How often does it change? Release cadence or slower favours CAG. Hourly writes, deletions or per-user documents favour RAG.
- Do you need to prove the answer? Strict ACLs, exact citations or version-level audit push you to RAG, or to a hybrid with the permissioned data in the retrieved head.
Write it as one sentence and put it in the design doc: cache the stable core, retrieve the volatile edge, and add a graph only when the questions need relations. That rule survives team changes and vendor pricing updates, which is more than most architecture diagrams manage.
My default is hybrid once a product has a stable core and live user data, and only after each half proves itself alone. I would rather ship retrieval first and add caching where the latency hurts than build both and guess which one is wrong when the answers degrade. If you want to know whether the result is actually better, why engineering metrics fail covers the dashboards that make a system look healthier than it is, and why small specialized models still matter covers the model choice that sits underneath this whole comparison.
Sources
- Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks — Lewis et al., 2020.
- Don't Do RAG: When Cache-Augmented Generation is All You Need for Knowledge Tasks — Chan et al., 2024.
- KAG: Boosting LLMs in Professional Domains via Knowledge Augmented Generation — Liang et al., Ant Group, 2024.
- Lost in the Middle: How Language Models Use Long Contexts — Liu et al., 2023.
- Anthropic prompt caching — cache pricing, TTLs and minimum prefix lengths.
- OpenAI prompt caching — automatic prefix caching and cached-input billing.
- vLLM automatic prefix caching — block hashing and invalidation behavior.
Related Reading
Designing Production-Ready RAG Systems
Retrieval quality is the product in a production-ready RAG system.
How to Design Reliable AI Systems: A Reliability Sequence
The demo works.
Designing AI Agents: An Architectural Guide
An agent is a control loop over tools.