RAGEngineering Hub
Chapter 11 · concept 5 of 6 · show all
  1. 1What RAG is, and why
    1. 1.1Why models need outside knowledge, and what hallucination means
    2. 1.2What RAG is: anatomy of a request
    3. 1.3RAG vs fine tuning vs long context and prompt caching
    4. 1.4Use cases and the quality, latency and cost triangle
    5. Chapter overview
  2. 2Tokens, cost and your first RAG
    1. 2.1Tokens and context windows for RAG
    2. 2.2The RAG lifecycle and your first RAG in miniature
    3. Chapter overview
  3. 3Getting documents in
    1. 3.1Content sources and file formats
    2. 3.2Parsing, layout and OCR
    3. 3.3Tables, images and mixed content
    4. 3.4Cleaning, normalization and quality gates
    5. 3.5Metadata, document identity and versioning
    6. 3.6Updates, deletes, reindexing and ingestion pipelines
    7. Chapter overview
  4. 4Chunking
    1. 4.1Why we chunk, and the main chunking strategies
    2. 4.2Structure aware chunking and tables
    3. 4.3Chunk size, overlap and token based sizing
    4. 4.4Contextual chunking and late chunking
    5. 4.5Parent child and multi representation indexing
    6. 4.6Chunk metadata, provenance and the chunking debugging playbook
    7. Chapter overview
  5. 5Embeddings
    1. 5.1Embeddings and similarity from first principles
    2. 5.2What embeddings cannot do
    3. 5.3Choosing an embedding model: size, cost, language
    4. 5.4Embedding model migration and index rebuilds
    5. Chapter overview
  6. 6Vector stores and scores
    1. 6.1Vector databases, ANN indexes and choosing a store
    2. 6.2Score calibration and thresholds
    3. 6.3Late interaction and multivector retrieval
    4. Chapter overview
  7. 7Finding the right chunks
    1. 7.1Query understanding, rewriting and expansion
    2. 7.2Dense retrieval and keyword search with BM25
    3. 7.3Hybrid retrieval and rank fusion
    4. 7.4topK, no good match, and metadata filtering
    5. 7.5Routing, diversity, deduplication and caching
    6. 7.6Reranking: two stage, cross encoder and LLM rerankers
    7. Chapter overview
  8. 8When retrieval fails
    1. 8.1Retrieval failure analysis playbook
    2. Chapter overview
  9. 9Building the answer
    1. 9.1Context selection, packing and citations
    2. 9.2Grounding prompts and abstention
    3. 9.3Lost in the middle and context management
    4. 9.4Conflicts, staleness and freshness rules
    5. 9.5Hallucination checks and answer verification
    6. 9.6Conversational RAG, answer UX and RAG APIs
    7. Chapter overview
  10. 10Measuring
    1. 10.1Why measure, and what to measure
    2. 10.2Building a golden dataset
    3. 10.3Retrieval metrics: precision, recall, MRR, nDCG
    4. 10.4Faithfulness and answer correctness
    5. 10.5LLM as judge, and judging the judge
    6. 10.6Offline and online evals, regression tests and slices
    7. Chapter overview
  11. 11Safety and operations
    1. 11.1Prompt injection and poisoned documents
    2. 11.2Access control, privacy and governance
    3. 11.3Index lifecycle operations
    4. 11.4Observability and tracing
    5. 11.5Latency, cost, caching and model routing
    6. 11.6Reliability, degraded modes and launch readiness
    7. Chapter overview
  12. 12Scale and advanced RAG
    1. 12.1Scaling, multi tenancy and enterprise architecture
    2. 12.2Choosing an architecture: naive, advanced, agentic, graph
    3. 12.3Agentic RAG and RAG as an MCP tool
    4. 12.4GraphRAG, structured data and multimodal RAG
    5. Chapter overview

Latency, cost, caching and model routing

Measure where time and money go before tuning. In our pipeline the reranker took 1.4 s and search under a millisecond; on input cost, RAG cut a question from $0.031 to $0.0043, and a smaller model would cut it about 40 times more.

A real question

Answers take too long and cost too much. Where do you start?

With a measurement. Time every stage and count tokens per request. Then cut the biggest cost first, often the reranker or the model call, not the search people suspect.

The problem

Why this matters

The belief

Search is the slow part of RAG.

On our pipeline, embedding the question took 3.4 ms and both searches under 0.1 ms. Reranking 10 candidates took 1,406 ms. The model call, not measured here, is usually the other big one.
What really happens

On our pipeline, embedding the question took 3.4 ms and both searches under 0.1 ms. Reranking 10 candidates took 1,406 ms. The model call, not measured here, is usually the other big one.

Why not the simpler way

Cost and latency decide whether a RAG system can launch at all. A slow answer is abandoned; an expensive one cannot scale. Both are easy to guess wrong, because the slow part is not always where intuition points.

The idea

The idea in plain words

Latency budget: the total time a user will wait, split across stages. Cost per request: tokens times price, plus reranking and embedding. Caching: reuse what does not change, from the prompt prefix to whole answers (RAG-30). Model routing: pick a model per request based on how hard it is.

A restaurant times each station in the kitchen before hiring more cooks. The slow station is not always the stove.

How it works

