Skip to content

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:

$0.50 per request

may not be viable when serving:

10,000 requests/day

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:

Quality
   +
Performance
   +
Reliability
   +
Security
   +
Cost Efficiency

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:

Answer Quality
Latency
Reliability
Security

A simplified objective is:

Cost โ†“
Quality โ†”
Latency โ†”
Reliability โ†”

๐Ÿง  2. RAG Cost Is More Than LLM Cost

A common mistake is:

RAG Cost = LLM Cost

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

LLM Tokens
Embedding Requests
Reranker Requests
Evaluation Calls

Fixed

Base Infrastructure
Monitoring Platform
Reserved Capacity

Semi-Variable

Vector DB
Compute
Storage
Network

๐Ÿง  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:

Input Tokens
+
Output Tokens

Conceptually:

LLM Cost
=
Input Tokens ร— Input Price
+
Output Tokens ร— Output Price

Actual pricing varies by provider, model, region, and pricing program.


๐Ÿง  7. RAG Token Composition

A request may contain:

System Prompt
+
User Query
+
Conversation History
+
Retrieved Context
+
Tool Results
+
Output

Therefore:

Input Tokens
=
Instructions
+
Query
+
History
+
Context
+
Tools

๐Ÿง  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:

8,000 โ†’ 3,000 tokens

the input token cost can fall significantly.


๐Ÿง  9. Context Cost

Retrieved Documents
        โ†“
Filtering
        โ†“
Reranking
        โ†“
Compression
        โ†“
Final Context
        โ†“
LLM

The goal is not:

Retrieve Maximum Context

but:

Retrieve Sufficient Evidence

๐Ÿง  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:

Context:
10,000 tokens

Useful:
3,000 tokens

Potentially irrelevant:
7,000 tokens

The system is paying for:

10,000

while deriving useful information from approximately:

3,000

๐Ÿง  12. Context Optimization

Use:

Top-K Tuning
+
Reranking
+
MMR
+
Context Compression
+
Deduplication
+
Metadata Filtering
+
Token Budgeting

๐Ÿง  13. Token Budget

Define:

Maximum Context Tokens

Example:

Context Budget = 4,000

Then:

Retrieved Candidates
        โ†“
Rank
        โ†“
Select
        โ†“
Fit within Budget

๐Ÿง  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:

Retrieval Work
Reranking Work
Context Tokens
LLM Input Cost
LLM Latency

Example:

K = 5
    โ†“
2,500 tokens

K = 20
    โ†“
10,000 tokens

The quality improvement may not justify the additional cost.


๐Ÿง  17. Cost-Aware Top-K

Instead of:

Always K = 20

use:

Simple Query โ†’ K = 5
Complex Query โ†’ K = 10
High Uncertainty โ†’ K = 20

๐Ÿง  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.

User Query
    โ†“
Rewrite Model
    โ†“
Retrieval

If rewriting costs:

$0.002/request

and is executed:

1,000,000 times

the rewriting layer alone contributes:

$2,000

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:

Original
 โ”œโ”€โ”€ Query A
 โ”œโ”€โ”€ Query B
 โ”œโ”€โ”€ Query C
 โ””โ”€โ”€ Query D

may multiply:

Embedding Calls
Retrieval Calls
Reranking Candidates
Network Requests

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:

Document Ingestion
Query Embeddings
Re-indexing
Evaluation

Query embeddings happen frequently.

Document embeddings can become expensive during large ingestion operations.


๐Ÿง  25. Embedding Cost Optimization

Use:

Batching
Caching
Incremental Embedding
Change Detection
Smaller Models
Local Models

where quality requirements permit.


๐Ÿง  26. Avoid Re-Embedding Unchanged Documents

Use content hashes:

import hashlib


def content_hash(text):

    return hashlib.sha256(
        text.encode("utf-8")
    ).hexdigest()

Pipeline:

Document
   โ†“
Hash
   โ†“
Compare Previous Hash
   โ”‚
   โ”œโ”€โ”€ Same โ†’ Skip
   โ””โ”€โ”€ Changed โ†’ Re-Embed

๐Ÿง  27. Incremental Indexing

Bad:

1,000,000 documents
        โ†“
Document changes
        โ†“
Re-embed 1,000,000

Better:

1,000,000 documents
        โ†“
500 changed
        โ†“
Re-embed 500

๐Ÿง  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:

Required Retrieval Quality
+
Cost Budget
+
Latency Target

๐Ÿง  30. Local vs Hosted Embeddings

Hosted

Application
    โ†“
External Embedding API

Costs may include:

API Usage
Network

Local

Application
    โ†“
Local Embedding Model

Costs shift toward:

Compute
GPU/CPU
Memory
Operations

Neither is universally cheaper.


๐Ÿง  31. Reranking Cost

Rerankers can be expensive because they may evaluate many query-document pairs.

Conceptually:

Cost โˆ Number of Candidates

๐Ÿง  32. Candidate Reduction

Instead of:

Retrieve 500
 โ†“
Rerank 500

use:

Dense Retrieval โ†’ 30
Sparse Retrieval โ†’ 30
Merge โ†’ 50
Rerank โ†’ 50
Select โ†’ 6

๐Ÿง  33. Reranker Selection

Possible options:

Lightweight Reranker
Cross-Encoder
LLM Reranker

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:

Do not call an LLM unless necessary.

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:

Complexity
Risk
Latency
Cost
Required Reasoning

๐Ÿง  38. Model Cascade

Small Model
     โ†“
Confidence
 โ”‚
 โ”œโ”€โ”€ High โ†’ Final Answer
 โ”‚
 โ””โ”€โ”€ Low โ†’ Large Model

Average cost can decrease if most queries are successfully handled by the smaller model.


๐Ÿง  39. Model Routing Example

FAQ
   โ†“
Small Model

Technical Design
   โ†“
Medium Model

Complex Multi-Hop Reasoning
   โ†“
Large Model

๐Ÿง  40. Model Routing Economics

Suppose:

80% queries โ†’ Small Model
20% queries โ†’ Large Model

instead of:

100% โ†’ Large Model

the average cost can be substantially lower, assuming quality remains acceptable.


๐Ÿง  41. Output Token Optimization

Output tokens directly affect:

Cost
Latency

Use:

Response Length Policies
Max Output Tokens
Structured Output
Concise Instructions

๐Ÿง  42. Output Budget

Simple Answer
    โ†“
200 tokens

Technical Explanation
    โ†“
800 tokens

Detailed Analysis
    โ†“
1500 tokens

Do not allocate the maximum output budget to every request.


๐Ÿง  43. Response Contract

Example:

Answer:
Maximum 5 bullet points.

Citations:
Only sources actually used.

Do not repeat the question.

This reduces unnecessary output.


๐Ÿง  44. Prompt Optimization

Prompt cost includes:

System Prompt
Examples
Instructions
Context
Conversation History
Tool Results

Reduce:

Repeated Instructions
Unused Examples
Duplicate Context
Excessive Formatting

๐Ÿง  45. Prompt Versioning

Use:

prompt-v1
prompt-v2
prompt-v3

Measure:

Quality
Tokens
Latency
Cost

A shorter prompt is not automatically better if quality drops.


๐Ÿง  46. Prompt Caching

If supported by the model/provider:

Static Prompt Prefix
        โ†“
Cache
        โ†“
Dynamic Context + Query

Potentially reduces:

Cost
Latency

๐Ÿง  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:

Full History
     โ†“
Conversation Summary
     โ†“
Relevant Recent Turns
     โ†“
LLM

๐Ÿง  49. Memory Budget

Set:

Maximum Conversation Context

Use:

Summary
+
Relevant Turns
+
Current Query

rather than blindly sending the complete conversation.


๐Ÿง  50. Semantic Conversation Selection

Retrieve only relevant historical messages:

Conversation Memory
        โ†“
Semantic Search
        โ†“
Relevant Turns
        โ†“
Prompt

This reduces token usage.


๐Ÿง  51. Retrieval Cache

Cache retrieval results for repeated requests.

Key should account for:

Normalized Query
Retriever Version
Index Version
Metadata Filter
Tenant
Authorization Context

๐Ÿง  52. Cache Economics

If:

100,000 requests

and:

30% cache hits

then:

30,000 requests

may avoid some downstream computation.

Actual savings depend on what the cache bypasses.


๐Ÿง  53. Semantic Cache

Example:

Query A:
"What database does payment use?"

Query B:
"Which DB is used by payments?"

Potentially reuse the result.

But semantic caching must validate:

Intent
Freshness
Authorization
Tenant
Knowledge Version

๐Ÿง  54. Cache Invalidation

