RAGEngineering Hub
Chapter 1 · concept 4 of 4 · 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

Use cases and the quality, latency and cost triangle

Where RAG fits and where it does not, and how every setting trades answer quality against speed and cost, with top k as the measured example.

A real question

If more chunks give the model more to work with, why not send twenty?

Every extra chunk costs money and time on every question. Past a point it buys nothing. You want the cheapest setting that is good enough.

The problem

Why this matters

More context is always safer, so turn every setting up.
The belief

More context is always safer, so turn every setting up.

On our corpus, gains stopped after 3 to 5 chunks. Top 3 held every answer; top 5 cost 60% more and found nothing new.
What really happens

On our corpus, gains stopped after 3 to 5 chunks. Top 3 held every answer; top 5 cost 60% more and found nothing new.

Why not the simpler way

The easy approach is to turn every setting up: more chunks, a bigger model, a reranker, several search passes. Each one can help quality. Each one also adds cost and waiting time, on every question, forever. Without numbers you end up paying for improvements you cannot see.

The idea

The idea in plain words

Every RAG system sits inside a triangle of quality, latency and cost. Moving towards one corner usually moves you away from another. The job is not to maximise quality but to find the cheapest, fastest setting that is good enough for the use case.

It is like choosing a delivery option. Same day, cheap and careful packaging rarely all come together. You decide which matters most for this parcel.

How it works

Step by step

  1. For example: the answer passage found for 95% of test questions, under 2 seconds, under one cent a question.
    1

    Write a target

    For example: the answer passage found for 95% of test questions, under 2 seconds, under one cent a question.

  2. Number of chunks, chunk size, the model, reranking. Change one, measure all three corners.
    2

    Move one lever at a time

    Number of chunks, chunk size, the model, reranking. Change one, measure all three corners.

  3. Stop when the target is met. Anything more is cost without benefit.
    3

    Keep the cheapest that passes

    Stop when the target is met. Anything more is cost without benefit.

In detail

RAG fits when answers live in documents: support over manuals, policy and compliance questions, internal knowledge, contract lookups. It fits badly when the answer needs a calculation over all records (use a database query), when there are no documents (brainstorming), or when one fixed answer is enough (a FAQ page).

The levers that move the triangle are chunk size, top k, the model, reranking and extra retrieval passes. Top k is the simplest to see: each extra chunk can hold the answer, and each one is paid for in tokens and read by the model.

Hybrid retrieval: the question is searched by keyword (BM25) and by meaning (vectors); reciprocal rank fusion merges the two ranked lists by position; the top 3 chunks go into the prompt.Question“E4012?”Keyword · BM25exact words, codesVector searchsimilar meaningFuse · RRF1 / (60 + rank)Top 3into the promptranked list Aranked list B
Fusion uses only each chunk's position in the two lists, so a BM25 score of 9.7 and a cosine of 0.67 never need to be compared.

The code

Try it in Python

def sweep_top_k(golden, retrieve, count_tokens, ks=(1, 2, 3, 5, 8)):
    """Print evidence recall and median prompt tokens for each top k."""
    for k in ks:
        hits, sizes = 0, []
        for q in golden:
            chunks = retrieve(q["question"], k)
            hits += any(q["evidence"] in c for c in chunks)
            sizes.append(sum(count_tokens(c) for c in chunks))
        sizes.sort()
        print(f"k={k}  recall={hits / len(golden):.3f}  median_tokens={sizes[len(sizes) // 2]}")

See it

What we measured

Measured · answer passage in context, and prompt size

Polder corpus, 47 golden questions, recursive 512 chunks, hybrid retrieval with RRF. A hit means one of the top k fused chunks holds the whole answer passage.

Top 1: 33 of 47, median 379 tokensbaseline0.702
Top 2: 44 of 47, median 730 tokens0.7020.936
Top 3: 47 of 47, median 1,078 tokens0.9361.000
Top 5: 47 of 47, median 1,723 tokens1.0001.000

Measured 2026-11-04 with corpus/scripts/measure-parts-1-3.mts: each list's top 10 fused with RRF, first k kept, Mini RAG Lab prompt. Top 8 also reached 47 of 47 at 2,455 tokens. Going from top 1 to top 2 gave the biggest gain per token.

Try it on a real example

How many chunks should go into the prompt? (47 test questions)

Send

Answer passage found: 33 of 47 · median prompt 379 tokens

For “What does error E4012 mean?”, the first chunk is the manual's introduction. The error table is chunk number two, and it is left out.

Cheap, but 14 questions miss their answer.

Choosing

Use it when, avoid it when

Use it when
  • Questions answered by passages in documents
  • A written target for quality, latency and cost before tuning
Avoid it when
  • Counts and sums over all records: query the database
  • Turning every lever up without measuring what each one buys

What it costs · Input cost grows linearly with top k. Here, top 5 cost 55% more input than top 3 for one more answer passage out of 47.

In production

Write the target before tuning: for example "answer passage in context for 95% of golden questions, under 2 seconds, under $0.01 a question". Then change one lever at a time and keep the cheapest setting that meets all three. Re-check when traffic, corpus size or model prices change, because the best point moves.

Watch out

Common mistakes

  • More context is always safer. Past top 5 here it added tokens and no hits.
  • Quality is the only goal. A correct answer that takes 20 seconds or costs a euro may fail the use case.
  • RAG fits every question about company data. Aggregate questions need a database.

Check yourself

Remember this

Remember these

  • RAG fits answers that live in documents, not sums over a database.
  • Every setting trades quality against latency and cost.
  • Write the target before tuning, then change one lever at a time.
  • Here, top 3 found all 47 answers; top 5 and top 8 added cost and nothing else.

Say it in an interview

  1. 01RAG is a trade between quality, latency and cost; I set a target for all three first.
  2. 02It fits answers that live in documents, not counts over records.
  3. 03On my corpus top 1 found 70% of answer passages, top 3 98% and top 5 100%.
  4. 04Top 5 cost 55% more input than top 3 for one more passage; top 8 bought nothing.
  5. 05I change one lever at a time and keep the cheapest setting that meets the target.

Quick quiz

Three questions

Question 1

Q1

Going from top 3 to top 5 chunks on the Polder corpus did what?

Question 2

Q2

Which use case fits RAG least well?

Question 3

Q3 · from RAG-05

What does the golden set measure that intuition cannot?

Saved on this device. No account needed.