Skip to content
Skip to lesson
Back to Topics
LearnApplied LLM Engineering & RAGProduction RAG Pipelines
MediumRAG & Retrieval12 min read

Production RAG Pipelines

Build a RAG pipeline that filters permissions before vector search, expands version-matched parent sections, abstains when evidence is missing, and attributes failures between retrieval and generation.

On this page

A developer asks an internal engineering assistant what maximum batch size the v2 inference API allows for offline embedding jobs. The assistant replies "50,000 requests per file" and cites [E1]. The endpoint returns 200 OK, and every dashboard stays green.

The answer is wrong in the quietest way possible. Under v2, the ceiling dropped to 20,000 requests per file, and only when the compressed payload stays under 100 MB. That 50,000 figure came from last year's deprecated v1 specification, which is what [E1] resolved to.

Retrieval-augmented generation () grounds a language model in an external document index so answers track live documentation without retraining weights.[1] Building a demo takes an afternoon, yet five failures break it in production: mistaking nearest neighbors for evidence, leaking restricted docs via post-filtering, letting stale revisions outrank current ones, splitting a specification across chunk edges so its 100 MB cap disappears, and tuning prompts when retrieval dropped the passage.

Four guarantees and three paths

Every grounded response needs four properties simultaneously:

PropertyTarget behaviorFailure prevented
Scope & ACLSearch only records permitted for the caller's workspace and groupsRestricted drafts leak into prompts or rerankers
FreshnessServe only active document versions and honor deletions permanentlyDeprecated v1 limits override v2 specs
CompletenessExpand matched child chunks to version-matched parent sectionsClause split drops the 100 MB payload cap
Grounding & attributionCite packed sources faithfully, abstain when unsupported, trace every stageUnverifiable claims or blind prompt tuning
Each stage narrows candidates by orders of magnitude while enforcing a distinct invariant: ACL pre-filtering protects privacy before scoring, hybrid retrieval preserves recall, cross-encoder reranking sharpens precision, and parent expansion grounds generation.

Splitting the system into three paths localizes every regression quickly:

  • Ingestion path (offline): Parses docs, builds child chunks linked to parent sections, attaches trusted tenant/group/version metadata, and publishes atomic versioned bundles.
  • Request path (online): Filters by caller identity and active version, retrieves and reranks candidates, packs source-labeled context within a token budget, and returns a cited answer or explicit abstention.
  • Evaluation path (pre-release): Replays a fixed labeled suite across any new index, retriever, prompt, or model, attributing regressions to the earliest failing stage before cutover.

Versioned evidence records and parent-child expansion

Carry source metadata from Chunking Strategies onto every indexed record: chunk_id, document_id, parent_id, version, workspace, acl_group, effective_from, and effective_to. Populate these fields strictly from trusted ingestion pipelines rather than document text, and version ACL grants separately from document content because group membership changes while text stays unchanged.

Retrieve small, expand to version-matched parents

Short chunks produce crisp retrieval vectors, while complete sections supply qualifiers and exceptions. Parent-child indexing searches compact child chunks, then resolves each hit through parent_id to its surrounding parent section after rechecking revision and ACL.[2] A lighter alternative is sentence-window retrieval, indexing single sentences and expanding to neighboring sentences on hit.[3]

A scaled 0 to 512 token document span compares four 128-token child chunks against their full 512-token parent section batch-api-sec4-v2. Query similarity matches Child 2 (tokens 128 to 256, 20,000 req/file ceiling, cos=0.89), while the dependent 100 MB payload cap sits in Child 3 (tokens 256 to 384). Following parent_id after rechecking revision and ACL expands the hit to the complete 512-token parent section packed as source E1.
Searching over tight 128-token child chunks sharpens retrieval precision; resolving `parent_id` after rechecking revision and ACL expands the match to the full 512-token parent section (`[E1]`) so the neighboring 100 MB cap is never lost.

Sliding overlap helps short phrases cross a split, yet multi-clause specifications with footnotes or exceptions still fracture unless you expand to the parent section.