Invalidate when:

Document Changes
Index Changes
Embedding Changes
Prompt Changes
Retriever Changes
Authorization Changes

๐Ÿง  55. Cache Versioning

Example:

tenant-a:
index:v12
retriever:v5
prompt:v8
embedding:v3

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:

Tenant A โ†’ $120/month
Tenant B โ†’ $480/month
Tenant C โ†’ $75/month

This enables:

Chargeback
Budgeting
Quota Management
Optimization

๐Ÿง  58. Cost Per User

Track:

Requests/User
Tokens/User
Cost/User
Model Usage/User

Avoid exposing user-level data broadly; apply appropriate privacy and access controls.


๐Ÿง  59. Cost by Application

Enterprise platforms may host:

Support Copilot
Developer Assistant
Legal Assistant
Finance Assistant
Research Assistant

Track cost separately.

Application
    โ†“
Requests
    โ†“
Tokens
    โ†“
Cost

๐Ÿง  60. Cost by Workflow

A single application may have:

Simple Search
Complex RAG
Agentic RAG
Graph RAG
SQL RAG
Document Analysis

Each can have a different cost profile.


๐Ÿง  61. Cost by Model

Track:

Model A
Model B
Model C

with:

Requests
Tokens
Latency
Quality
Cost

๐Ÿง  62. Cost by Provider

For multi-cloud enterprise systems:

AWS
Azure
GCP
External Providers
Self-Hosted Models

compare:

Cost
Latency
Quality
Availability

๐Ÿง  63. Reranking Cost by Query

Some queries may require:

No Reranking

others:

50 candidates

and complex queries:

100 candidates

Use query-aware policies.


๐Ÿง  64. Agentic RAG Cost

Agentic RAG can multiply cost.

User Query
   โ†“
Planner
   โ†“
Tool
   โ†“
Observation
   โ†“
Planner
   โ†“
Tool
   โ†“
Observation
   โ†“
LLM

Potentially:

Multiple LLM Calls
+
Multiple Retrieval Calls
+
Multiple Tool Calls

๐Ÿง  65. Agentic RAG Cost Guardrails

Define:

Max Iterations
Max Tool Calls
Max Tokens
Max Execution Time
Max Cost

Example:

Max Steps = 5
Max Tools = 8
Max Cost = $0.10

๐Ÿง  66. Agentic Early Termination

Agent
 โ†“
Evidence Sufficient?
 โ”‚
 โ”œโ”€โ”€ Yes โ†’ Final Answer
 โ””โ”€โ”€ No โ†’ Continue

Avoid unnecessary planning loops.


๐Ÿง  67. Agentic Loop Detection

Potential problem:

Plan
 โ†“
Search
 โ†“
Plan
 โ†“
Search
 โ†“
Plan
 โ†“
Search

Use:

Iteration Limit
Repeated Action Detection
Budget Limit

๐Ÿง  68. Graph RAG Cost

Graph RAG may require:

Graph Query
Entity Retrieval
Relationship Traversal
Subgraph Construction
LLM Reasoning

Cost can increase with traversal depth.


๐Ÿง  69. Graph Traversal Budget

Instead of:

Unlimited Traversal

use:

Maximum Hops
Maximum Nodes
Maximum Edges
Maximum Graph Query Time

๐Ÿง  70. SQL RAG Cost

SQL RAG can generate expensive queries.

Potential risks:

Large Table Scan
Complex Join
Repeated Query
Unbounded Result Set

Use:

Query Limits
Timeouts
Read-Only Access
Pagination
Query Validation

๐Ÿง  71. SQL Result Budget

Instead of:

100,000 rows

use:

Top-N
Aggregations
Pagination
Server-Side Filtering

Only return data required for reasoning.


๐Ÿง  72. Multimodal RAG Cost

Multimodal workloads may involve:

OCR
Vision Models
Image Embeddings
Text Embeddings
Image Storage
Large Context

Optimize using:

Selective OCR
Image Resizing
Compression
Cached Embeddings
Model Routing

๐Ÿง  73. Image Processing Cost

Avoid processing every image at maximum resolution.

Image
 โ†“
Determine Required Resolution
 โ†“
Resize
 โ†“
Vision Model

๐Ÿง  74. Validation Cost

If every answer invokes:

Primary LLM
+
Validation LLM
+
Citation LLM

the cost can multiply.

Possible alternatives:

Rules
+
Cheap Model
+
Selective Deep Validation

๐Ÿง  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.

Retriever
 โ†“
Chunk Metadata
 โ†“
Context
 โ†“
Response
 โ†“
Citation

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:

CPU Utilization
Memory
GPU Utilization
Autoscaling
Instance Size
Workload Scheduling

๐Ÿง  79. CPU vs GPU

Use GPU when:

High Model Throughput
Large Embedding Workloads
Local Reranking
Local LLM Inference

CPU may be more appropriate for:

Lightweight Retrieval
Metadata Filtering
Small Embedding Models
Low-Volume Workloads

๐Ÿง  80. GPU Utilization

Poor:

GPU Utilization = 15%

while paying for a large GPU.

Potential solutions:

Batching
Smaller GPU
Higher Concurrency
Model Quantization
Autoscaling

๐Ÿง  81. Autoscaling

Scale based on:

Requests/sec
Queue Depth
CPU
Memory
GPU
Token Throughput
Latency

๐Ÿง  82. Scale-to-Zero

For workloads that are:

Low Traffic
Batch
Development
Evaluation

scale-to-zero or scheduled compute can reduce infrastructure cost where supported.


๐Ÿง  83. Vector Database Cost

Vector DB cost depends on:

Data Size
Vector Dimensions
Replication
Queries
Storage
Compute
Index Type
High Availability

๐Ÿง  84. Vector Storage Optimization

Reduce:

Vector Dimensions
Duplicate Vectors
Unused Metadata
Old Versions
Redundant Indexes

where quality and operational requirements permit.


๐Ÿง  85. Data Lifecycle

Implement:

Hot
 โ†“
Warm
 โ†“
Cold
 โ†“
Archive
 โ†“
Delete

Not every document needs identical storage characteristics.


๐Ÿง  86. Document Retention

Enterprise knowledge bases may contain:

Active Documents
Historical Documents
Expired Documents
Archived Documents

Remove expired data from the active retrieval path when policy allows.


๐Ÿง  87. Storage Tiering

Hot Knowledge
    โ†“
Fast Vector Search

Cold Knowledge
    โ†“
Lower-Cost Storage

Retrieve cold data only when required.


๐Ÿง  88. Network Cost

Network costs may come from:

LLM API Calls
Vector DB
Object Storage
Cross-Region Traffic
Microservice Calls
Telemetry

Reduce unnecessary payloads and cross-region communication.


๐Ÿง  89. Region Optimization

Choose infrastructure locations based on:

Latency
Data Residency
Compliance
Availability
Provider Pricing

Do not optimize cost by violating data residency or regulatory requirements.


๐Ÿง  90. Observability Cost

Observability can become expensive when capturing:

Full Prompts
Full Context
Full Documents
Every Trace
Every Token

Use:

Sampling
Redaction
Aggregation
Retention
Selective Payload Capture

๐Ÿง  91. Evaluation Cost

RAG evaluation can itself consume LLM calls.

Production Dataset
      โ†“
Evaluation Model
      โ†“
Scores

Large evaluation suites can become expensive.


๐Ÿง  92. Evaluation Sampling

Instead of evaluating:

100% of requests

consider:

100% Critical Requests
100% Failures
100% Low-Quality Signals
Sample Normal Requests

The right sampling policy depends on the application's risk.


๐Ÿง  93. Continuous Evaluation Cost

Use:

Offline Evaluation
+
Production Sampling
+
Human Review

rather than evaluating every request with expensive models.


๐Ÿง  94. Cost-Aware Evaluation

Prioritize:

New Model
New Retriever
New Prompt
New Knowledge Base
High-Risk Domain
Production Regression

๐Ÿง  95. Cost Anomaly Detection

Monitor:

Average Cost / Request
Tokens / Request
Requests / Tenant
Model Distribution
Cache Hit Rate

๐Ÿง  96. Cost Spike Example

Normal:

$0.018/request

Suddenly:

$0.031/request

Investigate:

Context Tokens โ†‘
Model Routing Changed
Reranking Enabled
Validation Added
Cache Hit Rate โ†“

๐Ÿง  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:

Daily Cost = $2,160
Daily Requests = 120,000

then:

Cost/request
=
2160 / 120000
=
$0.018

๐Ÿง  100. Monthly Cost Forecast

A simple estimate:

Monthly Cost
=
Average Daily Cost ร— Number of Days