Step by step

  1. p50 and p95 latency per stage (RAG-48), input and output tokens per request, cost per request by model.
    1

    Measure first

    p50 and p95 latency per stage (RAG-48), input and output tokens per request, cost per request by model.

  2. Fewer rerank candidates or faster hardware; small k and short contexts; prompt caching for the fixed parts; streaming so users see text sooner.
    2

    Cut the biggest cost

    Fewer rerank candidates or faster hardware; small k and short contexts; prompt caching for the fixed parts; streaming so users see text sooner.

  3. Send simple, well-grounded questions to a small model and hard ones to a large one. Measure quality per route on the golden set.
    3

    Route by difficulty

    Send simple, well-grounded questions to a small model and hard ones to a large one. Measure quality per route on the golden set.

In detail

Rerank cost. Linear in candidates: rerank 10, not 50, unless measurement shows a gain; run on a GPU or use a hosted reranker.

Tokens. Context is usually the largest input. k from a recall curve (RAG-29), dedup, short chunk headers. Output tokens cost more per token than input; ask for short answers.

Prompt caching. Put stable content (system rules, tool definitions) first so it can be cached; the vendor charges cache reads at a fraction of input price ($0.20 against $4 per million for Opus 5.5, checked 2026-11-03).

Routing. Rules (question length, presence of codes, retrieval confidence) or a small classifier. Fall back to the larger model on low verification scores (RAG-37).

Streaming. Does not lower total time, but users see the first words sooner.

Token budget of one RAG call: 39 instruction tokens, about 1,026 tokens of retrieved chunks, about 13 question tokens, and up to 1,024 tokens reserved for the answer, all inside the context window.ONE CALL · ABOUT 2,102 TOKENS OF A MUCH LARGER CONTEXT WINDOWInstruction ~393 retrieved chunks~1,026Question ~13Answer reserve~1,024
Median prompt in the Mini RAG Lab: 1,078 tokens across 47 golden questions (recursive 512 chunks, top 3). The answer reserve is the max_tokens the lab sends.

The code

Try it in Python

PRICES = {"claude-opus-5-5": (4.00, 20.00), "claude-haiku-5-5": (0.10, 0.50)}   # $ per M tokens, in/out

def cost(model: str, tokens_in: int, tokens_out: int) -> float:
    pin, pout = PRICES[model]
    return (tokens_in * pin + tokens_out * pout) / 1_000_000

def route(question: str, top_score: float, has_code: bool) -> str:
    if has_code or top_score >= 0.75:      # well grounded, look-up style
        return "claude-haiku-5-5"
    return "claude-opus-5-5"               # vague or multi-part: the larger model

print(round(cost("claude-opus-5-5", 1078, 0), 4), round(cost("claude-haiku-5-5", 1078, 0), 6))

See it

What we measured

Measured · latency per stage and input cost per question

Latency: median over 47 golden questions, laptop CPU. Cost: list prices checked 2026-11-03, input tokens only, measured token counts from RAG-04.

Embed + BM25 + vector + fuseabout 3.5 ms
Rerank 10 candidates1,406 ms
Whole corpus, Opus 5.5$0.031
RAG top 3, Opus 5.5$0.031$0.0043
RAG top 3, Haiku 5.5$0.0043about $0.0001

Latency measured 2026-11-04 with corpus/scripts/measure-part-8.mts; costs calculated from measured tokens. Model latency and output cost need model calls: not measured yet. Answer quality on Haiku was not measured.

Try it on a real example

Input cost of one question, list prices, from measured token counts

Setup

Opus 5.5, about 7,650 input tokens

Every question sends all 25 documents.

$0.031 per question (RAG-04). With caching while warm: $0.0017.

Choosing

Use it when, avoid it when

Use it when
  • Per-stage timing and per-request cost before any tuning
  • Small k, prompt caching and routing where the golden set agrees
Avoid it when
  • Optimising search when the reranker or model dominates
  • Routing to a small model without measuring quality

What it costs · Measuring is cheap. Routing adds a decision step and a second model to test.

In production

Set budgets: for example p95 under a few seconds and a cost ceiling per 1,000 questions, and alert when a release breaks them. Watch the long tail: a few questions with huge contexts or many agent steps can dominate cost. Re-check routing quality whenever models or prices change.

Watch out

Common mistakes

  • A faster vector database fixes latency. Our search was under 0.1 ms.
  • The cheapest model is false economy. It may be right for simple questions; measure.
  • Streaming makes it faster. It makes it feel faster.

Check yourself

Remember this

Remember these

  • Time every stage and count tokens before tuning.
  • Our reranker was 1.4 s; search was under a millisecond.
  • Smaller contexts and smaller models cut cost the most.
  • Route by difficulty, and check quality per route on the golden set.

Say it in an interview

  1. 01I measure per-stage latency and per-request tokens before tuning anything.
  2. 02In my pipeline reranking 10 candidates took 1.4 s; search took under a millisecond.
  3. 03RAG cut input cost per question from $0.031 to $0.0043 on Opus; Haiku would be about $0.0001.
  4. 04I cache stable prompt prefixes and keep k small.
  5. 05Routing to a smaller model is an experiment, kept only if the golden set holds.

Quick quiz

Three questions

Question 1

Q1

In our pipeline, what is the first thing to speed up?

Question 2

Q2

Same 1,078-token prompt: Opus 5.5 input costs $0.0043. What does Haiku 5.5 cost?

Question 3

Q3 · from RAG-31

What does a reranker trade?

Saved on this device. No account needed.