RAG in Production: Evals, Observability, Cost, Freshness

RAG in Production: Evals, Observability, Cost, Freshness

Your runbook bot passed the demo. RAG in production fails more quietly: prompt edits lower quality, latency hides in retrieval, token bills creep up and deleted runbooks still get cited. Here you will gate changes on evals, trace requests with OpenTelemetry, alert on latency and groundedness SLOs, and keep the index cheap, fresh and access-controlled.

How RAG in production fits together

This builds on RAG 101 and reuses retrieve() from the hybrid search post. I have built RAG pipelines that automate documentation search; these are the layers they needed after the demo.

Architecture in three lanes: docs in Git flow through an incremental indexer into a vector and BM25 index; an on-call SRE asks the RAG API, which retrieves ACL-filtered chunks and calls Claude for a cited answer; the API sends spans through the OpenTelemetry Collector to Tempo and latency metrics to Prometheus, and an LLM judge scores a 5% sample of answers into Prometheus
Index on merge, answer per question, observe everything.

The index lane runs on every docs merge. The query lane is the only place a model sees document text. The observe lane sends spans through the OpenTelemetry Collector to Tempo, while Prometheus scrapes latency and groundedness counters. You need Python 3.10+ and an ANTHROPIC_API_KEY.

Evals: golden questions, recall@k and faithfulness

An eval turns "the answers feel worse" into a number. Build a golden set of 40 to 60 real questions from incident channels and post-mortems: one JSON object per line in golden.jsonl, with q, service, env and the expected runbook.

Recall@k is the share of questions whose expected runbook is among the top k retrieved chunks, so it tests the retriever alone. Faithfulness is the share of answer claims that the retrieved text supports, so it catches a model that improvises. Save this as evals.py:

import json, anthropic
from app import answer

JUDGE = "claude-opus-5-5"
ASK = 'Count claims in ANSWER and those CONTEXT supports. Reply JSON: {"claims": 5, "supported": 4}'

def judge(text, chunks):
    context = "\n".join(c["text"] for c, _ in chunks)
    msg = anthropic.Anthropic().messages.create(model=JUDGE, max_tokens=100, messages=[
        {"role": "user", "content": f"{ASK}\nCONTEXT: {context}\nANSWER: {text}"}])
    v = json.loads(msg.content[0].text)
    return v["supported"] / max(v["claims"], 1)

if __name__ == "__main__":
    golden = [json.loads(line) for line in open("golden.jsonl")]
    hits = faith = 0
    for g in golden:
        text, chunks = answer(g["q"], g["service"], g["env"])
        hits += g["expected"] in [c["source"] for c, _ in chunks]   # recall@4
        faith += judge(text, chunks) if chunks else 1                # refusals claim nothing
    print(f"recall@4={hits / len(golden):.2f} faithfulness={faith / len(golden):.2f}")

answer() is the traced function from the next section; it returns the text plus the chunks it used. If json.loads fails, the judge answered in prose: tighten the rubric rather than skipping the case. Expect a line like recall@4=0.88 faithfulness=0.94 (illustrative). Low recall means fixing chunking, filters or the index, not the prompt; for multi-hop failures, see advanced RAG.

LLM-as-judge and its limits

A model grading a model is cheap, but it is not ground truth. Zheng et al. (2023) found position, verbosity and self-preference biases in LLM judges, and no judge can tell that a supported claim came from an outdated runbook. Use a stronger judge than the generator, pin its model and prompt, and hand-check verdicts every release. The flowchart shows the gate.

Flowchart: an engineer changes the prompt, model or chunker; CI runs the golden set; if recall@4 is below baseline, fix retrieval first; if faithfulness is below 0.9, block the merge; otherwise the engineer spot-checks 10 judge verdicts; if the judge disagrees, fix the judge prompt; if it agrees, ship to a canary and watch the SLOs; every fix loops back to a re-run
Cyan runs in CI; green is the engineer.

Retrieval is checked first because no model can be faithful to the wrong runbook, and the human check comes before release, not after an incident.

Tracing retrieval and generation with OpenTelemetry

When an answer takes nine seconds, you need to know whether retrieval or the model was slow, and how many tokens it burned. The OpenTelemetry GenAI semantic conventions standardise those names. Save this as app.py:

import anthropic
from opentelemetry import trace
from search import retrieve

MODEL = "claude-sonnet-5-5"
tracer = trace.get_tracer("runbook-rag")

def answer(question, service, env):
    with tracer.start_as_current_span("rag.answer"):
        with tracer.start_as_current_span("retrieve") as span:
            chunks = retrieve(question, service, env, top_k=4)
            span.set_attribute("rag.sources", [c["source"] for c, _ in chunks])
        if not chunks:
            return "No runbook covers this.", []
        excerpts = "\n\n".join(c["text"] for c, _ in chunks)
        with tracer.start_as_current_span(f"chat {MODEL}", kind=trace.SpanKind.CLIENT) as span:
            resp = anthropic.Anthropic().messages.create(model=MODEL, max_tokens=500,
                system="Answer only from the excerpts and cite them.",
                messages=[{"role": "user", "content": f"{excerpts}\n\n{question}"}])
            span.set_attributes({"gen_ai.operation.name": "chat",
                                 "gen_ai.provider.name": "anthropic",
                                 "gen_ai.request.model": MODEL,
                                 "gen_ai.usage.input_tokens": resp.usage.input_tokens,
                                 "gen_ai.usage.output_tokens": resp.usage.output_tokens})
        return resp.content[0].text, chunks

