RAG cost optimization is the discipline of making retrieval-augmented generation cheaper without making its answers worse. The central question is simple: where does the money actually go in a RAG pipeline, and which levers cut that spend? The short answer is that most of the bill comes from generation tokens, embedding calls and repeated retrieval work, so the biggest savings come from sending the model less context, caching what repeats and routing easy questions to cheaper paths.
Many teams discover their RAG bill only after launch, when a helpful internal assistant turns into a line item that grows with every user. The good news is that retrieval systems are unusually tunable. Unlike a monolithic model call, a RAG pipeline has several stages, and each stage has its own cost controls. This guide walks through them in order, from measurement to the cheapest wins, so you can cut spend in a way you can defend with numbers.
Key takeaways
- Measure cost per query by stage — retrieval, embedding, reranking and generation — before changing anything.
- Context compression and tighter retrieval usually save more than switching models.
- Caching repeated questions and stable prompt prefixes removes work you have already paid for.
- Route simple questions to smaller models and keep the large model for hard ones.
- Re-measure after every change, because a saving in one stage can push cost into another.
Start by measuring cost per query
You cannot optimise what you cannot see. The first step in RAG cost optimization is logging the cost of every stage of a single query: the embedding call for the question, the vector search, any reranking pass, and the final generation call with its input and output tokens. Most teams are surprised by the split. Generation usually dominates, but retrieval-heavy designs with large top-k values and a reranker can make the retrieval side surprisingly expensive.
Track three numbers per query: total tokens in, total tokens out, and the number of retrieved chunks actually cited in the answer. If you retrieve ten chunks and the answer cites two, you are paying to send eight chunks the model never uses. That gap is the cheapest saving in the whole pipeline, and it is visible only if you log it. LLM token usage tracking gives you the instrumentation pattern for this kind of per-request accounting.
Set a baseline before you change anything: median and 95th-percentile cost per query, plus the share of queries that are repeats or near-repeats.
Send the model less context
The single most effective lever is reducing the number of tokens in the generation prompt. Every token of retrieved context is billed as input, so a pipeline that retrieves twelve chunks of 500 tokens each is paying for 6,000 input tokens before the model writes a word. Tighter retrieval, better chunking and context compression all attack this number directly.
Start with top-k. Many pipelines retrieve far more chunks than the model needs, because a large top-k feels safer. Test top-k of 3, 5 and 8 against your evaluation set and watch both answer quality and cost. In many knowledge-base workloads the quality curve flattens early, while the cost curve keeps rising. RAG context compression covers the techniques for shrinking what you do retrieve, from summarising chunks to dropping redundant passages.
Best for: teams whose generation bill dwarfs everything else and whose answers cite only a fraction of what they retrieve.
Improve retrieval quality instead of retrieving more
Retrieving more documents is the expensive way to fix weak answers. A better retriever finds the right passage in three chunks instead of twelve. Hybrid search, which combines keyword matching with vector search, often lifts recall enough to let you cut top-k. Metadata filtering has the same effect: when a query is about a specific product or date range, filtering before the search keeps irrelevant chunks out of the prompt entirely.
Query rewriting is another cheap win. A short, vague user question often retrieves poorly, which tempts teams to raise top-k. Rewriting the question into a fuller, more specific form — or expanding it with likely terms — usually retrieves better passages with fewer of them. The rewrite itself costs a small model call, but it is far cheaper than stuffing extra context into a large model call.
Cache what repeats
Real user traffic repeats itself. Support assistants see the same questions daily, and internal tools see the same documents requested again and again. Caching attacks that repetition at three levels: exact-match caching of whole answers, semantic caching of similar questions, and prompt caching of the stable prefix of your prompts.
Prompt caching deserves attention first, because it needs almost no new infrastructure. Providers such as Anthropic offer prompt caching on their APIs, where a stable prefix — system instructions, tool definitions and retrieved context — is stored and reused across requests. Cached tokens are read back at roughly a tenth of the normal input price, while the first write costs a modest premium, so the saving grows with every repeated prefix. The cache lifetime is short, typically minutes, and it resets when read, which suits chatty, multi-turn workloads well.
Semantic caching goes further by answering a new question from a cached answer to a similar earlier question. That removes the generation call entirely, which is the most expensive step. It needs a similarity threshold tuned to your data, because a wrong cache hit is worse than a slow answer. Start with a high threshold and lower it only while quality holds.
Route questions to the cheapest model that can answer them
Not every question needs your largest model. A router that sends simple factual questions to a small model and reserves the large model for multi-step reasoning can cut generation spend sharply. The router can be a classifier, a set of rules based on query type, or a small model judging difficulty. LLM model routing explains how to build this split without degrading answers.
Routing also applies inside retrieval. A cheap embedding model may be enough for a broad first pass, with a stronger reranker applied only to the top candidates. And for the generation step itself, consider whether a smaller model with good retrieved context can match the large model. Retrieval grounds the answer, so a smaller model working from strong evidence often performs better than expected — the context does much of the work.
Best for: workloads with a wide mix of easy and hard questions, where a single large model is doing simple lookups most of the day.
Control embedding and indexing costs
Embeddings are cheap per call but they scale with the size of your corpus, and re-embedding a whole corpus on every update is wasteful. Incremental indexing — embedding only new or changed documents — keeps this cost proportional to change rather than to total size. It also keeps the index fresh, which matters more than most teams expect.
Embedding model choice matters too. A smaller embedding model can be a fraction of the cost of a large one, and for many domains the retrieval quality difference is small. Test candidates on your own queries rather than trusting a public benchmark, because retrieval quality is deeply domain-dependent. If your documents are short and structured, you may even find that a smaller model with good chunking beats a larger one.