A proportional 3-clause specification spans the top: Clause 1 establishes auto-rotation for stale keys, Clause 2 sets the 14-day limit, and Clause 3 states the 48-hour risk-signal condition. Below on the same horizontal scale: fixed splitting cuts between Clause 2 and Clause 3 so Chunk A misses the 48-hour condition; sliding overlap creates Chunk B-prime covering Clauses 2 and 3 while leaving Chunk A incomplete; parent-child expansion matches a small child on Clause 2 and expands via parent_id to return all three clauses intact as parent E1.
Splitting mid-specification separates linked constraints. Parent-child expansion keeps every dependent clause intact when assembling context.

Publish each index update as an atomic bundle (child index, parent store, manifest, retriever config) and pin one bundle per request so child matches and expanded parents share the exact same revision. Separate deletions from supersession: archived versions stay queryable for replay, while deleted documents carry a permanent tombstone (plus cache purge) so rolling back an index pointer never resurrects deleted text. When swapping embedding models, build the new index in parallel and validate on shadow traffic because two models with the same dimension still inhabit incompatible vector spaces.

Pre-filter ACLs inside search, never after top-k

Pre-filter ACL invariant: Run tenant, workspace, and group predicates before or inside vector and lexical search rather than post-filtering global top-kk in application code. Post-filtering breaks twice: restricted chunks enter worker memory, caches, traces, and external rerankers before removal, and when another tenant dominates top-kk, the caller gets underfilled or empty results even when permitted docs sit just below the cutoff. In engines, pgvector's hnsw.iterative_scan keeps traversing until enough eligible rows match,[4][5][6] while Weaviate and Azure AI Search build allow-lists before or during traversal (such as ACORN or flat fallback).[7][8][9] Never retry an empty authorized search by relaxing the filter.

Authorized retrieval and context packing in code

This runnable pipeline indexes a technical documentation corpus with TfidfVectorizer and cosine similarity, applies workspace, ACL, effective-date, and tombstone filters before scoring, and packs version-matched parents:

authorized-rag-retrieval.py

def is_active(record: DocChunk | ParentSection, on_date: date) -> bool:
    return record.effective_from <= on_date and (record.effective_to is None or on_date <= record.effective_to)

def prefilter_chunks(
    caller: Caller, chunks: list[DocChunk], on_date: date, deleted_docs: frozenset[str] = frozenset()
) -> list[DocChunk]:
    return [
        c for c in chunks
        if c.document_id not in deleted_docs and c.workspace == caller.workspace
        and c.acl_group in caller.groups and is_active(c, on_date)
    ]

def search_prefiltered(
    query: str, caller: Caller, chunks: list[DocChunk], on_date: date,
    top_k: int = 2, deleted_docs: frozenset[str] = frozenset(),
) -> list[tuple[DocChunk, float]]:
    eligible = prefilter_chunks(caller, chunks, on_date, deleted_docs)
    if not eligible:
        return []
    vec = TfidfVectorizer(stop_words="english")
    matrix = vec.fit_transform([c.text for c in eligible])
    sims = cosine_similarity(vec.transform([query]), matrix).ravel()
    order = np.argsort(-sims)[:top_k]
    return [(eligible[int(i)], float(sims[int(i)])) for i in order if sims[int(i)] > 0.0]

def pack_parents(
    hits: list[tuple[DocChunk, float]], caller: Caller, on_date: date,
    parents: dict[str, ParentSection], max_chars: int = 420,
    deleted_docs: frozenset[str] = frozenset(),
) -> list[dict[str, str]]:
    packed, seen, total_chars = [], set(), 0
    for chunk, _ in hits:
        parent = parents.get(chunk.parent_id)
        if parent is None or parent.parent_id in seen or parent.document_id in deleted_docs:
            continue
        if (parent.document_id != chunk.document_id or parent.version != chunk.version
                or parent.workspace != caller.workspace or parent.acl_group not in caller.groups
                or not is_active(parent, on_date)):
            continue
        entry = f"[E{len(packed) + 1}] ({parent.version}) {parent.text}"
        if total_chars + len(entry) > max_chars:
            continue
        packed.append({
            "label": f"E{len(packed) + 1}", "chunk_id": chunk.chunk_id, "parent_id": parent.parent_id,
            "version": parent.version, "locator": parent.locator, "text": parent.text,
            "sha256": sha256(parent.text.encode()).hexdigest()[:12],
        })
        seen.add(parent.parent_id)
        total_chars += len(entry)
    return packed
