RAG Laboratory - Evaluation & Reliability: A Scientific Approach to Measuring RAG Systems

0
RAG Laboratory - Evaluation & Reliability: A Scientific Approach to Measuring RAG Systems

Part IV — From Architectural Evolution to Experimental Validation

Introduction: From Building RAG to Measuring RAG

Building a Retrieval-Augmented Generation (RAG) system is an important engineering achievement. Designing a modular architecture, integrating language models, implementing vector retrieval, and preparing the application for cloud deployment introduce additional layers of complexity.

However, a fundamental question remains:

How do we know whether the system actually works well?

A RAG application may retrieve relevant documents, generate convincing answers, and operate successfully under normal conditions. Yet these capabilities alone do not establish that the system is accurate, reliable, efficient, or economically sustainable.

Throughout the previous articles in this series, we explored the construction of an experimental RAG laboratory, investigated the challenges of moving RAG systems into production, and documented the architectural evolution of our application.

The laboratory evolved from a local prototype using separate persistence technologies into a more modular architecture incorporating PostgreSQL, pgvector, local and remote language models, containerization, and cloud infrastructure design.

The next stage introduces a different engineering objective.

Instead of primarily expanding the architecture, we want to systematically evaluate its behavior.

This article presents the experimental framework for RAG Laboratory — Evaluation & Reliability, organized around seven complementary engineering dimensions:

  • Retrieval Evaluation.
  • Generation Evaluation.
  • Performance Engineering.
  • LLM Benchmarking.
  • Economic Engineering.
  • Reliability Engineering.
  • End-to-End Observability.

Together, these dimensions establish a foundation for transforming a functional AI application into an evidence-driven engineering system.

1. The Experimental Baseline

Scientific evaluation begins with an established baseline.

In the first article of this series, we documented an experimental RAG application built around a corpus of technical documentation.

The initial laboratory included:

  • 11 technical guides.
  • 785 document sections.
  • 1,155 indexed chunks.
  • 30 labeled evaluation questions.
  • Local embedding generation and language-model inference.
  • Automated software testing and operational telemetry.

Selected experimental results were:

Metric Initial laboratory result
Recall@3 90.00%
Recall@5 96.67%
Recall@10 100.00%
Precision@3 38.89%
Precision@10 15.33%
MRR@3 0.7778
Passing automated tests 51
Statement coverage Approximately 95%

These measurements established that the laboratory could retrieve relevant technical information under controlled experimental conditions.

We also discovered that adding a cross-encoder reranker increased average retrieval latency from approximately 69 milliseconds to 1.39 seconds without improving the evaluated ranking metrics.

In a separate execution, language-model generation represented approximately 97.4% of total query-processing time.

These observations revealed an important principle:

Increasing architectural complexity does not necessarily improve system quality, and the most expensive component is not always the component that requires optimization.

Nevertheless, several questions remained unanswered.

Were the generated answers faithful to the retrieved documents? How would the system behave under concurrent requests? Which language model offered the best quality-to-cost relationship? What would happen if an external inference provider became unavailable?

These questions motivate the next experimental stage.

2. Retrieval Evaluation: Measuring the Quality of Evidence

Retrieval is the foundation of a RAG pipeline. Before a language model can generate a grounded answer, the system must identify and retrieve the information required to support that answer.

The new evaluation framework will expand the retrieval measurements already established in our laboratory.

2.1 Precision@K

Precision@K measures the proportion of relevant results among the first K retrieved items.

Precision@K = Relevant retrieved items within K / K

For example, if a system retrieves five document chunks and three are relevant:

Precision@5 = 3 / 5 = 0.60

This means that 60% of the retrieved context is relevant according to the evaluation labels.

Precision is particularly important in RAG because irrelevant context can consume tokens, increase inference costs, and introduce distracting information into the generation process.

2.2 Recall@K

Recall@K measures how much of the expected relevant evidence appears within the first K results.