Use batching and off-peak patterns where they fit
Not all RAG work is interactive. Summarisation, document enrichment and evaluation runs can often be batched, and several providers offer lower prices for asynchronous batch processing. If a job can wait hours, batching can cut its price substantially. The trade-off is latency, so keep interactive queries on the live path and move background work to batch.
Also look at when your traffic arrives. If your assistant is quiet overnight, scale down the serving infrastructure rather than paying for idle capacity. For self-hosted deployments this means autoscaling GPU instances; for API-based systems it means watching for unused provisioned throughput and reserved capacity that no longer matches demand.
Compare the main cost levers
| Lever | What it saves | Effort | Main risk |
|---|---|---|---|
| Lower top-k and context compression | Input tokens on every query | Low | Missing a passage the answer needed |
| Prompt caching | Repeated prefix tokens | Low | Cache misses if the prefix keeps changing |
| Semantic caching | Whole generation calls | Medium | Wrong answers from false-positive matches |
| Model routing | Generation cost on easy queries | Medium | Router errors sending hard queries down |
| Batch processing | Background job costs | Low | Latency for anything time-sensitive |
| Cheaper embeddings | Indexing and query embedding | Low | Lower retrieval recall on niche domains |
A cost optimisation checklist
Work through this list in order, and stop when the numbers say you have done enough. Each item is cheap to verify and expensive to skip.
- Log cost per query by stage for at least a week before changing anything.
- Measure how many retrieved chunks are actually cited in answers.
- Test top-k of 3, 5 and 8 on your evaluation set and pick the smallest that holds quality.
- Turn on prompt caching for stable system prompts and retrieved context.
- Check what share of queries are repeats, and cache the most common answers.
- Add a router for easy questions, with a fallback to the large model.
- Switch bulk and background jobs to batch processing where latency allows.
- Re-run your evaluation set after every change and record cost and quality together.
Common mistakes that raise the bill
The most common mistake is optimising the wrong stage. Teams often switch to a cheaper embedding model while generation still consumes most of the budget. Measure first, and let the numbers pick the target. Another frequent error is caching without invalidation: a cached answer that goes stale is a wrong answer served quickly, and the support tickets it creates cost more than the tokens saved.
A third mistake is treating cost and quality as separate conversations. Every saving should be paired with a quality check on the same evaluation set. If a change cuts cost by a third and quality by a tenth, that may be a good trade — but it should be a deliberate decision, recorded with numbers, not an accident discovered weeks later.
Frequently asked questions
What is the biggest cost driver in a RAG system?
Generation tokens are usually the largest cost, because the model is billed for every input token of retrieved context plus every output token it writes. Retrieval and embedding costs matter, but they are typically smaller unless top-k is very large or the corpus is re-embedded often.
Does reducing top-k hurt answer quality?
It can, if retrieval is weak. The safe approach is to test lower top-k values on an evaluation set and watch quality metrics. If quality falls, improve the retriever — with hybrid search, metadata filtering or query rewriting — rather than simply retrieving more.
Is semantic caching safe for factual answers?
It is safe when the similarity threshold is strict and the cached answers cover stable facts. Keep the threshold high at first, exclude time-sensitive questions from the cache, and invalidate entries when the underlying documents change.
How much can prompt caching save?
It depends on how much of each prompt is a stable prefix and how often that prefix repeats. Providers that offer prompt caching typically charge roughly a tenth of the normal input price for cached tokens, so workloads with long system prompts and repeated context see the largest savings.
Should I use a smaller model for RAG generation?
Often, yes, for straightforward questions. Retrieved context grounds the answer, so a smaller model working from good evidence can perform well. Test it on your evaluation set, and route harder questions to the larger model rather than replacing it outright.
How often should I review RAG costs?
Review cost per query weekly while the system is changing, and monthly once it is stable. Any change to chunking, top-k, models or traffic patterns is a reason to re-check the numbers.







