07. RAG Observability¶
Category: Production RAG Engineering
Module: Part V β Advanced Retrieval-Augmented Generation
Difficulty: Advanced
π Overview¶
A production RAG system is not observable simply because application logs exist.
Enterprise RAG introduces a multi-stage execution pipeline:
User Query
β
Query Processing
β
Query Rewriting
β
Embedding
β
Retrieval
β
Filtering
β
Reranking
β
Context Selection
β
Prompt Assembly
β
LLM Generation
β
Response Validation
β
Citation
β
Enterprise Response
When a user receives a poor answer, engineers need to determine:
Was the query rewritten incorrectly?
Did embedding fail?
Did retrieval return the wrong documents?
Did metadata filtering remove valid evidence?
Did reranking select poor results?
Was useful context discarded?
Was the prompt assembled incorrectly?
Did the LLM hallucinate?
Did response validation fail?
Were citations incorrect?
Was the request slow because of retrieval or generation?
Why did token usage increase?
Why did cost increase?
Traditional application logs are often insufficient to answer these questions.
Production RAG therefore requires end-to-end observability across the complete retrieval, reasoning, generation, and response pipeline.
The objective is not simply to collect more logs.
The objective is to create a system where every important RAG decision can be:
Production RAG observability connects system execution with answer quality, performance, cost, security, and user experience.
π― Learning Objectives¶
After completing this chapter, you will be able to:
- Understand observability in RAG systems
- Understand RAG observability vs traditional application observability
- Design end-to-end RAG traces
- Design RAG spans
- Trace retrieval pipelines
- Trace reranking
- Trace query rewriting
- Trace context selection
- Trace prompt assembly
- Trace LLM calls
- Trace response validation
- Trace citation generation
- Capture token usage
- Monitor latency
- Monitor throughput
- Monitor errors
- Monitor retries
- Monitor fallbacks
- Monitor retrieval quality signals
- Monitor context quality signals
- Monitor generation quality signals
- Monitor citation quality signals
- Monitor cost
- Implement structured logging
- Implement distributed tracing
- Design RAG-specific metrics
- Design RAG dashboards
- Build production alerts
- Perform trace-based debugging
- Correlate quality with infrastructure metrics
- Detect RAG regressions
- Detect retrieval failures
- Detect model failures
- Detect prompt failures
- Detect cost anomalies
- Detect latency regressions
- Implement tenant-aware observability
- Design privacy-aware observability
- Build enterprise-grade RAG observability architecture
π§ 1. What Is RAG Observability?¶
RAG observability is the ability to understand:
What happened?
Why did it happen?
Where did it happen?
How long did it take?
How much did it cost?
What evidence was used?
What answer was generated?
Was the answer trustworthy?
A useful model is:
RAG Observability
β
βββ Logs
βββ Metrics
βββ Traces
βββ Events
βββ Quality Signals
βββ Cost Signals
βββ Security Signals
π§ 2. Traditional Observability vs RAG Observability¶
Traditional backend observability often focuses on:
RAG requires those metrics plus AI-specific signals:
Retrieved Documents
Retrieval Scores
Reranker Scores
Context Size
Prompt Size
LLM Tokens
Model
Temperature
Citations
Grounding
Faithfulness
Answer Quality
Cost
π§ 3. The Three Pillars¶
The classic observability model is:
OBSERVABILITY
β
βββββββββββββΌββββββββββββ
βΌ βΌ βΌ
LOGS METRICS TRACES
For RAG, extend this with:
RAG OBSERVABILITY
β
βββββββββββββββββΌβββββββββββββββββ
βΌ βΌ βΌ
Logs Metrics Traces
β β β
βββββββββββββββββΌβββββββββββββββββ
βΌ
AI QUALITY
β
ββββββββββββββΌβββββββββββββ
βΌ βΌ βΌ
Retrieval Generation Citation
Quality Quality Quality
π§ 4. Logs¶
Logs answer:
What happened?
Example:
Logs are useful for:
π§ 5. Metrics¶
Metrics answer:
How often and how much?
Examples:
RAG requests / second
p95 latency
retrieval failure rate
average top-K
average context tokens
LLM tokens
cost / request
citation coverage
Metrics are ideal for:
π§ 6. Traces¶
Traces answer:
What happened during this particular request?
Example:
Trace
β
βββ Query Processing 12 ms
βββ Embedding 25 ms
βββ Vector Search 42 ms
βββ BM25 Search 31 ms
βββ Reranking 88 ms
βββ Context Selection 14 ms
βββ LLM 920 ms
βββ Validation 18 ms
βββ Citation 11 ms
π§ 7. Why Traces Matter¶
Suppose:
Without tracing:
With tracing:
The bottleneck becomes obvious.
π§ 8. End-to-End RAG Trace¶
flowchart TD
A["User Request"] --> B["Query Processing"]
B --> C["Query Rewriting"]
C --> D["Embedding"]
D --> E["Retrieval"]
E --> F["Filtering"]
F --> G["Reranking"]
G --> H["Context Selection"]
H --> I["Prompt Assembly"]
I --> J["LLM"]
J --> K["Response Validation"]
K --> L["Citation"]
L --> M["Final Response"]
A -.-> N["Trace"]
B -.-> N
C -.-> N
D -.-> N
E -.-> N
F -.-> N
G -.-> N
H -.-> N
I -.-> N
J -.-> N
K -.-> N
L -.-> N
π§ 9. Trace and Span¶
A trace represents the complete request.
A span represents one operation.
Trace
β
βββ Query Processing Span
βββ Embedding Span
βββ Retrieval Span
βββ Reranking Span
βββ Context Span
βββ Prompt Span
βββ LLM Span
βββ Validation Span
βββ Citation Span
π§ 10. Parent-Child Spans¶
RAG Request
β
βββ Retrieval
β βββ Vector Search
β βββ BM25 Search
β
βββ Reranking
β
βββ Generation
β βββ LLM Call
β
βββ Validation
This allows engineers to see both:
π§ 11. RAG Trace Context¶
A trace should propagate through services:
API Gateway
β
RAG Service
β
Retrieval Service
β
Vector DB
β
Reranker Service
β
LLM Gateway
β
Validation Service
The same trace context should be maintained where supported.
π§ 12. Trace ID¶
Every request should have a unique trace identifier.
Use it to correlate:
π§ 13. Request ID vs Trace ID¶
They solve different problems.
A single user request may cross multiple microservices.
π§ 14. Correlation IDs¶
Useful identifiers include:
Be careful with:
These should not be blindly logged.
π§ 15. RAG Trace Data¶
A RAG trace can capture:
{
"trace_id": "abc-123",
"request_id": "req-901",
"model": "enterprise-llm",
"retriever": "hybrid",
"top_k": 10,
"context_tokens": 4200,
"input_tokens": 5100,
"output_tokens": 340,
"latency_ms": 1820
}
π§ 16. Query Processing Observability¶
Track:
Original Query
Query Type
Query Length
Language
Query Rewrite
Number of Generated Queries
Classification
Routing Decision
Example:
Original:
"What DB does payment use?"
Rewritten:
"payment service database technology"
Queries Generated:
3
π§ 17. Query Rewrite Observability¶
For advanced query rewriting:
Capture:
π§ 18. Multi-Query Observability¶
Example:
Track:
Generated Queries
Successful Queries
Duplicate Queries
Retrieval Results per Query
Final Merged Results
π§ 19. Embedding Observability¶
Track:
Example:
π§ 20. Retrieval Observability¶
Track:
Example:
π§ 21. Retrieval Score Distribution¶
Scores can help detect retrieval problems.
Score
1.0 β€
0.8 β€ β
0.6 β€ β β β
0.4 β€ β β β β
0.2 β€ β β β β
βββββββββββββββββ
1 2 3 4 5
Rank
A sudden drop in score distribution may indicate:
π§ 22. Retrieval Score Observability¶
Track:
Example:
These are diagnostic signals, not universal quality guarantees.
π§ 23. Retrieval Result Observability¶
Track:
Example:
{
"document_id": "DOC-1024",
"chunk_id": "C-17",
"rank": 1,
"score": 0.91,
"source": "architecture-guide"
}
π§ 24. Metadata Filtering Observability¶
Track:
Example:
If this suddenly becomes:
it may indicate a filtering problem.
π§ 25. Tenant-Aware Retrieval Observability¶
For enterprise systems:
must remain isolated.
Observe:
Never expose sensitive tenant data through unrestricted logs.
π§ 26. Reranking Observability¶
Track:
Example:
π§ 27. Reranking Score Changes¶
Useful diagnostic:
This can help diagnose ranking behavior.
π§ 28. Context Selection Observability¶
Track:
Example:
π§ 29. Context Compression Ratio¶
A useful operational signal:
Compression Ratio
=
Selected Context Size
ββββββββββββββββββββ
Original Context Size
Example:
π§ 30. Prompt Observability¶
Track:
Prompt Version
Prompt Template
System Prompt Version
Context Tokens
Instruction Tokens
Total Input Tokens
Avoid storing sensitive raw prompts unless required and appropriately protected.
π§ 31. Prompt Versioning¶
Example:
When answer quality changes:
the prompt becomes a candidate cause.
π§ 32. LLM Observability¶
Track:
Provider
Model
Model Version
Temperature
Max Tokens
Input Tokens
Output Tokens
Total Tokens
Latency
Time to First Token
Finish Reason
Errors
Retries
π§ 33. LLM Latency¶
Separate:
from:
This helps distinguish:
π§ 34. Token Observability¶
Track:
Example:
π§ 35. Token Growth Detection¶
Monitor:
over time.
Example:
Possible causes:
π§ 36. Cost Observability¶
Track:
Embedding Cost
Retrieval Cost
Reranker Cost
LLM Input Cost
LLM Output Cost
Evaluation Cost
Infrastructure Cost
π§ 37. Cost Per Request¶
Example:
Embedding $0.0002
Reranking $0.0015
LLM Input $0.0120
LLM Output $0.0030
Infrastructure $0.0010
-----------------------
Total $0.0177
π§ 38. Cost by Tenant¶
Enterprise systems may require:
This helps with:
π§ 39. Cost by Model¶
Compare:
rather than cost alone.
π§ 40. RAG Error Observability¶
Classify failures:
QUERY_ERROR
EMBEDDING_ERROR
RETRIEVAL_ERROR
FILTER_ERROR
RERANKING_ERROR
CONTEXT_ERROR
PROMPT_ERROR
LLM_ERROR
VALIDATION_ERROR
CITATION_ERROR
TIMEOUT
RATE_LIMIT
SECURITY_ERROR
π§ 41. Error Rate¶
Track:
But also classify errors.
An overall:
does not tell you whether the failures are:
or:
π§ 42. Retry Observability¶
Track:
Example:
Retries can improve reliability but increase:
π§ 43. Fallback Observability¶
Example:
Track:
π§ 44. Circuit Breaker Observability¶
For external services:
track:
π§ 45. RAG SLOs¶
Production RAG can define SLOs such as:
Availability >= 99.9%
p95 Latency <= 2 seconds
Error Rate <= 0.5%
Citation Accuracy >= 95%
Faithfulness >= 90%
Quality thresholds should be defined according to the application and risk level.
π§ 46. Quality SLOs¶
Unlike traditional services, RAG can have AI quality SLOs:
This creates:
π§ 47. Error Budget¶
Traditional:
RAG can also track:
Example:
π§ 48. RAG Health Score¶
A dashboard may combine:
into a health view.
However:
Do not hide critical failures behind a single aggregate health score.
π§ 49. RAG Observability Dashboard¶
βββββββββββββββββββββββββββββββββββββββββββββββ
β RAG OVERVIEW β
βββββββββββββββββββββββββββββββββββββββββββββββ€
β Requests/sec 142 β
β p95 Latency 1.82s β
β Error Rate 0.31% β
β β
β Retrieval Recall 93.1% β
β Faithfulness 95.7% β
β Citation Accuracy 97.2% β
β β
β Avg Context Tokens 4,210 β
β Avg Total Tokens 5,020 β
β Cost / Request $0.018 β
β β
β Fallback Rate 0.8% β
β Abstention Rate 3.2% β
βββββββββββββββββββββββββββββββββββββββββββββββ
Values are illustrative.
π§ 50. Retrieval Dashboard¶
βββββββββββββββββββββββββββββββββββββββ
β RETRIEVAL OBSERVABILITY β
βββββββββββββββββββββββββββββββββββββββ€
β Recall@5 88.4% β
β Recall@10 94.1% β
β Hit Rate 96.2% β
β MRR 81.7% β
β NDCG@5 79.8% β
β β
β Avg Top-1 Score 0.91 β
β Avg Top-K Score 0.74 β
β Avg Results 10 β
β Retrieval p95 96 ms β
βββββββββββββββββββββββββββββββββββββββ
π§ 51. Generation Dashboard¶
βββββββββββββββββββββββββββββββββββββββ
β GENERATION QUALITY β
βββββββββββββββββββββββββββββββββββββββ€
β Faithfulness 95.7% β
β Answer Relevance 93.8% β
β Completeness 91.2% β
β Groundedness 96.1% β
β Citation Accuracy 97.2% β
β Citation Coverage 95.9% β
βββββββββββββββββββββββββββββββββββββββ
π§ 52. Latency Dashboard¶
Total p95 Latency
β
βββ Query Processing 20ms
βββ Embedding 35ms
βββ Retrieval 70ms
βββ Reranking 120ms
βββ Context 15ms
βββ LLM 1,420ms
βββ Validation 25ms
βββ Citation 12ms
π§ 53. Cost Dashboard¶
Monthly Cost
β
βββ LLM 68%
βββ Embeddings 12%
βββ Reranking 8%
βββ Vector DB 7%
βββ Observability 5%
This helps prioritize optimization.
π§ 54. Trace Visualization¶
A production trace might look like:
TRACE: 4c9d8c7e
0ms βββββββββββββββββββββββββββββββββββββββββ 1800ms
Query βββ
Embedding ββββ
Retrieval βββββββ
Reranking βββββββββββ
Context βββ
Prompt βββ
LLM βββββββββββββββββ
Validation ββ
Citation ββ
This quickly exposes latency bottlenecks.
π§ 55. Trace Waterfall¶
sequenceDiagram
participant U as User
participant API as RAG API
participant R as Retriever
participant RR as Reranker
participant L as LLM
participant V as Validator
participant C as Citation
U->>API: Query
API->>R: Retrieve
R-->>API: Documents
API->>RR: Rerank
RR-->>API: Ranked Context
API->>L: Generate
L-->>API: Answer
API->>V: Validate
V-->>API: Valid
API->>C: Attribute Sources
C-->>API: Citations
API-->>U: Response
π§ 56. Span Attributes¶
A retrieval span may include:
retriever.type
retriever.top_k
retriever.index
retriever.collection
retriever.filter
retriever.result_count
retriever.latency_ms
A generation span:
llm.provider
llm.model
llm.temperature
llm.input_tokens
llm.output_tokens
llm.total_tokens
llm.latency_ms
llm.finish_reason
π§ 57. Span Events¶
Events can record important moments:
query_rewritten
retrieval_completed
reranking_completed
context_compressed
llm_retry
validation_failed
citation_added
fallback_triggered
π§ 58. Structured Logging¶
Prefer structured logs:
{
"timestamp": "2026-08-11T10:15:30Z",
"level": "INFO",
"service": "rag-service",
"trace_id": "abc123",
"event": "retrieval_completed",
"retriever": "hybrid",
"top_k": 10,
"result_count": 10,
"latency_ms": 72
}
Structured logs are easier to query and aggregate.
π§ 59. Bad Logging¶
Avoid:
This is difficult to search or aggregate.
Prefer:
π§ 60. Sensitive Data Logging¶
Never blindly log:
RAG systems may process highly sensitive enterprise information.
π§ 61. Prompt Logging Strategy¶
Possible levels:
Level 0
No prompt content
Level 1
Metadata only
Level 2
Redacted prompt
Level 3
Encrypted prompt storage
Level 4
Full prompt with strict access controls
Choose based on:
π§ 62. Document Logging Strategy¶
Avoid storing complete sensitive documents inside traces.
Instead capture:
Example:
π§ 63. Trace Sampling¶
Tracing every request can be expensive.
Possible strategies:
100% Errors
100% High-Latency Requests
100% Security Events
10% Normal Requests
1% Low-Value Requests
Actual sampling should depend on system requirements.
π§ 64. Tail-Based Sampling¶
Instead of deciding sampling before seeing the result:
Keep traces with:
π§ 65. Quality-Based Sampling¶
A powerful RAG-specific strategy:
Possible triggers:
π§ 66. User Feedback Observability¶
Capture:
User behavior can become an important quality signal.
π§ 67. Feedback Correlation¶
Correlate:
Example:
π§ 68. Citation Click Observability¶
If citations are interactive:
Track:
This can help understand whether users trust and use citations.
π§ 69. Conversation Observability¶
For conversational RAG:
Track:
π§ 70. Conversation Context Growth¶
Long conversations can create:
Monitor:
π§ 71. Memory Observability¶
For memory-enabled RAG:
π§ 72. Agentic RAG Observability¶
Agentic RAG requires additional tracing:
π§© 73. Agentic RAG Trace¶
flowchart TD
A["User Query"] --> B["Planner"]
B --> C["Tool Selection"]
C --> D["Retriever"]
D --> E["Observation"]
E --> F{"Enough Evidence?"}
F -->|No| B
F -->|Yes| G["Generation"]
G --> H["Validation"]
H --> I["Final Answer"]
Track:
π§ 74. Graph RAG Observability¶
Track:
Entities Retrieved
Relationships Retrieved
Graph Traversal Depth
Nodes Visited
Edges Visited
Subgraph Size
Graph Query Latency
Example:
π§ 75. SQL RAG Observability¶
Track:
Generated SQL
Schema Selected
Tables
Columns
Execution Time
Rows Returned
Query Success
Validation Result
Do not expose sensitive SQL or data without appropriate controls.
π§ 76. SQL Safety Observability¶
Track whether generated SQL attempted:
Production SQL RAG should have explicit read/write policies.
π§ 77. Multimodal RAG Observability¶
Track:
Image ID
Document ID
OCR
Vision Model
Image Embedding
Text Embedding
Cross-Modal Retrieval
Visual Context
π§ 78. Evaluation + Observability¶
These systems complement each other.
Together:
π§ 79. Quality-Trace Correlation¶
Suppose:
Trace analysis may show:
which may show:
The chain becomes:
Model Change
β
Embedding Change
β
Retrieval Degradation
β
Context Degradation
β
Faithfulness Degradation
This is the real value of RAG observability.
π§ 80. Root Cause Analysis¶
A production debugging workflow:
User Complaint
β
Find Trace
β
Inspect Latency
β
Inspect Retrieval
β
Inspect Ranking
β
Inspect Context
β
Inspect Prompt
β
Inspect LLM
β
Inspect Validation
β
Inspect Citation
π§ 81. Retrieval Failure Debugging¶
Potential causes:
π§ 82. Generation Failure Debugging¶
Possible causes:
π§ 83. Citation Failure Debugging¶
Potential causes:
π§ 84. Latency Failure Debugging¶
or:
The optimization target becomes obvious.
π§ 85. Cost Failure Debugging¶
Possible root cause:
π§ 86. Observability Data Model¶
A useful conceptual model:
Trace
β
βββ Request
β
βββ Query
β
βββ Retrieval
β βββ Documents
β βββ Scores
β
βββ Context
β
βββ Prompt
β
βββ LLM
β
βββ Validation
β
βββ Citation
β
βββ Metrics
β
βββ Feedback
π§ 87. Event Model¶
Example:
{
"event": "reranking_completed",
"trace_id": "abc123",
"candidate_count": 50,
"selected_count": 5,
"latency_ms": 94
}
π§ 88. Metric Types¶
Use:
Examples:
Counter¶
Gauge¶
Histogram¶
Distribution¶
π§ 89. RAG Counters¶
Useful counters:
rag_requests_total
rag_errors_total
retrieval_requests_total
retrieval_failures_total
llm_requests_total
llm_failures_total
fallbacks_total
validation_failures_total
citation_failures_total
π§ 90. RAG Histograms¶
Useful histograms:
rag_latency
retrieval_latency
reranking_latency
llm_latency
context_tokens
input_tokens
output_tokens
cost_per_request
π§ 91. Prometheus-Style Metrics¶
Example:
Latency:
Retrieval:
π§ 92. Metric Cardinality¶
Be careful with labels.
Bad:
as high-cardinality metric labels.
This can create huge metric stores.
Prefer:
and keep high-cardinality identifiers in traces/logs.
π§ 93. Logs vs Metrics vs Traces¶
| Data | Best For |
|---|---|
| Logs | Detailed events |
| Metrics | Trends and alerts |
| Traces | Request-level debugging |
| Evaluation | Quality measurement |
| Feedback | User experience |
π§ 94. Observability Architecture¶
flowchart LR
A["RAG Application"] --> B["Telemetry SDK"]
B --> C["Logs"]
B --> D["Metrics"]
B --> E["Traces"]
C --> F["Log Backend"]
D --> G["Metrics Backend"]
E --> H["Trace Backend"]
F --> I["Observability Platform"]
G --> I
H --> I
J["RAG Evaluation"] --> I
I --> K["Dashboards"]
I --> L["Alerts"]
I --> M["Root Cause Analysis"]
π§ 95. OpenTelemetry Concept¶
An enterprise RAG architecture can use an open telemetry standard for:
The application instruments:
and exports telemetry to the organization's observability platform.
π§ 96. Instrumentation Strategy¶
Instrument at these boundaries:
and RAG-specific boundaries:
π§ 97. Custom RAG Spans¶
Examples:
rag.query
rag.rewrite
rag.embedding
rag.retrieve
rag.rerank
rag.context
rag.prompt
rag.generate
rag.validate
rag.citation
These provide a consistent vocabulary.
π§ 98. Trace Naming¶
Good:
Avoid inconsistent names such as:
A consistent naming convention improves observability across teams.
π§ 99. Production RAG Trace¶
TRACE
β
βββ rag.query
β βββ query classification
β
βββ rag.rewrite
β βββ query-1
β βββ query-2
β βββ query-3
β
βββ rag.embedding
β
βββ rag.retrieve
β βββ dense
β βββ sparse
β
βββ rag.rerank
β
βββ rag.context
β
βββ rag.prompt
β
βββ rag.generate
β
βββ rag.validate
β
βββ rag.citation
π§ 100. Distributed RAG¶
In a microservice architecture:
Client
β
API Gateway
β
RAG Orchestrator
β
Retrieval Service
β
Vector Service
β
Reranker
β
LLM Gateway
β
Validation Service
Trace context should propagate across the service boundaries.
π§ 101. Service Dependency Map¶
flowchart TD
A["RAG API"] --> B["Query Service"]
A --> C["Retrieval Service"]
C --> D["Vector DB"]
C --> E["Search Engine"]
A --> F["Reranker"]
A --> G["LLM Gateway"]
A --> H["Validation Service"]
A --> I["Citation Service"]
A --> J["Telemetry"]
B --> J
C --> J
F --> J
G --> J
H --> J
I --> J
π§ 102. Dependency Observability¶
Monitor:
for:
π§ 103. External LLM Provider Monitoring¶
Track:
π§ 104. Model Routing Observability¶
For multi-model RAG:
Track:
π§ 105. Multi-Model RAG¶
Example:
Query Classifier
β
βββ Simple β Model A
β
βββ Complex β Model B
β
βββ Multimodal β Model C
Observability must explain:
π§ 106. Router Observability¶
Track:
π§ 107. Cache Observability¶
RAG systems often use:
Track:
π§ 108. Cache Hit Rate¶
Example:
π§ 109. Cache Correctness¶
A cache hit is useful only if the cached result remains valid.
Track:
π§ 110. Knowledge Base Observability¶
RAG quality depends on the knowledge base.
Monitor:
Documents
Chunks
Embeddings
Index Size
Ingestion Failures
Duplicate Documents
Stale Documents
Deleted Documents
π§ 111. Ingestion Observability¶
Track each stage.
π§ 112. Ingestion Trace¶
π§ 113. Data Freshness¶
Monitor:
Measure:
Example:
π§ 114. Stale Knowledge Detection¶
Track:
This is particularly important for:
π§ 115. Knowledge Graph Observability¶
Track:
Nodes
Edges
Entity Extraction
Relationship Extraction
Graph Updates
Graph Query Latency
Graph Traversal
π§ 116. Graph Update Monitoring¶
Failures at any stage can affect Graph RAG.
π§ 117. SQL RAG Observability¶
Monitor:
This creates a full SQL RAG trace.
π§ 118. Security Observability¶
Enterprise RAG must observe:
Authorization Decisions
Tenant Filters
Access Denials
Prompt Injection Detection
Sensitive Data Detection
Policy Violations
π§ 119. Prompt Injection Events¶
Example:
Security events should be highly visible.
π§ 120. Data Leakage Monitoring¶
Monitor whether responses expose:
π§ 121. Auditability¶
For regulated enterprise systems, maintain appropriate audit information:
Who requested
When requested
What system version
What sources were used
What policies applied
What response was produced
Do not retain more sensitive content than necessary.
π§ 122. Observability Retention¶
Not every telemetry type needs the same retention.
Example:
Retention should follow:
π§ 123. Observability Cost¶
Observability itself can become expensive.
Costs include:
Avoid logging everything blindly.
π§ 124. High-Value Telemetry¶
Prioritize:
Errors
Slow Requests
Low-Quality Requests
Security Events
Fallbacks
Cost Anomalies
Retrieval Failures
π§ 125. Low-Value Telemetry¶
Avoid excessive:
π§ 126. Observability Governance¶
Define:
What is logged?
What is traced?
What is sampled?
What is retained?
Who can access it?
How is it redacted?
π§ 127. PII Redaction¶
Before telemetry storage:
Example:
Use an appropriate enterprise redaction mechanism.
π§ 128. Secrets Redaction¶
Never expose:
in:
π§ 129. Access Control¶
Observability systems themselves contain sensitive information.
Use:
π§ 130. Enterprise Observability Architecture¶
USERS
β
βΌ
βββββββββββββββ
β RAG API β
ββββββββ¬βββββββ
β
βΌ
βββββββββββββββββββ
β RAG ORCHESTRATORβ
ββββββββββ¬βββββββββ
β
ββββββββββββββββββββΌβββββββββββββββββββ
βΌ βΌ βΌ
Retrieval Reranking LLM
β β β
ββββββββββββββββββββΌβββββββββββββββββββ
βΌ
Response Validation
β
βΌ
Citation
β
βΌ
RESPONSE
β
βΌ
βββββββββββββββββββ
β TELEMETRY LAYER β
ββββββββββ¬βββββββββ
β
βββββββββββββββββΌββββββββββββββββ
βΌ βΌ βΌ
Logs Metrics Traces
β β β
βββββββββββββββββΌββββββββββββββββ
βΌ
ββββββββββββββββββββ
β OBSERVABILITY β
β PLATFORM β
ββββββββββ¬ββββββββββ
β
ββββββββββββββββΌβββββββββββββββ
βΌ βΌ βΌ
Dashboard Alerts Analytics
β
βΌ
Root Cause
β
βΌ
System Improvement
π§ 131. RAG Observability Data Flow¶
flowchart LR
A["User Query"] --> B["RAG Pipeline"]
B --> C["Telemetry"]
C --> D["Logs"]
C --> E["Metrics"]
C --> F["Traces"]
B --> G["Evaluation"]
G --> H["Quality Signals"]
D --> I["Observability Platform"]
E --> I
F --> I
H --> I
I --> J["Dashboard"]
I --> K["Alerts"]
I --> L["Root Cause Analysis"]
π§ 132. RAG Observability Golden Signals¶
Traditional services often monitor:
RAG should extend this to:
Latency
Traffic
Errors
Saturation
+
Retrieval Quality
Context Quality
Generation Quality
Citation Quality
Token Usage
Cost
π§ 133. RAG Golden Signals¶
RAG GOLDEN SIGNALS
β
βββββββββββββββββββΌββββββββββββββββββ
βΌ βΌ βΌ
System AI Quality Economics
β β β
Latency Retrieval Tokens
Traffic Grounding Cost
Errors Citation Model Usage
Saturation Relevance
Completeness
π§ 134. RAG Health Model¶
System Health
β
βββ Availability
βββ Latency
βββ Errors
βββ Retrieval
βββ Generation
βββ Grounding
βββ Citation
βββ Security
βββ Cost
π§ 135. Alerting¶
Alerts should be actionable.
Bad:
Good:
ALERT:
RAG p95 latency exceeded SLO.
Current:
3.2 seconds
Target:
2.0 seconds
Primary contributor:
Reranker latency
Trace samples:
Available
π§ 136. Quality Alert¶
ALERT:
Faithfulness degradation detected.
Current:
88.7%
Baseline:
95.1%
Change:
-6.4 percentage points
Potential correlation:
Embedding model changed 2 hours ago.
π§ 137. Cost Alert¶
ALERT:
Average RAG cost increased by 42%.
Previous:
$0.018/request
Current:
$0.025/request
Primary signal:
Context tokens +61%
π§ 138. Retrieval Alert¶
ALERT:
Recall proxy degradation detected.
Top-1 retrieval score:
0.91 β 0.63
Affected retriever:
hybrid-v3
Affected tenant:
tenant-group-a
π§ 139. Alert Severity¶
Use severity levels:
Example:
π§ 140. Alert Fatigue¶
Too many alerts create:
Only alert when:
π§ 141. Trace-Based Debugging Workflow¶
1. Find affected request
β
2. Open trace
β
3. Check total latency
β
4. Inspect retrieval
β
5. Inspect ranking
β
6. Inspect context
β
7. Inspect prompt
β
8. Inspect LLM
β
9. Inspect validation
β
10. Inspect citations
β
11. Compare evaluation score
β
12. Identify root cause
π§ 142. Incident Example¶
User reports:
Trace:
Query
β
Retrieval
β
Old document ranked #1
β
New document ranked #8
β
Context selection selected #1
β
LLM generated answer
Root cause:
not necessarily:
π§ 143. Another Incident¶
User reports:
Trace:
Root cause:
π§ 144. Another Incident¶
User reports:
Trace:
Root cause:
π§ 145. Observability and RAG Evaluation¶
RAG REQUEST
β
βββββββββββββββ΄ββββββββββββββ
βΌ βΌ
OBSERVABILITY EVALUATION
β β
What happened? Was it good?
β β
Trace / Logs Quality Metrics
Metrics Judge
β Human Review
βββββββββββββββ¬ββββββββββββββ
βΌ
ROOT CAUSE
β
βΌ
SYSTEM IMPROVEMENT
π§ 146. Production Feedback Loop¶
flowchart TD
A["Production Request"] --> B["RAG Execution"]
B --> C["Telemetry"]
B --> D["User Feedback"]
C --> E["Observability"]
D --> F["Evaluation"]
E --> G["Failure Detection"]
F --> G
G --> H["Root Cause Analysis"]
H --> I["Engineering Change"]
I --> J["Regression Evaluation"]
J --> K{"Quality Gate"}
K -->|Pass| L["Deploy"]
K -->|Fail| I
L --> A
π§ 147. Production RAG Observability Checklist¶
β Trace every important RAG stage
β Propagate trace context across services
β Use structured logging
β Define RAG-specific metrics
β Monitor p50/p95/p99 latency
β Monitor throughput
β Monitor error rates
β Monitor retries
β Monitor fallbacks
β Monitor circuit breakers
β Monitor query rewriting
β Monitor embedding
β Monitor retrieval
β Monitor retrieval scores
β Monitor metadata filtering
β Monitor reranking
β Monitor context selection
β Monitor context size
β Monitor prompt version
β Monitor LLM calls
β Monitor token usage
β Monitor validation
β Monitor citations
β Monitor retrieval quality
β Monitor grounding
β Monitor faithfulness
β Monitor answer relevance
β Monitor citation accuracy
β Monitor citation coverage
β Monitor cost
β Monitor cost by model
β Monitor cost by tenant
β Monitor cost anomalies
β Monitor knowledge freshness
β Monitor ingestion failures
β Monitor index health
β Monitor stale documents
β Monitor prompt injection
β Monitor authorization
β Monitor tenant isolation
β Monitor sensitive data leakage
β Implement dashboards
β Implement alerts
β Implement trace sampling
β Implement quality-based sampling
β Implement PII redaction
β Implement secrets redaction
β Implement RBAC
β Implement retention policies
β Correlate traces with evaluations
β Correlate traces with user feedback
β Implement failure taxonomy
β Implement root-cause analysis
β Implement continuous improvement
π§ͺ 148. Practical Project¶
Build a Production RAG Observability Platform.
The platform should capture:
and expose:
π§ͺ 149. Suggested Project Structure¶
rag-observability/
β
βββ instrumentation/
β βββ query.py
β βββ retrieval.py
β βββ reranking.py
β βββ context.py
β βββ generation.py
β βββ validation.py
β βββ citation.py
β
βββ telemetry/
β βββ logging/
β βββ metrics/
β βββ tracing/
β
βββ evaluation/
β βββ quality/
β βββ grounding/
β βββ citation/
β
βββ dashboards/
β
βββ alerts/
β
βββ security/
β βββ redaction/
β βββ access-control/
β
βββ storage/
β
βββ configuration/
π§ͺ 150. Example Instrumentation¶
class RAGRetriever:
def retrieve(self, query):
with tracer.start_as_current_span(
"rag.retrieve"
) as span:
span.set_attribute(
"retriever.type",
"hybrid"
)
span.set_attribute(
"retriever.top_k",
10
)
results = self.search(query)
span.set_attribute(
"retriever.result_count",
len(results)
)
return results
π§ͺ 151. LLM Instrumentation¶
class LLMService:
def generate(self, prompt):
with tracer.start_as_current_span(
"rag.generate"
) as span:
response = self.llm.generate(
prompt
)
span.set_attribute(
"llm.model",
self.model_name
)
span.set_attribute(
"llm.input_tokens",
response.input_tokens
)
span.set_attribute(
"llm.output_tokens",
response.output_tokens
)
return response
π§ͺ 152. RAG Trace Record¶
{
"trace_id": "trace-001",
"query": {
"length": 42,
"language": "en"
},
"retrieval": {
"type": "hybrid",
"top_k": 10,
"latency_ms": 72
},
"reranking": {
"enabled": true,
"candidates": 50,
"selected": 5,
"latency_ms": 94
},
"context": {
"chunks": 5,
"tokens": 4200
},
"generation": {
"model": "enterprise-llm",
"input_tokens": 5100,
"output_tokens": 340,
"latency_ms": 1420
},
"citation": {
"count": 3
}
}
π§ͺ 153. Example Metrics¶
rag_requests = Counter(
"rag_requests_total",
"Total RAG requests"
)
rag_latency = Histogram(
"rag_request_duration_seconds",
"RAG request latency"
)
retrieval_latency = Histogram(
"rag_retrieval_duration_seconds",
"Retrieval latency"
)
llm_tokens = Counter(
"rag_llm_tokens_total",
"Total LLM tokens"
)
π§ͺ 154. Observability Test¶
Create a test query:
Expected trace:
rag.query
β
rag.embedding
β
rag.retrieve
β
rag.rerank
β
rag.context
β
rag.prompt
β
rag.generate
β
rag.validate
β
rag.citation
π§ͺ 155. Observability Acceptance Criteria¶
The project should be able to answer:
What happened?
How long did it take?
Which documents were retrieved?
What scores did they receive?
Which documents were selected?
How many context tokens were used?
Which model generated the answer?
How many tokens were consumed?
How much did the request cost?
Were citations generated?
Was validation successful?
Did the request use a fallback?
Did the user provide negative feedback?
π§ 156. Advanced Production Exercise¶
Extend the platform to support:
β Distributed tracing
β OpenTelemetry instrumentation
β Trace sampling
β Tail-based sampling
β Quality-based sampling
β Structured logs
β Prometheus metrics
β RAG dashboards
β Quality dashboards
β Cost dashboards
β Tenant dashboards
β Alerting
β Error budgets
β RAG SLOs
β User feedback correlation
β Evaluation correlation
β Failure taxonomy
β Root cause analysis
β Knowledge freshness
β Cache observability
β Multi-model routing
β Agentic RAG tracing
β Graph RAG tracing
β SQL RAG tracing
β Multimodal RAG tracing
β PII redaction
β Secret redaction
β RBAC
β Auditability
π§ 157. Production RAG Observability Maturity¶
Level 1 β Application Logs¶
Level 2 β Metrics¶
Level 3 β Distributed Tracing¶
Level 4 β RAG-Aware Observability¶
Level 5 β Quality Observability¶
Level 6 β Enterprise AI Observability¶
π§ 158. Observability Maturity Model¶
Enterprise AI
β²
β
Quality + Governance
β
RAG-Aware Telemetry
β
Distributed Tracing
β
Metrics
β
Logs
β
ββββββββββββββββΊ
π§ 159. Final Production Architecture¶
USER
β
βΌ
ββββββββββββββ
β RAG API β
βββββββ¬βββββββ
β
βΌ
βββββββββββββββββββ
β RAG ORCHESTRATORβ
ββββββββββ¬βββββββββ
β
βββββββββββββββββββΌββββββββββββββββββ
βΌ βΌ βΌ
Query Retrieval Model
β β β
βΌ βΌ βΌ
Rewrite Reranker LLM
β β
ββββββββββ¬βββββββββ
βΌ
Validation
β
βΌ
Citation
β
βΌ
Response
β
βΌ
ββββββββββββββββββββ
β TELEMETRY β
ββββββββββ¬ββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
βΌ βΌ βΌ
Logs Metrics Traces
β β β
ββββββββββββββββββΌβββββββββββββββββ
βΌ
Observability Platform
β
ββββββββββββββββββββββΌβββββββββββββββββββββ
βΌ βΌ βΌ
Dashboard Alerts Analysis
β β β
ββββββββββββββββββββββΌβββββββββββββββββββββ
βΌ
RAG Evaluation
β
βΌ
Root Cause Analysis
β
βΌ
System Improvement
β
βΌ
Regression Testing
β
βΌ
Deployment
π§ 160. Final Mental Model¶
RAG OBSERVABILITY
β
βββββββββββββββββββββββββΌββββββββββββββββββββββββ
βΌ βΌ βΌ
SYSTEM AI QUALITY ECONOMICS
β β β
Latency Retrieval Tokens
Traffic Grounding Cost
Errors Faithfulness Model Usage
Saturation Citation Cache
β Relevance
β Completeness
βββββββββββββββββββββββββΌββββββββββββββββββββββββ
β
βΌ
SECURITY
β
ββββββββββββΌβββββββββββ
βΌ βΌ βΌ
Access Leakage Injection
β
βΌ
USER EXPERIENCE
β
ββββββββββββΌβββββββββββ
βΌ βΌ βΌ
Feedback Citations Escalation
β
βΌ
ROOT CAUSE ANALYSIS
β
βΌ
CONTINUOUS IMPROVEMENT
The fundamental production loop is:
Observe
β
Measure
β
Evaluate
β
Correlate
β
Diagnose
β
Improve
β
Benchmark
β
Deploy
β
Observe Again
Production RAG observability is not simply monitoring infrastructure. It is the engineering discipline that connects every retrieval, context, generation, citation, quality, cost, security, and user-experience signal into one explainable system.
π 161. Key Takeaways¶
- Logs tell you what happened.
- Metrics tell you what is happening at scale.
- Traces tell you how an individual request executed.
- RAG requires AI-specific observability in addition to infrastructure telemetry.
- Every major RAG stage should have appropriate telemetry.
- Query rewriting should be observable.
- Embedding generation should be observable.
- Retrieval should expose diagnostic metadata.
- Reranking should expose candidate and ranking information.
- Context selection should expose context size and selection behavior.
- Prompt versions should be tracked.
- LLM model, token, latency, and finish information should be captured.
- Response validation should generate observable events.
- Citation generation should be traceable.
- Retrieval quality should be correlated with final response quality.
- Token usage is both a performance and cost signal.
- Context growth can cause latency and cost regressions.
- RAG observability should include quality signals such as groundedness and faithfulness.
- User feedback can be correlated with traces to identify failure patterns.
- Production RAG requires observability for agentic workflows.
- Graph RAG requires graph-specific telemetry.
- SQL RAG requires SQL generation and execution telemetry.
- Multimodal RAG requires cross-modal telemetry.
- Enterprise systems require tenant-aware observability.
- Sensitive prompts and documents should not be blindly logged.
- PII and secrets must be appropriately redacted.
- Observability platforms themselves require access control.
- Trace sampling can reduce observability costs.
- Tail-based and quality-based sampling can preserve high-value traces.
- Knowledge-base freshness should be observable.
- Ingestion pipelines should be observable.
- Cache behavior should be observable.
- Model routing should be observable.
- Quality SLOs can complement traditional infrastructure SLOs.
- RAG error budgets can help manage AI quality degradation.
- Alerts should be actionable rather than noisy.
- Trace-based debugging enables root-cause analysis.
- Evaluation tells you whether the result was good.
- Observability tells you what happened.
- Combining both enables continuous RAG improvement.
π§ 162. Chapter Navigation¶
Part V β Advanced Retrieval-Augmented Generation¶
Previous:
06. RAG Evaluation & Benchmarking
Next:
08. RAG Performance Optimization
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.