Recall@K = Relevant items retrieved within K / Total relevant items

A high recall score indicates that the system successfully retrieves a large proportion of the evidence required by the evaluation.

However, increasing K may introduce additional irrelevant context.

The engineering challenge is therefore not simply maximizing recall. It is finding a retrieval configuration that provides sufficient evidence without unnecessarily expanding the generation context.

2.3 Mean Reciprocal Rank (MRR)

Mean Reciprocal Rank measures how early the first relevant result appears in the retrieved ranking.

If the first relevant document appears at position one, its reciprocal rank is 1.0. If it appears at position two, the value is 0.5.

MRR averages these values across the evaluation questions.

This metric helps determine whether the system consistently places useful evidence near the beginning of the retrieved context.

2.4 Normalized Discounted Cumulative Gain (nDCG)

The next laboratory stage will introduce nDCG to evaluate ranking quality more comprehensively.

Unlike binary relevance measurements, nDCG can incorporate graded relevance judgments.

Relevance grade Interpretation
0 Irrelevant
1 Marginally relevant
2 Relevant
3 Highly relevant

nDCG rewards rankings that place highly relevant evidence near the top and discounts relevant items appearing at lower positions.

The score compares the observed ranking with an ideal ranking, normally producing a value between zero and one.

To use this metric meaningfully, our evaluation dataset must include consistent relevance judgments and, where appropriate, graded labels.

2.5 The experimental objective

The retrieval experiments will compare configurations using the same corpus, questions, relevance labels, and evaluation definitions.

Potential variables include retrieval depth, similarity thresholds, embedding models, and ranking strategies.

The objective is to answer:

Which retrieval configuration provides the most useful evidence for generation without introducing unnecessary context?

3. Generation Evaluation: Measuring the Quality of Answers

A successful retrieval operation does not guarantee a successful answer.

This distinction was one of the central findings of our investigation into production RAG challenges.

A language model may receive the correct evidence and still misinterpret it, omit important details, or introduce unsupported claims.

The next laboratory stage will therefore evaluate three complementary dimensions of generated responses.

3.1 Faithfulness

Faithfulness measures whether the claims in a generated answer are supported by the retrieved context.

Consider a technical document that states that a particular service supports three authentication methods.

If the generated answer claims that the service supports five methods, the additional claims are not faithful to the supplied evidence.

Faithfulness evaluation can be performed by identifying factual claims in the response and checking whether each claim is supported by the retrieved passages.

A conceptual claim-level measurement is:

Faithfulness = Supported claims / Total evaluated claims

Importantly, faithfulness is not identical to factual correctness. An answer may faithfully reproduce information from an outdated or incorrect document.

3.2 Answer Relevance

Answer relevance measures how directly the generated response addresses the user's question.

A response may be factually supported but still fail to answer what the user actually asked.

For example, a question about configuring authentication might receive a detailed explanation of system architecture without providing the requested configuration steps.

The information may be accurate, but the answer is insufficiently relevant.

3.3 Context Relevance

Context relevance measures whether the retrieved material is useful for answering the question.

This dimension connects retrieval evaluation with generation evaluation.

A retrieval system might return documents that are semantically similar to the question but do not contain the specific evidence needed to answer it.

Context relevance helps identify this difference between semantic similarity and practical usefulness.

3.4 Beyond automated evaluation

Frameworks such as RAGAS and RAGChecker provide useful approaches for evaluating RAG responses.

However, automated evaluators also have limitations.

An LLM-based judge can exhibit inconsistency, preference bias, or sensitivity to the evaluation prompt.

Our experimental methodology should therefore combine automated scoring with human-reviewed reference answers and periodic calibration.

The evaluator model, evaluation prompt, scoring rubric, and configuration should be recorded alongside each result.

The objective is not to replace human judgment with another language model. It is to make quality assessment more systematic, transparent, and reproducible.

