09. RAG Cost Optimization¶
Category: Production RAG Engineering
Module: Part V โ Advanced Retrieval-Augmented Generation
Difficulty: Advanced
๐ Overview¶
A production RAG system must be optimized not only for accuracy and latency, but also for economic efficiency.
A system that produces excellent answers but costs:
may not be viable when serving:
Similarly, a system that is inexpensive but produces poor answers creates operational and business risk.
Production RAG cost optimization therefore focuses on the complete cost chain:
User Query
โ
Query Processing
โ
Embedding
โ
Retrieval
โ
Reranking
โ
Context Processing
โ
Prompt Assembly
โ
LLM Generation
โ
Validation
โ
Citation
โ
Observability
The objective is:
A useful production principle is:
Do not minimize cost blindly. Minimize the cost of achieving the required quality, latency, and reliability.
๐ฏ Learning Objectives¶
After completing this chapter, you will be able to:
- Understand RAG cost architecture
- Identify major RAG cost drivers
- Calculate cost per request
- Calculate cost per user
- Calculate cost per tenant
- Calculate cost per workflow
- Understand LLM token economics
- Optimize input token usage
- Optimize output token usage
- Optimize retrieval costs
- Optimize embedding costs
- Optimize reranking costs
- Optimize validation costs
- Optimize agentic RAG costs
- Optimize Graph RAG costs
- Optimize SQL RAG costs
- Optimize multimodal RAG costs
- Implement caching strategies
- Implement model routing
- Implement model cascading
- Implement adaptive retrieval
- Reduce unnecessary LLM calls
- Optimize context size
- Optimize prompt size
- Optimize infrastructure costs
- Optimize vector database costs
- Optimize observability costs
- Implement cost budgets
- Implement cost guardrails
- Implement tenant-level cost controls
- Build cost dashboards
- Detect cost anomalies
- Perform cost attribution
- Perform cost forecasting
- Design cost-aware RAG architectures
๐ง 1. What Is RAG Cost Optimization?¶
RAG cost optimization is the process of reducing the resources required to serve RAG requests while preserving acceptable:
A simplified objective is:
๐ง 2. RAG Cost Is More Than LLM Cost¶
A common mistake is:
In reality:
Total RAG Cost
โ
โโโ LLM
โโโ Embeddings
โโโ Reranking
โโโ Vector Database
โโโ Search Infrastructure
โโโ Compute
โโโ Storage
โโโ Network
โโโ Observability
โโโ Evaluation
โโโ Background Processing
๐ง 3. Cost Architecture¶
flowchart TD
A["RAG Request"] --> B["Query Processing"]
B --> C["Embedding"]
C --> D["Retrieval"]
D --> E["Reranking"]
E --> F["Context Processing"]
F --> G["LLM"]
G --> H["Validation"]
H --> I["Citation"]
C --> J["Embedding Cost"]
D --> K["Vector/Search Cost"]
E --> L["Reranker Cost"]
G --> M["LLM Cost"]
H --> N["Validation Cost"]
I --> O["Processing Cost"]
P["Infrastructure"] --> Q["Compute"]
P --> R["Storage"]
P --> S["Network"]
P --> T["Observability"]
๐ง 4. Cost Categories¶
A practical classification:
Variable Cost
โ
Cost changes with requests/tokens
Fixed Cost
โ
Infrastructure that exists regardless of request volume
Semi-Variable Cost
โ
Resources that scale with workload
Examples:
Variable¶
Fixed¶
Semi-Variable¶
๐ง 5. Cost Per Request¶
A simplified model:
C_request =
C_embedding
+ C_retrieval
+ C_reranking
+ C_context
+ C_generation
+ C_validation
+ C_observability
+ C_infrastructure
๐ง 6. LLM Cost¶
LLM cost is commonly driven by:
Conceptually:
Actual pricing varies by provider, model, region, and pricing program.
๐ง 7. RAG Token Composition¶
A request may contain:
Therefore:
๐ง 8. Context Is Often the Largest Optimization Opportunity¶
Example:
System Prompt 1,000 tokens
User Query 100 tokens
Conversation 900 tokens
Retrieved Context 8,000 tokens
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Input 10,000 tokens
If the context is reduced:
the input token cost can fall significantly.
๐ง 9. Context Cost¶
The goal is not:
but:
๐ง 10. Context Efficiency¶
A useful conceptual metric:
Context Efficiency
=
Useful Evidence
โโโโโโโโโโโโโโโโโโ
Context Tokens
Higher is generally better.
This is not a universal standardized metric; use it as an engineering diagnostic.
๐ง 11. Context Waste¶
Example:
The system is paying for:
while deriving useful information from approximately:
๐ง 12. Context Optimization¶
Use:
Top-K Tuning
+
Reranking
+
MMR
+
Context Compression
+
Deduplication
+
Metadata Filtering
+
Token Budgeting
๐ง 13. Token Budget¶
Define:
Example:
Then:
๐ง 14. Token Budget Architecture¶
flowchart LR
A["Model Context Window"] --> B["System Instructions"]
A --> C["User Query"]
A --> D["Conversation"]
A --> E["Retrieved Context"]
A --> F["Output Budget"]
E --> G["Context Budget"]
G --> H["Relevant Evidence"]
๐ง 15. Dynamic Context Budget¶
Not every query needs the same amount of context.
Simple FAQ
โ
2,000 tokens
Technical Query
โ
4,000 tokens
Complex Multi-Hop Query
โ
8,000 tokens
Use adaptive budgets where appropriate.
๐ง 16. Cost of Top-K¶
Increasing K can increase:
Example:
The quality improvement may not justify the additional cost.
๐ง 17. Cost-Aware Top-K¶
Instead of:
use:
๐ง 18. Adaptive Retrieval¶
Query
โ
Retrieve Small Candidate Set
โ
Confidence Check
โ
โโโ High Confidence โ Generate
โ
โโโ Low Confidence โ Expand Retrieval
This reduces expensive work for easy queries.
๐ง 19. Early Exit¶
Example:
Initial Retrieval
โ
Top Result Score = 0.94
โ
Evidence Sufficient?
โ
โโโ Yes โ Generate
โโโ No โ Expand
Use calibrated signals rather than arbitrary score thresholds.
๐ง 20. Query Rewriting Cost¶
Query rewriting may require an LLM.
If rewriting costs:
and is executed:
the rewriting layer alone contributes:
before the main generation cost.
๐ง 21. Conditional Query Rewriting¶
Query
โ
Complexity Detector
โ
โโโ Simple โ Direct Retrieval
โ
โโโ Complex โ Query Rewrite
This can significantly reduce unnecessary model calls.
๐ง 22. Multi-Query Cost¶
Multi-query:
may multiply:
Use it when the quality improvement justifies the additional cost.
๐ง 23. Multi-Query Cost Optimization¶
Query
โ
Determine Need
โ
โโโ Low Ambiguity โ Single Query
โ
โโโ High Ambiguity โ Multi-Query
๐ง 24. Embedding Cost¶
Embedding cost can come from:
Query embeddings happen frequently.
Document embeddings can become expensive during large ingestion operations.
๐ง 25. Embedding Cost Optimization¶
Use:
where quality requirements permit.
๐ง 26. Avoid Re-Embedding Unchanged Documents¶
Use content hashes:
Pipeline:
Document
โ
Hash
โ
Compare Previous Hash
โ
โโโ Same โ Skip
โโโ Changed โ Re-Embed
๐ง 27. Incremental Indexing¶
Bad:
Better:
๐ง 28. Batch Embedding¶
Document 1 โ
Document 2 โ
Document 3 โโโ Batch โ Embedding Model
Document 4 โ
Document 5 โ
Batching can reduce per-request overhead and improve accelerator utilization.
๐ง 29. Embedding Model Economics¶
Compare:
Model A
Quality = 91%
Cost = Low
Model B
Quality = 94%
Cost = Medium
Model C
Quality = 96%
Cost = High
Choose based on:
๐ง 30. Local vs Hosted Embeddings¶
Hosted¶
Costs may include:
Local¶
Costs shift toward:
Neither is universally cheaper.
๐ง 31. Reranking Cost¶
Rerankers can be expensive because they may evaluate many query-document pairs.
Conceptually:
๐ง 32. Candidate Reduction¶
Instead of:
use:
๐ง 33. Reranker Selection¶
Possible options:
Use the least expensive approach that meets the quality requirement.
๐ง 34. Selective Reranking¶
Query
โ
Initial Retrieval
โ
Confidence
โ
โโโ High โ Skip Reranker
โ
โโโ Low โ Rerank
This can reduce average cost.
๐ง 35. LLM Cost¶
LLM cost often dominates production RAG economics.
RAG Request
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LLM COST โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Input Tokens โ
โ Output Tokens โ
โ Number of Calls โ
โ Model Selection โ
โ Retries โ
โ Validation Calls โ
โ Agent Tool Calls โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ง 36. Reduce Number of LLM Calls¶
One of the strongest cost optimizations:
Example:
Query
โ
Classifier
โ
โโโ FAQ โ Cached Answer
โโโ Search โ Retrieval + Small LLM
โโโ Complex โ Large LLM
โโโ SQL โ SQL Pipeline
๐ง 37. Model Routing¶
flowchart TD
A["Query"] --> B["Model Router"]
B --> C["Small Model"]
B --> D["Medium Model"]
B --> E["Large Model"]
C --> F["Response"]
D --> F
E --> F
The router should consider:
๐ง 38. Model Cascade¶
Average cost can decrease if most queries are successfully handled by the smaller model.
๐ง 39. Model Routing Example¶
๐ง 40. Model Routing Economics¶
Suppose:
instead of:
the average cost can be substantially lower, assuming quality remains acceptable.
๐ง 41. Output Token Optimization¶
Output tokens directly affect:
Use:
๐ง 42. Output Budget¶
Do not allocate the maximum output budget to every request.
๐ง 43. Response Contract¶
Example:
This reduces unnecessary output.
๐ง 44. Prompt Optimization¶
Prompt cost includes:
Reduce:
๐ง 45. Prompt Versioning¶
Use:
Measure:
A shorter prompt is not automatically better if quality drops.
๐ง 46. Prompt Caching¶
If supported by the model/provider:
Potentially reduces:
๐ง 47. Conversation Cost¶
Conversational RAG can become expensive because history grows.
Turn 1 โ 500 tokens
Turn 2 โ 1,200 tokens
Turn 3 โ 2,500 tokens
Turn 4 โ 4,500 tokens
Turn 5 โ 7,000 tokens
๐ง 48. Conversation Compression¶
Instead of passing all history:
๐ง 49. Memory Budget¶
Set:
Use:
rather than blindly sending the complete conversation.
๐ง 50. Semantic Conversation Selection¶
Retrieve only relevant historical messages:
This reduces token usage.
๐ง 51. Retrieval Cache¶
Cache retrieval results for repeated requests.
Key should account for:
๐ง 52. Cache Economics¶
If:
and:
then:
may avoid some downstream computation.
Actual savings depend on what the cache bypasses.
๐ง 53. Semantic Cache¶
Example:
Potentially reuse the result.
But semantic caching must validate:
๐ง 54. Cache Invalidation¶
Invalidate when:
Document Changes
Index Changes
Embedding Changes
Prompt Changes
Retriever Changes
Authorization Changes
๐ง 55. Cache Versioning¶
Example:
This prevents stale results from older pipeline versions.
๐ง 56. Tenant Cost Attribution¶
Enterprise RAG should answer:
How much does Tenant A cost?
How much does Tenant B cost?
Which tenant consumes the most tokens?
Which tenant generates the most expensive requests?
๐ง 57. Cost Per Tenant¶
Example:
This enables:
๐ง 58. Cost Per User¶
Track:
Avoid exposing user-level data broadly; apply appropriate privacy and access controls.
๐ง 59. Cost by Application¶
Enterprise platforms may host:
Track cost separately.
๐ง 60. Cost by Workflow¶
A single application may have:
Each can have a different cost profile.
๐ง 61. Cost by Model¶
Track:
with:
๐ง 62. Cost by Provider¶
For multi-cloud enterprise systems:
compare:
๐ง 63. Reranking Cost by Query¶
Some queries may require:
others:
and complex queries:
Use query-aware policies.
๐ง 64. Agentic RAG Cost¶
Agentic RAG can multiply cost.
Potentially:
๐ง 65. Agentic RAG Cost Guardrails¶
Define:
Example:
๐ง 66. Agentic Early Termination¶
Avoid unnecessary planning loops.
๐ง 67. Agentic Loop Detection¶
Potential problem:
Use:
๐ง 68. Graph RAG Cost¶
Graph RAG may require:
Cost can increase with traversal depth.
๐ง 69. Graph Traversal Budget¶
Instead of:
use:
๐ง 70. SQL RAG Cost¶
SQL RAG can generate expensive queries.
Potential risks:
Use:
๐ง 71. SQL Result Budget¶
Instead of:
use:
Only return data required for reasoning.
๐ง 72. Multimodal RAG Cost¶
Multimodal workloads may involve:
Optimize using:
๐ง 73. Image Processing Cost¶
Avoid processing every image at maximum resolution.
๐ง 74. Validation Cost¶
If every answer invokes:
the cost can multiply.
Possible alternatives:
๐ง 75. Risk-Based Validation¶
flowchart TD
A["Generated Response"] --> B["Risk Classifier"]
B --> C["Low Risk"]
B --> D["Medium Risk"]
B --> E["High Risk"]
C --> F["Rule Validation"]
D --> G["Lightweight Validation"]
E --> H["Deep Validation"]
F --> I["Final Response"]
G --> I
H --> I
๐ง 76. Cost-Aware Citation¶
Citations should ideally be produced using source metadata already carried through the pipeline.
Avoid unnecessary additional LLM calls just to reconstruct sources.
๐ง 77. Infrastructure Cost¶
Infrastructure includes:
RAG Compute
Vector DB
Search Engine
Object Storage
Databases
GPU
Load Balancers
Network
Observability
๐ง 78. Compute Optimization¶
Optimize:
๐ง 79. CPU vs GPU¶
Use GPU when:
CPU may be more appropriate for:
๐ง 80. GPU Utilization¶
Poor:
while paying for a large GPU.
Potential solutions:
๐ง 81. Autoscaling¶
Scale based on:
๐ง 82. Scale-to-Zero¶
For workloads that are:
scale-to-zero or scheduled compute can reduce infrastructure cost where supported.
๐ง 83. Vector Database Cost¶
Vector DB cost depends on:
๐ง 84. Vector Storage Optimization¶
Reduce:
where quality and operational requirements permit.
๐ง 85. Data Lifecycle¶
Implement:
Not every document needs identical storage characteristics.
๐ง 86. Document Retention¶
Enterprise knowledge bases may contain:
Remove expired data from the active retrieval path when policy allows.
๐ง 87. Storage Tiering¶
Retrieve cold data only when required.
๐ง 88. Network Cost¶
Network costs may come from:
Reduce unnecessary payloads and cross-region communication.
๐ง 89. Region Optimization¶
Choose infrastructure locations based on:
Do not optimize cost by violating data residency or regulatory requirements.
๐ง 90. Observability Cost¶
Observability can become expensive when capturing:
Use:
๐ง 91. Evaluation Cost¶
RAG evaluation can itself consume LLM calls.
Large evaluation suites can become expensive.
๐ง 92. Evaluation Sampling¶
Instead of evaluating:
consider:
The right sampling policy depends on the application's risk.
๐ง 93. Continuous Evaluation Cost¶
Use:
rather than evaluating every request with expensive models.
๐ง 94. Cost-Aware Evaluation¶
Prioritize:
๐ง 95. Cost Anomaly Detection¶
Monitor:
๐ง 96. Cost Spike Example¶
Investigate:
๐ง 97. Cost Dashboard¶
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ RAG COST DASHBOARD โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Requests/day 120,000 โ
โ Avg Cost/request $0.018 โ
โ Daily Cost $2,160 โ
โ Monthly Forecast $64,800 โ
โ โ
โ LLM 69% โ
โ Embeddings 11% โ
โ Reranking 7% โ
โ Vector DB 6% โ
โ Infrastructure 4% โ
โ Observability 3% โ
โ โ
โ Cache Hit Rate 31% โ
โ Avg Context Tokens 3,900 โ
โ Avg Output Tokens 420 โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Values are illustrative.
๐ง 98. Cost Breakdown¶
TOTAL COST
โ
โโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโ
โผ โผ โผ
AI DATA PLATFORM
โ โ โ
LLM Tokens Vector DB Compute
Embeddings Storage Network
Reranker Search Observability
Evaluation Object Storage
๐ง 99. Cost per Request Formula¶
If:
then:
๐ง 100. Monthly Cost Forecast¶
A simple estimate:
Example:
This is a simple forecast and does not account for traffic growth or tiered pricing.
๐ง 101. Cost Forecasting¶
Forecast using:
Example:
But cost may not exactly double if:
๐ง 102. Cost Elasticity¶
Measure:
A highly elastic architecture may scale cost almost linearly.
An optimized architecture can sometimes achieve:
through:
๐ง 103. Cost per Successful Answer¶
A more useful business metric than raw cost:
Cost per Successful Answer
=
Total Cost
โโโโโโโโโโโโโโโโโโโโ
Successful Answers
This captures quality.
๐ง 104. Cost per High-Quality Answer¶
Example:
Then:
๐ง 105. Quality-Adjusted Cost¶
Conceptually:
This can help compare architectures.
However, quality scores must be defined consistently.
๐ง 106. Cost vs Quality¶
Quality
โฒ
โ โ
โ โ
โ โ
โ โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโบ Cost
There is often a point of diminishing returns.
๐ง 107. Diminishing Returns¶
Example:
The additional:
may not justify:
depending on the use case.
๐ง 108. Cost Optimization Frontier¶
Quality
โฒ
โ
โ โ
โ โ
โ โ
โ โ
โโโโโโโโโโโโโโโโโโโโบ Cost
The goal is to operate near an efficient frontier rather than blindly choosing the cheapest or most accurate configuration.
๐ง 109. Cost Guardrails¶
Production systems should have limits:
Max Cost / Request
Max Tokens / Request
Max Agent Iterations
Max Tool Calls
Max Retrieval Candidates
Max Context Tokens
๐ง 110. Request Budget¶
Example:
Pipeline:
๐ง 111. Budget-Aware Routing¶
If the request has already consumed:
a cheaper path may be selected.
๐ง 112. Agent Cost Budget¶
Agent
โ
โโโ Step 1 โ $0.01
โโโ Step 2 โ $0.02
โโโ Step 3 โ $0.02
โโโ Step 4 โ $0.03
โ
โผ
$0.08
โ
โผ
Budget = $0.10
Next expensive action may be blocked.
๐ง 113. Tenant Budgets¶
Example:
Use:
according to business policy.
๐ง 114. Soft vs Hard Budgets¶
Soft Budget¶
Hard Budget¶
๐ง 115. Graceful Degradation¶
When budget is constrained:
or:
or:
๐ง 116. Cost-Aware Architecture¶
flowchart TD
A["User Query"] --> B["Budget Manager"]
B --> C["Query Router"]
C --> D["Fast Path"]
C --> E["Standard RAG"]
C --> F["Advanced RAG"]
E --> G["Retrieval"]
F --> G
G --> H["Reranking"]
H --> I["Context Budget"]
I --> J["Model Router"]
J --> K["Small Model"]
J --> L["Large Model"]
K --> M["Validation"]
L --> M
M --> N["Response"]
B --> O["Cost Tracking"]
O --> P["Budget Enforcement"]
๐ง 117. Cost-Aware Retrieval¶
A production retriever should consider:
not only:
๐ง 118. Cost-Aware Query Routing¶
Use the expensive route only when required.
๐ง 119. Cost-Aware Validation¶
๐ง 120. Cost-Aware Agentic RAG¶
Agent should understand:
Example:
๐ง 121. Cost-Aware Graph RAG¶
Use:
to prevent runaway graph exploration.
๐ง 122. Cost-Aware SQL RAG¶
Use:
where supported.
๐ง 123. Cost-Aware Multimodal RAG¶
Use:
๐ง 124. Cost-Aware Evaluation¶
Prioritize evaluation of:
๐ง 125. Cost Optimization by Layer¶
Layer Optimization
Query Routing / Rewrite selectively
Embedding Cache / Batch
Retrieval Top-K / ANN
Hybrid Parallel / Candidate reduction
Reranking Smaller candidate set
Context Compression / Deduplication
Prompt Shorter / Cache
LLM Model routing
Validation Risk-based
Citation Metadata propagation
Agent Step budgets
Graph Traversal limits
SQL Query limits
Multimodal Resolution / routing
Infrastructure Autoscaling
Observability Sampling
๐ง 126. Cost Optimization Priority¶
A practical sequence:
1. Measure total cost
2. Identify largest cost component
3. Reduce unnecessary work
4. Reduce token volume
5. Reduce number of model calls
6. Add caching
7. Introduce model routing
8. Optimize retrieval
9. Optimize infrastructure
10. Add budget guardrails
11. Continuously benchmark
๐ง 127. Cost Optimization Example¶
Baseline:
Optimized:
Top-K = Adaptive
Reranker = Selective
Context = 4,000 tokens
LLM = Routed
Validation = Risk-Based
Cache = Enabled
๐ง 128. Example Cost Comparison¶
| Configuration | Tokens | LLM Calls | Avg Cost | p95 Latency |
|---|---|---|---|---|
| Baseline | 8,500 | 3 | $0.052 | 2.8s |
| Context Optimized | 5,000 | 3 | $0.035 | 2.2s |
| Model Routing | 5,000 | 2 | $0.021 | 1.7s |
| Cached + Routed | 5,000 | 1.4 avg | $0.015 | 1.3s |
Values are illustrative.
๐ง 129. Cost Optimization Experiment¶
Hypothesis:
Measure:
๐ง 130. Cost Experiment Matrix¶
| Experiment | Cost | Latency | Quality | Decision |
|---|---|---|---|---|
| Baseline | โ | โ | โ | โ |
| Context Reduction | โ | โ | โ | โ |
| Smaller Model | โ | โ | โ | โ |
| Caching | โ | โ | โ | โ |
| Selective Reranking | โ | โ | โ | โ |
| Model Routing | โ | โ | โ | โ |
| Adaptive Retrieval | โ | โ | โ | โ |
Populate using real benchmarks.
๐งช 131. Practical Project¶
Build a:
Production RAG Cost Optimization Lab
Start with a baseline RAG system and progressively optimize:
๐งช 132. Baseline Project¶
Query
โ
Embedding
โ
Vector Search
โ
Top-10
โ
Reranking
โ
Large LLM
โ
Validation LLM
โ
Response
Measure:
๐งช 133. Optimization Stage 1 โ Context¶
Change:
to:
Measure:
๐งช 134. Optimization Stage 2 โ Reranking¶
Change:
to:
Measure:
๐งช 135. Optimization Stage 3 โ Model Routing¶
Measure:
๐งช 136. Optimization Stage 4 โ Caching¶
Add:
Measure:
๐งช 137. Optimization Stage 5 โ Adaptive Retrieval¶
Measure:
๐งช 138. Optimization Stage 6 โ Budget Guardrails¶
Implement:
Test:
๐งช 139. Cost Test Dataset¶
Include:
Simple Queries
Complex Queries
Long Queries
Multi-Hop Queries
No-Answer Queries
Repeated Queries
Ambiguous Queries
SQL Queries
Graph Queries
Multimodal Queries
Agentic Queries
๐งช 140. Cost Benchmark Harness¶
def benchmark_cost(rag, queries):
results = []
for query in queries:
result = rag.answer(query)
results.append({
"query": query,
"cost": result.cost,
"latency_ms": result.latency_ms,
"input_tokens": result.input_tokens,
"output_tokens": result.output_tokens,
"llm_calls": result.llm_calls
})
return results
๐งช 141. Cost Metrics¶
Track:
Cost / Request
Cost / Successful Answer
Cost / High-Quality Answer
Cost / Tenant
Cost / User
Cost / Workflow
Cost / Model
Cost / Provider
๐งช 142. Token Metrics¶
Track:
๐งช 143. Model Metrics¶
Track:
๐งช 144. Cache Metrics¶
Track:
๐งช 145. Budget Metrics¶
Track:
๐งช 146. Cost Dashboard¶
A production dashboard should show:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ COST OVERVIEW โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Daily Cost $2,160 โ
โ Monthly Forecast $64,800 โ
โ Cost / Request $0.018 โ
โ Cost / Success $0.021 โ
โ โ
โ Input Tokens 4,100 โ
โ Output Tokens 390 โ
โ Cache Hit Rate 31% โ
โ โ
โ LLM 69% โ
โ Embedding 11% โ
โ Reranking 7% โ
โ Vector DB 6% โ
โ Infra 4% โ
โ Observability 3% โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Illustrative values.
๐งช 147. Tenant Cost Dashboard¶
This enables chargeback and optimization.
๐งช 148. Cost Anomaly Detection¶
Alert when:
or:
or:
๐งช 149. Example Cost Alert¶
ALERT: RAG cost anomaly
Average cost/request:
$0.018
Current:
$0.029
Increase:
61%
Primary signal:
Context tokens +72%
Possible cause:
Top-K configuration changed.
๐ง 150. Cost Governance¶
Enterprise RAG should define:
๐ง 151. Model Governance¶
Define:
๐ง 152. Cost Governance by Risk¶
Different workloads can have different budgets:
๐ง 153. FinOps for RAG¶
RAG can adopt FinOps principles:
๐ง 154. RAG FinOps Architecture¶
flowchart TD
A["RAG Usage"] --> B["Telemetry"]
B --> C["Cost Attribution"]
C --> D["Tenant"]
C --> E["Application"]
C --> F["Model"]
C --> G["Workflow"]
D --> H["Budgets"]
E --> H
F --> H
G --> H
H --> I["Optimization"]
I --> J["Routing"]
I --> K["Caching"]
I --> L["Context Optimization"]
I --> M["Infrastructure Optimization"]
J --> N["Lower Cost"]
K --> N
L --> N
M --> N
๐ง 155. Production Cost Optimization Architecture¶
USER
โ
โผ
โโโโโโโโโโโโโโโ
โ RAG API โ
โโโโโโโโฌโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโ
โ Budget Manager โ
โโโโโโโโโโฌโโโโโโโโโ
โ
โผ
Query Router
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โผ โผ โผ
Fast Path Standard Advanced
โ โ โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โผ
Retrieval
โ
โผ
Reranking
โ
โผ
Context Budget
โ
โผ
Model Router
โ
โโโโโโโโโโดโโโโโโโโโ
โผ โผ
Small LLM Large LLM
โ โ
โโโโโโโโโโฌโโโโโโโโโ
โผ
Validation
โ
โผ
Citation
โ
โผ
Response
โ
โผ
Cost Telemetry
โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โผ โผ โผ
Tenant Model Workflow
Cost Cost Cost
โ โ โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโ
โผ
Cost Dashboard
โ
โผ
Optimization
๐ง 156. Cost Optimization Maturity¶
Level 1 โ Basic Visibility¶
Level 2 โ Token Visibility¶
Level 3 โ Component Cost¶
Level 4 โ Cost Attribution¶
Level 5 โ Cost Controls¶
Level 6 โ Cost-Aware RAG¶
Level 7 โ Autonomous Optimization¶
๐ง 157. Cost Optimization Mental Model¶
RAG COST
โ
โโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโ
โผ โผ โผ
AI DATA PLATFORM
โ โ โ
LLM Vector DB Compute
Embedding Storage Network
Reranker Search Observability
Evaluation
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโ
โผ
COST CONTROL
โ
โโโโโโโโโโโโโโโผโโโโโโโโโโโโโโ
โผ โผ โผ
Reduce Reuse Route
Work Work Work
โ โ โ
โโโโโโโโโโโโโโโผโโโโโโโโโโโโโโ
โผ
COST / QUALITY
๐ง 158. Final Cost Optimization Loop¶
Measure
โ
Attribute
โ
Find Largest Cost Driver
โ
Remove Unnecessary Work
โ
Reduce Tokens
โ
Reduce Model Calls
โ
Cache
โ
Route
โ
Optimize Infrastructure
โ
Apply Budgets
โ
Benchmark Quality
โ
Deploy
โ
Monitor
โ
Repeat
๐ง 159. Production Principles¶
Principle 1¶
The cheapest request is the request you do not need to execute.
Use:
Principle 2¶
The second-cheapest request is the one executed with the smallest suitable model.
Principle 3¶
Context is a cost center.
Do not treat retrieved tokens as free.
Principle 4¶
Every additional RAG stage has an economic cost.
Before adding:
measure the quality improvement.
Principle 5¶
Optimize cost per successful answer, not cost per request alone.
๐ง 160. Production RAG Cost Checklist¶
โ Calculate cost/request
โ Calculate cost/successful answer
โ Calculate cost/high-quality answer
โ Track LLM input tokens
โ Track LLM output tokens
โ Track context tokens
โ Track conversation tokens
โ Track embedding cost
โ Track reranking cost
โ Track retrieval infrastructure
โ Track vector DB cost
โ Track compute cost
โ Track network cost
โ Track observability cost
โ Track evaluation cost
โ Optimize context size
โ Optimize Top-K
โ Optimize reranking candidates
โ Optimize query rewriting
โ Optimize multi-query
โ Batch embeddings
โ Cache embeddings
โ Incrementally embed documents
โ Use content hashes
โ Optimize vector indexes
โ Cache retrieval
โ Implement semantic cache where appropriate
โ Version caches
โ Implement cache invalidation
โ Preserve tenant isolation
โ Implement model routing
โ Implement model cascades
โ Use smaller models where appropriate
โ Limit output tokens
โ Optimize prompts
โ Use prompt caching where appropriate
โ Implement selective validation
โ Optimize citation processing
โ Limit agent iterations
โ Limit agent tool calls
โ Limit agent token budgets
โ Limit Graph RAG traversal
โ Limit SQL result sets
โ Optimize multimodal processing
โ Optimize compute
โ Optimize GPU utilization
โ Optimize vector DB
โ Optimize storage
โ Optimize network
โ Implement autoscaling
โ Separate workloads
โ Implement backpressure
โ Implement tenant budgets
โ Implement application budgets
โ Implement workflow budgets
โ Implement request budgets
โ Implement soft limits
โ Implement hard limits
โ Implement graceful degradation
โ Build cost dashboards
โ Build tenant dashboards
โ Build model dashboards
โ Build workflow dashboards
โ Detect anomalies
โ Forecast costs
โ Benchmark optimizations
โ Monitor quality regressions
โ Review cost continuously
๐ 161. Key Takeaways¶
- RAG cost is broader than LLM API cost.
- Cost should be measured across the entire architecture.
- LLM tokens are often a major cost driver.
- Context size is one of the most important optimization opportunities.
- Reduce unnecessary context before reducing model quality.
- Do not blindly increase Top-K.
- Use adaptive retrieval where appropriate.
- Query rewriting should be conditional when possible.
- Multi-query retrieval should justify its additional cost.
- Batch embedding operations.
- Cache repeated embeddings.
- Avoid re-embedding unchanged documents.
- Use incremental indexing.
- Use content hashes for change detection.
- Reranking cost grows with candidate volume.
- Reduce candidates before expensive reranking.
- Selective reranking can reduce cost.
- Model routing can significantly reduce average LLM cost.
- Model cascades can use expensive models only when required.
- Output token limits reduce both cost and latency.
- Prompt optimization reduces unnecessary input tokens.
- Conversation compression controls growing history cost.
- Retrieval caching can avoid repeated downstream computation.
- Semantic caching requires careful freshness and authorization controls.
- Cache versioning is essential.
- Tenant isolation must apply to caches.
- Agentic RAG requires explicit cost budgets.
- Agent loops must have limits.
- Graph traversal should have bounded depth and result size.
- SQL RAG requires execution and result-size controls.
- Multimodal RAG requires image and vision cost controls.
- Validation should be risk-based where appropriate.
- Citation processing should reuse source metadata.
- Infrastructure cost matters alongside model cost.
- Vector DB cost depends on storage, compute, replication, and workload.
- Autoscaling can reduce idle infrastructure costs.
- Storage tiering can reduce long-term knowledge-base costs.
- Observability can itself become a significant cost center.
- Evaluation should be sampled intelligently where appropriate.
- Cost should be attributable by tenant, application, model, and workflow.
- Cost budgets provide predictable governance.
- Cost guardrails protect against runaway agentic or high-token requests.
- Graceful degradation allows systems to remain useful under budget constraints.
- RAG FinOps combines visibility, allocation, optimization, and governance.
- Cost optimization must preserve quality and reliability.
- The correct target is not minimum cost.
- The correct target is minimum cost for the required production quality and service level.
๐งญ 162. Chapter Navigation¶
Part V โ Advanced Retrieval-Augmented Generation¶
Previous:
08. RAG Performance Optimization
Next:
10. Production Retrieval Architecture
Section:
06 โ Production RAG Engineering
Production RAG Engineering Path¶
01 Prompt Assembly
โ
02 Context Selection & Context Engineering
โ
03 Response Validation
โ
04 Citation & Source Attribution
โ
05 Enterprise Response
โ
06 RAG Evaluation & Benchmarking
โ
07 RAG Observability
โ
08 RAG Performance Optimization
โ
09 RAG Cost Optimization
โ
10 Production Retrieval Architecture
โ
11 Building Production RAG Systems
Enterprise AI Engineering Handbook
Building Production-Grade Enterprise AI Systems โ One Chapter at a Time.