Output
Unfiltered top hit (leaky/stale risk): batch-api-v1-limits
Pre-filtered hits: [('batch-api-v2-limits', 0.661)]
Packed context: [('E1', 'batch-api-sec4-v2', 'a609ac25af27')]
After tombstone delete: []

Keep three operational guardrails beside context packing: avoid padding prompts with weak distractors (relevant passages buried in the middle lose accuracy[10]), delimit retrieved passages as untrusted quoted data to block indirect prompt injection (Prompt Injection Defense),[11] and key caches by workspace, ACL revision, effective date, bundle ID, and prompt/model version while rechecking live grants and answer-critical numeric thresholds (18,000 vs. 25,000 requests) before reusing any cached or buffered reply.

Evaluate retrieval and generation separately

An end-to-end score hides whether retrieval, context packing, or generation failed. Measure each layer separately (as in RAGAS and TruLens's RAG triad[12][13]):

LayerMetricFormula / DefinitionFailure caught
Stage 1 RetrievalCandidate Recall∣Ck∩R∣/∣R∣\lvert C_k \cap R \rvert / \lvert R \rvertFirst-stage search missed required passages RR (distinct from ANN recall vs. exact search)
Context PackingContext Recall[14]∣E∩R∣/∣R∣\lvert E \cap R \rvert / \lvert R \rvertReranker or token budget dropped a retrieved passage before the prompt
Context PackingContext Precision∣E∩R∣/∣E∣\lvert E \cap R \rvert / \lvert E \rvertPrompt is flooded with distractors (set precision vs. rank-weighted Ragas ContextPrecision[15])
GenerationFaithfulness[16]1m∑j=1mI(entailed(cj,E))\frac{1}{m}\sum_{j=1}^m \mathbb{I}(\text{entailed}(c_j, E))Model contradicts context or invents unsupported claims
GenerationAnswer RelevanceFraction of required query aspects addressed (or clean abstention when R⊈ER \not\subseteq E)Model cites valid text faithfully yet dodges the question

Faithfulness vs. citation syntax vs. answer relevance

Checking whether packed context EE entails atomic claim cjc_j is an NLI check (entailed, contradicted, or unsupported). Keep three distinct failures separate: a valid citation with an unfaithful claim ([E1] exists and states 20,000, yet the model claims 50,000), a faithful but off-topic answer (accurately summarizing SSE timeouts when asked about batch limits: faithfulness 1.0, answer relevance 0.0), and supported denial vs. abstention (a 25,000-request job against the v2 limit is a supported no, whereas missing documentation calls for explicit abstention).

Attribute the first failed stage

Check stages in causal pipeline order: authorization -> candidate retrieval -> context packing -> faithfulness -> citation support -> answer relevance. Stopping at the earliest failure prevents editing prompts when retrieval or reranking dropped the source.

A causal stage-attribution matrix evaluates three candidate records across four ordered checks: Allowed (ACL), Fresh, Key Topic, and Both Limits. EU Key v2 passes all four and is packed as E1; EU Session fails at Stage 3 (Key Topic); Admin Override is blocked immediately at Stage 1 (ACL). On the right, packed E1 separates supported answers (10d age and 48h signal), supported denials (15d age or 49h signal), and abstentions (missing permitted rule).
Multi-criteria evaluation checks authorization, freshness, context relevance, and compound-condition support in order, separating valid answers from denials and abstentions.
failure-attribution-and-rag-metrics.py

def compute_metrics(trace: RagTrace) -> dict[str, float]:
    cand_set, pack_set = set(trace.candidate_ids), set(trace.packed_ids)
    cand_recall = len(cand_set & REQUIRED_DOCS) / len(REQUIRED_DOCS)
    ctx_recall = len(pack_set & REQUIRED_DOCS) / len(REQUIRED_DOCS)
    ctx_prec = len(pack_set & REQUIRED_DOCS) / len(pack_set) if pack_set else 0.0
    if trace.claims:
        entailed = [ENTAILED_BY.get(c.text) in pack_set for c in trace.claims]
        cited_ok = [c.cited_label is not None and trace.source_map.get(c.cited_label) == ENTAILED_BY.get(c.text) for c in trace.claims]
        faith, cite_acc = float(np.mean(entailed)), float(np.mean(cited_ok))
    else:
        faith, cite_acc = 0.0, 0.0
    ans_rel = len(trace.answered_aspects & REQUIRED_ASPECTS) / len(REQUIRED_ASPECTS)
    return {"cand_recall": cand_recall, "ctx_recall": ctx_recall, "ctx_prec": ctx_prec,
            "faithfulness": faith, "cite_support": cite_acc, "ans_relevance": ans_rel}

def first_failed_stage(trace: RagTrace) -> str:
    if not trace.caller_authorized:
        return "1_authorization"
    m = compute_metrics(trace)
    for key, stage in (
        ("cand_recall", "2_candidate_retrieval"),
        ("ctx_recall", "3_context_packing"),
        ("faithfulness", "4_faithfulness"),
        ("cite_support", "5_citation_support"),
        ("ans_relevance", "6_answer_relevance"),
    ):
        if m[key] < 1.0:
            return stage
    return "pass"
Output
healthy                  | ctx_rec=1.0 ctx_prec=1.00 faith=1.0 rel=1.0 -> pass
noisy_context_still_pass | ctx_rec=1.0 ctx_prec=0.50 faith=1.0 rel=1.0 -> pass
retrieval_miss           | ctx_rec=0.0 ctx_prec=0.00 faith=0.0 rel=1.0 -> 2_candidate_retrieval
packer_dropped_v2        | ctx_rec=0.0 ctx_prec=0.00 faith=0.0 rel=1.0 -> 3_context_packing
hallucinated_v1_limit    | ctx_rec=1.0 ctx_prec=1.00 faith=0.0 rel=1.0 -> 4_faithfulness
faithful_but_off_topic   | ctx_rec=1.0 ctx_prec=0.50 faith=1.0 rel=0.0 -> 6_answer_relevance

Traceability and latency budgets

Log compact identifiers (request_id, user_id, workspace, acl_revision, index_bundle_id, candidate_ids, source_map with parent_id/version/sha256, cited_labels, abstained, model_version, stage timings) instead of dumping restricted corpus text into shared logs. Because greedy decoding (temperature = 0) is still best-effort across serving upgrades,[17] store full prompts only in an access-controlled archive when required.

Budget TTFT and tail latency by stage

Distinguish model (prompt arrival to first token) from end-to-end TTFT (caller arrival through authorization, retrieval, packing, and prefill to first client token). Streaming over shows tokens as they decode, whereas buffering the entire answer for post-generation verification delays first text until decode plus verification finish.

A critical-path Gantt timeline on a 0 to 800 ms scale breaks down one streaming RAG request: 2 ms caller authorization, 18 ms hybrid retrieval, and 1 ms context packing (21 ms evidence prep) followed by 320 ms model startup and prefill reach caller-visible TTFT at 341 ms. Streaming decode runs 410 ms to finish at 751 ms, while a nonblocking 3 ms trace write completes off the critical path at 754 ms.
One streaming request timeline: 2 ms auth + 18 ms retrieval + 1 ms packing + 320 ms model startup = 341 ms caller-visible TTFT. Nonblocking trace writes run off the critical path.

Propagate one end-to-end deadline across stages and measure complete-request p95 directly: if five independent stages each pass 95% of the time, all five pass together only 0.955≈77.4%0.95^5 \approx 77.4\% of the time.

latency-and-tail-budget.py

def check_latency(timings: dict[str, int]) -> list[str]:
    breaches = [s for s, lim in STAGE_BUDGET_MS.items() if timings.get(s, -1) < 0 or timings[s] > lim]
    if all(s in timings and timings[s] >= 0 for s in CRITICAL_PATH):
        if sum(timings[s] for s in CRITICAL_PATH) > DEADLINE_MS:
            breaches.append("end_to_end_deadline")
    return breaches
Output
Healthy e2e TTFT: 341 ms | breaches: []
Cumulative slow : 1050 ms | breaches: ['end_to_end_deadline']
All-5-pass empirical rate: 0.774 (analytic 0.95^5 = 0.774)

Pre-launch verification checklist

CheckRelease blockerFirst place to fix
Pre-filter ACLAny restricted chunk enters candidates, reranker, or tracesSearch-engine pre-filter and metadata schema
Version & tombstonesSuperseded or deleted revision surfaces on rollbackBundle pinning, effective-date filter, tombstone table
Context recall & precisionRequired parent dropped or drowned by distractorsStage-1 retriever, chunking, rerank cutoff, packer budget
Faithfulness & relevanceUnsupported claims, wrong citations, or off-topic repliesPrompt grounding, claim verifier, abstention threshold
Prompt injectionRetrieved text alters system behavior or invokes toolsData delimiters; keep tool authorization outside the model
Cache isolationCache key omits workspace, ACL revision, or bundle versionCache key schema and pre-return grant recheck
Tail latencyEnd-to-end p95 misses request deadlineProfile slowest stage; enforce deadline propagation

Ship RAG as an evidence pipeline rather than a prompt wrapper: enforce ACLs and versions inside search, expand to pinned parent sections, attribute failures to the first broken stage, and budget end-to-end tail latency before launch.

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 5 answered
1.A vector index ranks documents A through F in descending similarity. A, C, and E are restricted for the caller; B, D, and F are permitted. Fetching global top-3 into the app worker and post-filtering returns which documents, and what two defects occur?
2.A request pins index bundle B4 and retrieves child chunk X at revision r4. Serving flips to bundle B5 before context packing. B4 holds X's parent at r4; B5 holds the same document at r5. Both pass current ACL checks. Which parent should packing load?
3.For a query requiring document R, first-stage retrieval returns [R, D1, D2], and context packing sends [R, D1, D2] to the prompt. The model writes two claims: one supported by R (cited [E1]) and one contradicted by R (cited [E1]). What are context recall, context precision, and faithfulness?
4.In causal failure attribution, a trace shows: caller authorized (pass), candidate recall 1.0, context recall 0.0 (reranker dropped the required section), faithfulness 0.0, answer relevance 0.0. Which stage should engineers fix first?
5.A serial request spends 3 ms on auth, 27 ms on retrieval, 5 ms on packing, 260 ms on model prefill, 390 ms decoding tokens, and 15 ms on full-answer verification. Ignoring network jitter, what are caller-visible first-text latencies for immediate streaming versus buffered verification?

5 questions remaining.

References

Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks.

Lewis, P., et al. · 2020 · NeurIPS 2020

https://arxiv.org/abs/2005.11401

ParentDocumentRetriever

LangChain · 2024

https://reference.langchain.com/python/langchain-classic/retrievers/parent_document_retriever/ParentDocumentRetriever

SentenceWindowNodeParser

LlamaIndex · 2024

https://github.com/run-llama/llama_index/blob/main/llama-index-core/llama_index/core/node_parser/text/sentence_window.py

Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs

Malkov, Y. A., & Yashunin, D. A. · 2018 · IEEE Transactions on Pattern Analysis and Machine Intelligence

https://arxiv.org/abs/1603.09320

pgvector

pgvector contributors · 2026 · GitHub

https://github.com/pgvector/pgvector

pgvector 0.8.0 released

PostgreSQL Global Development Group · 2024

https://www.postgresql.org/about/news/pgvector-080-released-2952/

Filtering

Weaviate · 2026

https://docs.weaviate.io/weaviate/concepts/filtering

ACORN: Performant and Predicate-Agnostic Search Over Vector Embeddings and Structured Data

Patel, L., Kraft, P., Guestrin, C., & Zaharia, M. · 2024

https://arxiv.org/abs/2403.04871

Azure AI Search: vector query filters

Microsoft · 2026

https://learn.microsoft.com/en-us/azure/search/vector-search-filters

Lost in the Middle: How Language Models Use Long Contexts

Liu, N.F., et al. · 2024 · TACL 2024

https://aclanthology.org/2024.tacl-1.9/

Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection

Greshake, K., et al. · 2023 · AISec 2023

https://arxiv.org/abs/2302.12173

RAGAS: Automated Evaluation of Retrieval Augmented Generation.

Es, S., et al. · 2023 · arXiv preprint

https://arxiv.org/abs/2309.15217

The RAG Triad

TruLens / TruEra · 2023

https://www.trulens.org/getting_started/core_concepts/rag_triad/

Ragas: Context Recall

Ragas maintainers · 2026

https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/context_recall/

Ragas: Context Precision

Ragas maintainers · 2026

https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/context_precision/

Ragas: Faithfulness

Ragas maintainers · 2026

https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/faithfulness/

Reproducible outputs with the seed parameter

OpenAI · 2023

https://developers.openai.com/cookbook/examples/reproducible_outputs_with_the_seed_parameter

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.