4. Performance Engineering: Measuring Real System Behavior

The initial laboratory provided valuable measurements of individual processing stages.

The next stage will extend this analysis to the behavior of the complete application through its HTTP interface.

4.1 End-to-end HTTP latency

Internal processing measurements explain where execution time is spent.

However, users experience the complete request-response cycle.

End-to-end HTTP latency can include:

  • Network communication.
  • Request validation and authentication.
  • Queueing.
  • Embedding generation.
  • Vector retrieval.
  • Prompt construction.
  • Language-model inference.
  • Response serialization and delivery.

Measuring only internal generation time may therefore underestimate the latency experienced by the client.

The laboratory will distinguish server-side processing time from client-observed HTTP response time.

4.2 Latency percentiles

Average latency can conceal important performance problems.

The new evaluation framework will include three percentile measurements:

Metric Interpretation
P50 Median request latency
P95 95% of measured requests complete within this time
P99 99% of measured requests complete within this time

P50 describes typical behavior, while P95 and P99 reveal slower requests that may significantly affect user experience.

Percentile measurements must be interpreted together with sample size. A small number of requests cannot provide a stable estimate of tail latency.

4.3 Throughput and concurrency

Throughput measures how many requests the system can process during a given period.

A system may answer one query in five seconds but behave very differently when ten users submit requests simultaneously.

The experimental framework will evaluate increasing concurrency levels and observe:

  • Completed requests per second.
  • Latency distribution.
  • Timeout and error rates.
  • Resource utilization.
  • Queueing behavior.

The objective is to identify sustainable operating capacity rather than simply the highest short-term request rate.

4.4 Performance as an architectural property

Different RAG configurations may exhibit different bottlenecks.

Local inference can be constrained by GPU memory and computational capacity. Remote inference can introduce network latency, provider rate limits, and variable service availability.

The experiments will help determine whether retrieval, generation, infrastructure, or external dependencies dominate the observed response time.

Performance engineering begins with identifying the bottleneck, not assuming where it exists.

5. LLM Benchmarking: Comparing Models and Providers

The architectural evolution of our laboratory introduced support for local and remote language-model providers.

This creates an opportunity to study model selection as an engineering decision rather than a simple comparison of model size or reputation.

5.1 Establishing comparable conditions

A meaningful benchmark should evaluate models using equivalent tasks.

Where possible, each model should receive:

  • The same evaluation questions.
  • The same retrieved context.
  • The same generation instructions.
  • Comparable output-token limits.
  • Documented sampling parameters.

The model identifier, provider, execution environment, and actual response status must also be recorded.

These controls help isolate differences in generation behavior from differences introduced by retrieval.

5.2 Benchmarking dimensions

The laboratory will compare models across multiple dimensions.

Dimension Evaluation objective
Faithfulness Are claims supported by the evidence?
Answer relevance Does the response address the question?
Completeness Does the answer cover the required information?
Latency How long does generation take?
Token consumption How many input and output tokens are used?
Reliability How frequently do requests succeed or fail?
Cost What is the economic cost of producing the answer?

The results should not be reduced prematurely to a single ranking.

A model that produces excellent answers may be unsuitable for a latency-sensitive application. Another model may respond quickly but omit important information.

5.3 Model quality versus provider reliability

A remote provider may reject a request because of rate limits, temporary unavailability, or service restrictions.

These events should be distinguished from the quality of the model itself.

Similarly, a local model may fail because the available hardware cannot support its memory requirements.

The benchmark should therefore separate successful-response quality from the probability of obtaining a successful response.

5.4 Preparing for intelligent model selection

The longer-term architectural opportunity is to introduce an intelligent model-selection layer capable of routing requests according to quality requirements, latency objectives, cost constraints, and provider availability.

However, implementing a model router before establishing reliable benchmarks would introduce additional complexity without sufficient evidence.

The benchmark must come before the routing policy.

