Forward Deployed EngineeringAI EngineeringRetrieval-Augmented Generation
Walk me through a RAG pipeline end-to-end, and tell me where it usually breaks
Question 10 of 10 · Updated
On this page
Interview-ready answer#
I would split a RAG (Retrieval-Augmented Generation) system into two pipelines: offline or asynchronous knowledge ingestion, and online retrieval and generation. In ingestion, we connect to the customer's data sources, parse documents, preserve metadata and permissions, split content into meaningful chunks, generate embeddings, and index the chunks. At query time, we authenticate the user, retrieve authorized and relevant evidence using vector search, keyword search, or both, optionally rerank the results, assemble a bounded context, and ask the LLM to answer from that evidence with citations or abstain when evidence is insufficient.
Where does it break? I first look upstream: missing or stale documents, bad parsing and chunking, poor retrieval, or relevant evidence getting dropped during reranking and context assembly. Even with the right evidence, generation can misinterpret it or hallucinate. Rather than swapping models blindly, I trace the request and test whether the correct evidence exists in the index, is retrieved, reaches the prompt, and supports the final answer. I evaluate each stage separately, then optimize end-to-end quality, latency, cost, and security against the customer's actual acceptance criteria.
End-to-end architecture#
INGESTION (initial load + incremental updates)
Customer sources -> Parse / OCR -> Clean + structure
-> Chunk + attach source/version/ACL metadata
-> Embed -> Vector / keyword indexes
-> Refresh, delete and reconcile changes
QUERY TIME
User query + authenticated identity
-> Query understanding / optional rewrite
-> Authorized candidate retrieval (dense + sparse)
-> Optional rerank -> Deduplicate + pack context
-> LLM -> Evidence/citation checks -> Answer or abstain
ACROSS BOTH PATHS
Observability | Evaluation | Access control | VersioningACL means access control list. Authorization must be enforced by trusted services and storage/search policies, not by instructions to the LLM. This is a representative architecture; not every RAG system requires a vector database, a reranker, or an LLM-based query rewrite.
Walkthrough of each stage#
- Ingestion and parsing: Connect to PDFs, wikis, databases, and enterprise applications. Extract usable text, preserve headings, tables, page numbers, document IDs, versions, and access rules. Use incremental synchronization and propagate edits, deletions, and permission changes. For tables or transactional facts, structured queries may be more appropriate than text extraction.
- Chunking: Divide content along meaningful boundaries, such as sections or paragraphs. Small chunks improve precision but may lose context; large chunks preserve more context but consume the prompt budget and introduce noise. Tune chunking and overlap on real questions rather than treating a fixed token size as universal.
- Embedding and indexing: Represent chunks with a suitable embedding model and store vectors alongside metadata and source text or pointers. Dense retrieval captures semantic similarity; sparse retrieval such as BM25 helps with exact identifiers and terminology. Keep query and document embeddings compatible and version the model, preprocessing, and index.
- Retrieval: Normalize or optionally rewrite the query without losing user intent. Retrieve a candidate set from permitted documents. Hybrid search combines sparse and dense signals, for example through reciprocal rank fusion; approximate nearest-neighbor search trades some recall for speed. Apply trusted tenant and document permission constraints so unauthorized content cannot reach the LLM.
- Reranking and context assembly: Optionally use a more expensive relevance scorer on the shortlist, remove redundant chunks, select evidence that covers the question, and pack it within a token budget. Preserve source identifiers, effective dates, and citation anchors. Include neighboring context when needed.
- Generation and response: Instruct the model to answer using the supplied evidence, cite supporting passages, express uncertainty, and abstain or escalate when evidence is insufficient or conflicting. Check citation IDs and, where appropriate, claim-level support. Retrieved text is untrusted data: do not let embedded instructions override system policy or trigger unauthorized actions.
Where it breaks and how I debug it#
| Failure stage | Typical symptom | Diagnosis and corrective action |
|---|---|---|
| Ingestion | Correct policy never appears | Check source inventory, parser output, sync lag, and deletion/version history; repair extraction or ingestion. |
| Chunking | Policy exception is missing or detached | Inspect the actual chunk and neighbors; use structure-aware or parent-child chunks. |
| Embeddings / retrieval | Irrelevant results; exact IDs missed | Inspect ranked candidates and labeled retrieval recall; add lexical search, tune filters or ANN settings, and evaluate embeddings. |
| Reranking | Relevant candidate disappears | Compare candidate recall before and after reranking; adjust shortlist size and reranker or disable it if it harms quality. |
| Context assembly | Correct evidence retrieved but not in prompt | Inspect final prompt evidence IDs, token accounting, deduplication, and truncation; adjust selection and ordering. |
| Generation | Wrong answer despite correct context | Run with manually supplied gold evidence; improve instructions, model choice, evidence checks, or abstention. |
| Security / freshness | Wrong tenant or superseded policy appears | Test access boundaries, cache isolation, revocation and version filters; block unsafe responses and reconcile indexes. |
These failures are common patterns, not a universal ranking. A single wrong answer can have multiple causes. A useful trace records document and chunk identifiers, index version, candidate scores, reranker ranks, final context IDs, model version, token counts, and latency. Restrict access to logs and redact sensitive text.
Evaluation: isolate the problem before optimizing#
Build a representative evaluation set from customer workflows with expected answers, acceptable supporting evidence, unanswerable questions, and authorization edge cases.
- Retrieval quality: Recall@k measures the fraction of labeled relevant evidence retrieved among the top k results, averaged over queries with relevant evidence. Track ranking quality with MRR or nDCG when ordering matters. If a question needs several facts, also track whether all necessary evidence is present.
- Answer quality: Evaluate factual correctness, groundedness (whether claims are supported by retrieved evidence), citation correctness and coverage, and appropriate abstention. A fluent answer can still be wrong. Calibrate automated or LLM-based judges against human-reviewed examples.
- Operational quality: Track end-to-end p50/p95 latency, stage latency, cost per successful task, ingestion freshness, error rates, and access-control violations. Define targets with the customer, not arbitrary universal thresholds.
Use an oracle-context experiment: bypass retrieval and provide the known correct evidence to the same generator. If answer quality improves substantially, retrieval or context construction is a likely bottleneck. If it remains poor, investigate generation, prompt design, evidence ambiguity, and the evaluation labels. Compare baseline and changed configurations on the same held-out dataset before rollout.
Practical FDE scenario#
Suppose an enterprise assistant answers, 'Can contractors expense international travel?' with a citation to the full-time employee handbook. Do not simply increase top-k or upgrade the LLM. Inspect whether the contractor policy was ingested, whether its exceptions remained attached to the relevant section, and whether the query retrieved it. If both policies were retrieved, inspect reranking and the final context for scope and effective dates. Add appropriate policy metadata and scope handling, clarify ambiguous user questions, and test whether the answer cites the applicable policy. If the evidence is missing or contradictory, abstain and route the user to the policy owner.
This hypothetical case illustrates the FDE's job: work with the customer's domain experts, agree on what constitutes a correct answer, fix the actual failing stage, and demonstrate improvement using evidence rather than anecdotal demos.
Engineering trade-offs#
- Hybrid retrieval versus dense alone: Better coverage for exact terms and semantic queries can justify additional index and operational complexity; verify on customer data.
- Top-k and chunk size: More evidence can improve recall but also increase noise, latency, and token cost. Optimize the candidate pool and final context separately.
- Reranking: Often improves ordering but adds compute and latency; measure the marginal gain and use a bounded shortlist.
- Freshness versus cost: Incremental updates reduce staleness, but require reliable change detection, idempotency, and deletion handling. Cache only with appropriate version and authorization scope.
- RAG versus fine-tuning: RAG is useful for grounding answers in changing external knowledge; fine-tuning is often used to change behavior, style, or task performance. They can be complementary. Neither guarantees factual accuracy.
Likely interviewer follow-ups#
- What if the correct document is never retrieved? Inspect ingestion and candidate recall before tuning generation; compare dense, lexical, and hybrid retrieval.
- What if retrieval is good but the answer is wrong? Test the final prompt and gold-evidence generation; check conflicting sources, instructions, and claim-level support.
- How do you prevent cross-tenant leakage? Enforce identity-derived access constraints at retrieval, recheck source access as needed, isolate caches, and test permission changes and adversarial requests. Never rely on the prompt as the authorization boundary.
References
- 1.
- 2.
- 3.
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models