The chat span is named after the operation and model, and its gen_ai.* attributes record the model and token usage. rag.sources is our own attribute: when an answer is wrong, the trace shows which runbooks the model saw. The conventions are still marked Development, so expect renames. Now run the eval set with tracing on:

pip install opentelemetry-distro opentelemetry-exporter-otlp
export OTEL_SERVICE_NAME=runbook-rag OTEL_TRACES_EXPORTER=console OTEL_METRICS_EXPORTER=none
opentelemetry-instrument python evals.py

opentelemetry-instrument configures the SDK from environment variables; without it the API is a silent no-op, the usual reason for "no spans". Each answered question prints three JSON spans. In production, set OTEL_TRACES_EXPORTER=otlp and point OTEL_EXPORTER_OTLP_ENDPOINT at your Collector.

On a 30M+ active-series stack I ran, Grafana Tempo tracing helped cut MTTR by up to 80%. The waterfall shows one answer:

Trace waterfall for one question: rag.answer takes 2.45 seconds, its retrieve child 0.18 seconds with rag.sources listing four runbooks, and the chat claude-sonnet-5-5 client span 2.2 seconds with 1912 input tokens and 214 output tokens
Where the time and tokens went (illustrative).

The model call dominates and input tokens drive the cost, so lowering top_k or chunk size is the first lever. Re-run the evals to confirm recall survives the cut.

SLOs for an AI service: latency and groundedness

A RAG service fails slowly or confidently wrong. An SLO (service level objective) is a target share of good events over a window; the gap to 100% is the error budget. These targets are starting points:

SLIGood eventTargetWindow
LatencyAnswer in under 4 s95%28 days
GroundednessJudge finds every claim supported95%28 days
FreshnessDoc change searchable within 1 h99%28 days
Cost (budget)Under 6,000 tokens per answer99%7 days

Wrap answer() in a prometheus_client histogram named rag_request_duration_seconds, with a bucket exactly at 4 seconds. A background worker judges a 5% sample of answers and increments two counters, rag_judged_total and rag_grounded_total. Then in PromQL:

# Groundedness SLI over 28 days (target 95%)
sum(increase(rag_grounded_total[28d])) / sum(increase(rag_judged_total[28d]))

# Page: latency SLO (95% under 4 s) burning its budget 14.4x too fast
1 - sum(rate(rag_request_duration_seconds_bucket{le="4.0"}[1h]))
      / sum(rate(rag_request_duration_seconds_count[1h])) > 14.4 * 0.05

Swap [1h] for [28d] to get the latency SLI itself. The 14.4× multiplier comes from the Google SRE workbook: at that rate a 28-day budget is gone in under two days, so pair it with a 5-minute window. If the query returns nothing, the 4-second bucket is missing. Groundedness gets a ticket, not a page: a 5% sample is small and the judge is noisy.

Caching, incremental re-indexing and access control

Caching saves tokens but can serve stale or forbidden answers. The diagram shows the re-index diff on top and the per-query checks below.

Two lanes. Re-index: an edited, an unchanged and a deleted runbook are diffed by hash, so only new chunks are embedded, unchanged ones are kept and removed ones are deleted from the index. Query: a payments SRE hits the answer cache, whose key includes their groups; on a miss the ACL filter drops HR chunks before ranking and Claude sees only allowed text
Re-embed the diff; filter by group first.

During an incident, twenty people ask the same question within minutes. An exact-match cache serves them for free if its key holds the normalised question, service, env, caller's groups, index version and prompt version. Anthropic prompt caching bills a repeated system-prompt prefix, marked with cache_control, at a reduced rate. Avoid semantic caches: "restart checkout" and "restart checkout in staging" embed almost identically.

Full rebuilds are slow, and append-only indexes keep retired runbooks searchable. Instead, make each chunk's ID the SHA-256 of its source and text. On every merge, diff wanted IDs against stored ones: add the new, delete the missing. Diff against every runbook, never just the changed files, or everything else gets deleted. Name the collection after the embedding model, so upgrades become blue/green swaps.

Access control belongs in the query, not the prompt. Store each runbook's owning group as chunk metadata and filter on the caller's groups, for example where={"acl": {"$in": groups}} in Chroma, so restricted chunks never reach ranking. Add golden questions that a group must see refused. "Never reveal HR pages" in a system prompt is not access control.

Common pitfalls

  • Tuning prompts for retrieval bugs. Check recall@k first.
  • Unbounded context. A large top_k inflates tokens and latency.
  • High-cardinality labels. Keep sources on spans, not metric labels. Trimming labels with the Collector and vector.dev is how I cut one metrics bill by up to 50%.
  • Cache keys without groups. One cached answer leaks restricted runbooks to everyone.

Key takeaways

  • Gate prompt, model and index changes on recall@k and faithfulness.
  • Trace retrieval and generation with GenAI attributes.
  • Page on latency burn; ticket on groundedness.
  • Re-embed only the diff, and filter by ACL before the model sees text.

Related articles