6. Economic Engineering: Understanding the Cost of Intelligence

AI systems introduce a variable that traditional software engineering does not always measure at the individual request level: the economic cost of generating intelligence.

Two RAG queries may require significantly different amounts of computation, context, and output tokens.

The laboratory will therefore extend its evaluation framework to include economic observations.

6.1 Token accounting

For token-based inference providers, the system should record input and output token consumption separately.

Input tokens may include system instructions, the user's question, retrieved document passages, and additional conversational context.

Output tokens represent the generated response and, depending on the provider's accounting model, may include other billable generation tokens.

Accurate accounting requires recording provider-reported usage whenever available rather than relying exclusively on estimated token counts.

6.2 Cost per query

A simplified inference-cost calculation is:

Inference cost = Input tokens × Input token price + Output tokens × Output token price

Prices must be expressed consistently, accounting for whether the provider charges per token, per thousand tokens, or per million tokens.

The total cost of a RAG request may also include embedding generation, retrieval infrastructure, storage, network communication, and monitoring.

For local inference, the absence of an external API charge does not mean that execution is economically free. Hardware, electricity, infrastructure utilization, and maintenance remain relevant.

6.3 Quality-to-cost relationship

Consider the following hypothetical comparison:

Model Quality score Latency Cost per query
Model A 0.90 4.2 s $0.020
Model B 0.85 2.1 s $0.005
Model C 0.72 1.0 s $0.001

These values are illustrative, not measured results from our laboratory.

Model A produces the highest quality score. Model B offers a different balance between quality, latency, and cost. Model C may be appropriate for simpler tasks with lower quality requirements.

There is no universally optimal model.

The preferred configuration depends on the application, the minimum acceptable quality, and the available operational budget.

6.4 Cost per successful answer

An important extension is to evaluate the cost of obtaining an answer that satisfies predefined quality requirements.

Cost per accepted answer = Total experimental cost / Number of answers meeting the acceptance criteria

This measurement incorporates the economic impact of failed requests, retries, and answers that do not meet the required quality threshold.

It also connects directly with the broader principle of engineering productivity:

The objective is not to generate the cheapest possible response. It is to deliver useful, reliable outcomes with an economically sustainable architecture.

7. Reliability Engineering: Evaluating Failure and Recovery

Reliability cannot be established by testing only successful execution paths.

A RAG system depends on multiple components that may fail independently or interact in unexpected ways.

The next laboratory stage will investigate how the application behaves when those dependencies become unavailable or degraded.

7.1 Availability and successful execution

Availability describes whether a service is capable of providing its intended functionality when required.

For a controlled request-based experiment, a useful initial indicator is:

Request success rate = Successful requests / Total attempted requests

However, an HTTP 200 response alone does not necessarily represent a successful RAG interaction.

A response may be technically successful while containing unsupported claims or incomplete information.

The laboratory should distinguish:

  • HTTP-level success.
  • Successful retrieval.
  • Successful generation.
  • Answers meeting quality acceptance criteria.

7.2 Error classification

Different failure types require different engineering responses.

Failure category Example
Retrieval failure Vector database unavailable
Embedding failure Embedding provider timeout
Generation failure Model server unavailable
Provider limitation Rate limit or quota exceeded
Data inconsistency Missing or outdated index entries
Quality failure Unsupported or incomplete answer

Structured error classification helps identify recurring failure patterns and determine which components require additional controls.

7.3 Controlled failure experiments

The laboratory can introduce controlled failures to evaluate application behavior.

Potential experiments include temporarily disabling the vector database, introducing inference-provider timeouts, simulating rate-limit responses, and interrupting network communication.

Each experiment should examine whether the system:

  • Detects the failure.
  • Returns an appropriate response.
  • Preserves diagnostic information.
  • Avoids uncontrolled retry behavior.
  • Recovers after the dependency becomes available.

These are proposed experiments, not reliability capabilities already demonstrated by the laboratory.