Example:

$2,160 ร— 30
=
$64,800

This is a simple forecast and does not account for traffic growth or tiered pricing.


๐Ÿง  101. Cost Forecasting

Forecast using:

Requests
+
Tokens
+
Model Mix
+
Infrastructure

Example:

Current:
100K requests/day

Projected:
200K requests/day

But cost may not exactly double if:

Caching improves
Model mix changes
Reserved capacity applies

๐Ÿง  102. Cost Elasticity

Measure:

Traffic +10%
Cost +?

A highly elastic architecture may scale cost almost linearly.

An optimized architecture can sometimes achieve:

Traffic โ†‘
Cost โ†‘ slower than traffic

through:

Caching
Batching
Autoscaling
Efficient Models

๐Ÿง  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:

Total Cost:
$10,000

High-Quality Answers:
800,000

Then:

$10,000 / 800,000
=
$0.0125

๐Ÿง  105. Quality-Adjusted Cost

Conceptually:

Quality-Adjusted Cost
=
Cost
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Quality Score

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:

Cost       Quality

$0.01       85%
$0.015      91%
$0.02       94%
$0.04       95%
$0.08       95.5%

The additional:

$0.04

may not justify:

+0.5%

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:

Request Budget = $0.10

Pipeline:

Query
 โ†“
Budget Check
 โ†“
Retrieval
 โ†“
Reranking
 โ†“
Generation
 โ†“
Remaining Budget?

๐Ÿง  111. Budget-Aware Routing

Budget = $0.10

Small Model:
$0.01

Reranker:
$0.02

Large Model:
$0.08

If the request has already consumed:

$0.07

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:

Tenant A
Monthly Budget:
$5,000

Tenant B
Monthly Budget:
$2,000

Use:

Quota
Warning Threshold
Hard Limit

according to business policy.


๐Ÿง  114. Soft vs Hard Budgets

Soft Budget

80%
 โ†“
Warning

Hard Budget

100%
 โ†“
Block / Degrade

๐Ÿง  115. Graceful Degradation

When budget is constrained:

Large Model
    โ†“
Small Model

or:

Advanced RAG
    โ†“
Fast Retrieval

or:

Deep Validation
    โ†“
Light Validation

๐Ÿง  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:

Quality
Latency
Cost

not only:

Similarity Score

๐Ÿง  118. Cost-Aware Query Routing

Query
 โ”‚
 โ”œโ”€โ”€ Cheap Route
 โ”‚
 โ”œโ”€โ”€ Standard Route
 โ”‚
 โ””โ”€โ”€ Expensive Route

Use the expensive route only when required.


๐Ÿง  119. Cost-Aware Validation

Low Risk
  โ†“
No expensive validator

Medium Risk
  โ†“
Cheap validator

High Risk
  โ†“
Deep validator

๐Ÿง  120. Cost-Aware Agentic RAG

Agent should understand:

Remaining Budget
Remaining Steps
Remaining Tokens

Example:

{
  "max_cost": 0.10,
  "spent": 0.063,
  "remaining": 0.037,
  "max_steps": 5,
  "steps_used": 3
}

๐Ÿง  121. Cost-Aware Graph RAG

Use:

Maximum Hops
Maximum Nodes
Maximum Edges
Maximum Query Time

to prevent runaway graph exploration.


๐Ÿง  122. Cost-Aware SQL RAG

Use:

Query Timeout
Row Limit
Read-Only Mode
Cost Estimation
Execution Plan

where supported.


๐Ÿง  123. Cost-Aware Multimodal RAG

Use:

Image Resolution Policy
OCR Selection
Vision Model Routing
Image Cache
Embedding Cache

๐Ÿง  124. Cost-Aware Evaluation

Prioritize evaluation of:

New Models
New Prompts
New Retrieval
High-Risk Queries
Production Failures
User Negative Feedback

๐Ÿง  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:

Top-K              = 20
Reranker           = 20
Context            = 8,000 tokens
LLM                = Large
Validation         = Large LLM
Cache              = None

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:

Reducing context from 8K
to 4K tokens will reduce cost
without materially reducing quality.

Measure:

Cost
Latency
Faithfulness
Answer Relevance
Citation Accuracy

๐Ÿง  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:

Token Usage
LLM Calls
Retrieval
Reranking
Context
Caching
Model Selection
Infrastructure