Controlled failure experiments

7.4 Recovery and graceful degradation

A system may be unable to generate an answer because its language-model provider is unavailable.

Rather than returning an apparently successful but fabricated response, the application should communicate the failure clearly.

Where the architecture supports alternative providers, controlled fallback may improve availability.

However, fallback behavior must also be evaluated for quality, cost, and consistency.

Reliability is not simply the ability to keep responding. It is the ability to preserve acceptable behavior under adverse conditions.

8. Observability: Connecting Every Stage of the RAG Pipeline

Observability connects all the previous evaluation dimensions.

Without complete execution evidence, it becomes difficult to explain why a query succeeded, why an answer was incorrect, or why a particular model became expensive.

8.1 End-to-end query traceability

Each evaluated request should receive a unique trace identifier.

That identifier can connect the complete processing lifecycle:

HTTP Request → Embedding → Retrieval → Context Construction → LLM Generation → Response → Evaluation

The trace should preserve the relationship between the query, retrieved evidence, model configuration, generated answer, and evaluation result.

8.2 What should be recorded?

A proposed observation record includes:

Observation category Example fields
Request identity Trace ID, timestamp, evaluation run ID
Retrieval Embedding model, top-K, chunk identifiers, similarity scores
Generation Provider, model identifier, prompt version, response status
Performance Stage durations, HTTP latency, queueing time where measurable
Economics Input tokens, output tokens, estimated or reported cost
Reliability Error category, retries, timeout, recovery status
Quality Precision, recall, faithfulness, answer relevance
Reproducibility Corpus version, configuration version, application release

This structure would allow engineers to investigate relationships that isolated metrics cannot reveal.

For example, an answer-quality regression might be associated with a particular model change, an increase in retrieved context, or an outdated document index.

8.3 Observability is not unrestricted logging

Complete traceability does not mean storing every piece of information indefinitely.

Queries, prompts, documents, and generated answers may contain sensitive data.

An observability architecture should therefore incorporate appropriate access controls, retention policies, redaction, and data minimization.

The goal is to preserve sufficient diagnostic evidence without creating unnecessary information-exposure risks.

9. Designing a Scientific Experimental Methodology

The seven evaluation dimensions become more valuable when they are organized into a repeatable experimental process.

The proposed laboratory methodology will follow a structured sequence.

Step 1: Establish a versioned baseline

Record the application release, corpus, evaluation questions, embedding model, generation model, retrieval configuration, and execution environment.

Step 2: Define a research question

Each experiment should investigate a specific engineering question.

For example:

Does increasing retrieval depth improve answer faithfulness enough to justify the additional latency and token consumption?

Step 3: Control experimental variables

Where possible, change one architectural variable at a time while keeping the remaining configuration constant.

When multiple variables must change together, document the resulting limitations on causal interpretation.

Step 4: Execute repeatable trials

Repeat experiments to account for model variability, infrastructure conditions, and provider behavior.

Separate warm-up requests from measured requests and document the number of observations.

Step 5: Collect multidimensional evidence

Record retrieval quality, generation quality, latency, throughput, token consumption, cost, errors, and relevant telemetry.

Step 6: Analyze trade-offs

Determine whether the observed improvement introduces disadvantages in other dimensions.

An improvement in faithfulness may be accompanied by higher cost. A faster model may produce less complete answers.

Step 7: Document conclusions and limitations

Record what the experiment demonstrated, what it did not demonstrate, and which questions require further investigation.

This final step is particularly important.

A scientifically useful experiment does not need to produce a positive result. It needs to produce interpretable evidence.

10. The RAG Evaluation & Reliability Scorecard

The following scorecard summarizes the proposed experimental framework for the next laboratory stage.