๐Ÿงช 132. Baseline Project

Query
 โ†“
Embedding
 โ†“
Vector Search
 โ†“
Top-10
 โ†“
Reranking
 โ†“
Large LLM
 โ†“
Validation LLM
 โ†“
Response

Measure:

Cost
Latency
Tokens
Quality

๐Ÿงช 133. Optimization Stage 1 โ€” Context

Change:

10 chunks

to:

Adaptive context selection

Measure:

Tokens
Cost
Quality

๐Ÿงช 134. Optimization Stage 2 โ€” Reranking

Change:

Rerank 100

to:

Retrieve 50
Rerank 30
Select 6

Measure:

Latency
Cost
Recall
Answer Quality

๐Ÿงช 135. Optimization Stage 3 โ€” Model Routing

Simple
 โ†“
Small Model

Complex
 โ†“
Large Model

Measure:

Model Distribution
Cost
Quality
Latency

๐Ÿงช 136. Optimization Stage 4 โ€” Caching

Add:

Embedding Cache
Retrieval Cache
Semantic Cache

Measure:

Hit Rate
Cost Reduction
Latency Reduction

๐Ÿงช 137. Optimization Stage 5 โ€” Adaptive Retrieval

Initial Retrieval
      โ†“
Confidence
 โ”‚
 โ”œโ”€โ”€ High โ†’ Generate
 โ””โ”€โ”€ Low โ†’ Expand

Measure:

Average Retrieval Work
Cost
Recall
Quality

๐Ÿงช 138. Optimization Stage 6 โ€” Budget Guardrails

Implement:

Max Cost
Max Tokens
Max LLM Calls
Max Retrieval Candidates
Max Agent Steps

Test:

Normal Query
Complex Query
Adversarial Query
Runaway Agent

๐Ÿงช 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:

Input Tokens
Output Tokens
Context Tokens
Conversation Tokens
Tool Tokens
Total Tokens

๐Ÿงช 143. Model Metrics

Track:

Model
Requests
Tokens
Latency
Quality
Cost
Fallback Rate

๐Ÿงช 144. Cache Metrics

Track:

Cache Hit Rate
Cache Miss Rate
Saved Requests
Saved Tokens
Saved Cost
Stale Results
Invalidations

๐Ÿงช 145. Budget Metrics

Track:

Budget Utilization
Requests Over Budget
Soft Limit Warnings
Hard Limit Blocks
Graceful Degradations

๐Ÿงช 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

Tenant      Requests     Tokens       Cost

Tenant A      40K        120M       $1,200
Tenant B      20K         90M         $900
Tenant C      10K         30M         $300

This enables chargeback and optimization.


๐Ÿงช 148. Cost Anomaly Detection

Alert when:

Cost/request > baseline ร— 1.30

or:

Daily cost > expected budget

or:

Token usage increases unexpectedly

๐Ÿงช 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:

Budget
Quota
Model Policy
Token Policy
Retention Policy
Cache Policy
Routing Policy

๐Ÿง  151. Model Governance

Define:

Approved Models
Maximum Model Tier
Allowed Providers
Allowed Regions
Fallback Models

๐Ÿง  152. Cost Governance by Risk

Different workloads can have different budgets:

Low Risk
   โ†“
Low-Cost Model

Medium Risk
   โ†“
Standard Model

High Risk
   โ†“
Premium Model + Validation

๐Ÿง  153. FinOps for RAG

RAG can adopt FinOps principles:

Visibility
      โ†“
Allocation
      โ†“
Optimization
      โ†“
Governance
      โ†“
Continuous Improvement

๐Ÿง  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

Track LLM Cost

Level 2 โ€” Token Visibility

Input
Output
Context

Level 3 โ€” Component Cost

Embedding
Retrieval
Reranking
LLM

Level 4 โ€” Cost Attribution

Tenant
User
Application
Workflow

Level 5 โ€” Cost Controls

Budgets
Quotas
Guardrails

Level 6 โ€” Cost-Aware RAG

Adaptive Retrieval
Model Routing
Caching
Context Optimization

Level 7 โ€” Autonomous Optimization

Measure
   โ†“
Detect
   โ†“
Optimize
   โ†“
Benchmark
   โ†“
Deploy

๐Ÿง  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:

Cache
Early Exit
Routing
Deduplication

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:

Reranking
Query Rewriting
Validation
Agent Planning

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.