Engineering dimension Primary measurements Experimental objective
Retrieval Precision@K, Recall@K, MRR, nDCG Retrieve and rank useful evidence
Generation Faithfulness, answer relevance, context relevance Produce grounded and useful answers
Performance HTTP latency, throughput, P50/P95/P99 Characterize realistic system capacity
LLM benchmarking Quality, completeness, latency, success rate Compare models and providers
Economic engineering Tokens, cost per query, cost per accepted answer Evaluate economic sustainability
Reliability Availability indicators, errors, timeouts, recovery Understand behavior during failures
Observability Traces, events, configuration and evidence linkage Explain and reproduce results

The scorecard is not intended to produce an arbitrary universal quality score.

Instead, it provides a structured view of the system's engineering characteristics.

Different applications may prioritize different dimensions.

A safety-critical knowledge assistant may require extremely strong evidence of answer faithfulness. A high-volume support application may emphasize latency and cost while maintaining defined quality thresholds.

The engineering responsibility is to establish those requirements explicitly and evaluate the system against them.

Frequently Asked Questions

What is the difference between retrieval evaluation and generation evaluation?

Retrieval evaluation measures whether the system finds and ranks relevant evidence. Generation evaluation measures whether the language model uses that evidence to produce a faithful, relevant, and sufficiently complete answer.

Why should a RAG system measure nDCG in addition to precision and recall?

nDCG provides additional insight into ranking quality, particularly when retrieved documents have different relevance levels. It rewards placing highly relevant evidence near the top of the ranking.

Does high faithfulness guarantee that an answer is correct?

No. Faithfulness measures whether an answer is supported by the supplied context. If the source documents contain incorrect or outdated information, a faithful answer may still be factually incorrect.

Why is P99 latency important?

P99 reveals slow requests that may be hidden by average or median latency measurements. These requests can significantly affect user experience and operational reliability.

Can local language models be more economical than cloud models?

They can be under certain workloads and infrastructure conditions. However, local execution still involves hardware, energy, maintenance, and capacity costs. The comparison must account for the complete operating environment.

Should RAG benchmarks compare only successful responses?

No. Successful-response quality should be evaluated alongside request failures, timeouts, and provider limitations. A model that produces excellent answers but is frequently unavailable may be unsuitable for a particular application.

Is observability the same as evaluation?

No. Observability provides evidence about system execution and behavior. Evaluation determines whether that behavior satisfies defined quality and operational requirements. Both are necessary for evidence-driven engineering.

Does this framework establish that the laboratory is production-ready?

Not by itself. The framework defines how selected production-oriented properties can be evaluated. Production readiness requires actual experimental evidence, security validation, operational controls, and requirements appropriate to the intended deployment.

Conclusion: Engineering Intelligence Requires Measuring Intelligence

The evolution of our RAG Laboratory has demonstrated that building an AI application involves much more than connecting a language model to a vector database.

Architecture, persistence, provider integration, automated testing, and infrastructure design are essential engineering foundations.

However, they represent only part of the journey.

The next stage requires a deeper understanding of how the system behaves, how well it answers questions, how much it costs, and how reliably it operates when conditions change.

By introducing retrieval evaluation, generation evaluation, performance engineering, LLM benchmarking, economic engineering, reliability testing, and end-to-end observability, we can investigate these questions systematically.

The objective of RAG Laboratory — Evaluation & Reliability is not simply to accumulate more metrics.

It is to establish an experimental environment where architectural decisions can be evaluated through reproducible evidence.

A faster model is not necessarily a better model.

A more sophisticated retrieval pipeline is not necessarily a more accurate pipeline.

A lower-cost response is not necessarily a more economical outcome.

And a successful deployment is not necessarily a reliable system.

The real engineering challenge is understanding the relationships between quality, performance, cost, and reliability—and making architectural decisions based on those relationships.

That is the direction of our next experimental journey.

Because in the era of artificial intelligence, building intelligent systems is only the beginning.

Engineering them requires proving what they can do, understanding where they fail, and continuously measuring whether they are improving.

You may like these posts