Q19Retrieval strategies
What is hypothetical document embedding (HyDE)?
Explain using a generated hypothetical answer-like document to support retrieval.
Answer
HyDE generates a hypothetical document or passage related to the question and embeds that text to search for real documents with similar representations.
The hypothetical passage is a retrieval aid, not a source of truth. It can contain invented details, so final answers should be grounded in actual retrieved documents.
HyDE may help when query wording differs greatly from corpus wording. Test it against direct query embeddings and other query-rewriting approaches.
Key Points
- HyDE generates text to aid retrieval.
- The generated text is not evidence.
- Final answers should use real sources.
- Evaluate against simpler retrieval methods.
Q20Retrieval strategies
What is parent-child retrieval?
Retrieve small passages but supply a larger contextual parent section.
Answer
Parent-child retrieval indexes smaller child chunks for precise matching and associates them with larger parent sections or documents.
When a child matches, the system can return the parent or a bounded surrounding section to preserve context. This can balance precise retrieval with complete explanations.
The approach needs stable parent-child identifiers, deduplication, and context-budget controls so a few matches do not expand into excessive content.
Key Points
- Child chunks improve retrieval granularity.
- Parent content adds context.
- Use stable relationships and deduplication.
- Limit expanded context.
Q24Vector search
What are HNSW and IVF indexes?
Compare graph-based and cluster-based approximate vector indexes.
Answer
HNSW is a graph-based approximate nearest-neighbor method that navigates a hierarchy of links to find nearby vectors. It often offers strong query performance at the cost of memory and index-building resources.
IVF-style indexes partition vectors into clusters and search selected clusters. Their performance depends on clustering, how many clusters are probed, and any quantization used.
The better option depends on data size, memory limits, update patterns, latency targets, and recall requirements. Benchmark the actual engine implementation.
Key Points
- HNSW uses a navigable graph.
- IVF partitions vectors into clusters.
- Memory and recall trade-offs differ.
- Tune using representative workloads.
Q28Embeddings
How do you migrate to a new embedding model?
Plan a compatible index migration and compare retrieval quality.
Answer
Do not assume vectors from two embedding models can be mixed. Even if dimensions match, the models may produce different vector spaces.
A safer migration is to version the embedding configuration, create a new index or namespace, re-embed documents, evaluate it, and switch traffic after validation. A dual-read or shadow-testing period can reduce risk.
Track rollback criteria, ingestion progress, index cost, and query latency. Keep source documents available so vectors can be regenerated.
Key Points
- Do not mix incompatible vector spaces.
- Version model and preprocessing settings.
- Re-embed and evaluate before cutover.
- Keep rollback and reindexing plans.
Q30Evaluation
What are MRR and NDCG?
Explain ranking metrics for search results.
Answer
Mean Reciprocal Rank measures how highly the first relevant result appears across queries. A first relevant result at rank one contributes more than one at a lower rank.
Normalized Discounted Cumulative Gain evaluates the graded relevance of ranked results, discounting lower positions and normalizing against an ideal ranking.
Use these metrics when result order matters, and ensure relevance judgments are consistent. Pair them with recall and task-level answer metrics.
Key Points
- MRR focuses on the first relevant result.
- NDCG supports graded relevance.
- Ranking order affects both metrics.
- Use consistent relevance labels.
Q31Evaluation
How do you evaluate a RAG system end to end?
Evaluate retrieval, groundedness, answer quality, safety, latency, and cost.
Answer
Create representative questions with relevant source passages and expected answer facts. Include answerable, ambiguous, and unanswerable questions.
Measure retrieval recall and ranking quality separately from answer correctness, evidence faithfulness, citation accuracy, and appropriate abstention. Review failures to identify whether ingestion, retrieval, prompt construction, or generation caused them.
Also measure latency, cost, access-control behavior, and robustness to malicious documents. Re-run the suite after changes to data, embeddings, retrievers, prompts, or models.
Key Points
- Evaluate each pipeline stage.
- Include unanswerable and adversarial cases.
- Measure groundedness and citations.
- Track operational and security metrics.
Q33Evaluation
How do you measure hallucinations in RAG?
Identify unsupported claims, invalid citations, and failure to abstain.
Answer
Define hallucination for the use case, such as a factual claim not supported by the retrieved evidence. Create tests with trusted source documents and questions whose answers are known or intentionally absent.
Measure unsupported claims, citation correctness, answer accuracy, and abstention behavior separately when possible. Human review is valuable for ambiguous or high-impact cases.
No single score captures every failure. Test retrieval misses, conflicting sources, stale documents, and adversarial content.
Key Points
- Define the failure precisely.
- Check claims against trusted sources.
- Evaluate citation and abstention behavior.
- Use a mix of automated and human review.
Q35Evaluation
Can an LLM judge evaluate RAG answers?
Use model-based scoring carefully and validate against human judgments.
Answer
An LLM judge can score answers against a rubric for correctness, relevance, faithfulness, or citation use. It can scale review when exact-match metrics are insufficient.
Judge models may be biased by answer length, wording, position, or their own blind spots. A confident score is not proof of quality.
Calibrate the judge against human-reviewed examples, define explicit rubrics, sample outputs for audit, and use independent checks for factual or security-critical claims.
Key Points
- Use explicit rubrics.
- Judge scores can be biased.
- Calibrate against human review.
- Audit high-impact or uncertain cases.
Q36Security
What is indirect prompt injection in RAG?
Explain malicious instructions embedded in retrieved documents.
Answer
Indirect prompt injection occurs when retrieved content contains instructions intended to manipulate the model, such as telling it to ignore prior directions or reveal sensitive data.
Retrieved documents must be treated as untrusted data. Restrict tools and permissions, separate instructions from source content, validate outputs, and enforce authorization in application code.
Prompt wording alone is not a security boundary. Test with malicious documents and ensure the model cannot use retrieved instructions to grant itself new capabilities.
Key Points
- Retrieved text can contain malicious instructions.
- Treat external content as untrusted data.
- Enforce permissions outside the model.
- Test adversarial documents and tool use.
Q37Security
How do you prevent data leakage in RAG?
Enforce document permissions, tenant isolation, and safe caching.
Answer
Authenticate the user and apply document-level or tenant-level authorization before retrieved content is added to the model context. Metadata filters can help but should be backed by trusted application checks.
Partition caches by authorization scope, protect logs and traces, and ensure citations only point to documents the user is allowed to access.
Test cross-tenant and cross-role access scenarios. Hiding a citation or telling the model not to reveal content is not sufficient once unauthorized content has entered the context.
Key Points
- Authorize before building context.
- Enforce tenant boundaries in trusted code.
- Partition caches and protect logs.
- Test cross-user leakage explicitly.
Q39Security
How should personally identifiable information be handled in RAG?
Apply minimization, access controls, retention, and privacy-aware observability.
Answer
Determine what personal data is necessary for the use case and avoid indexing or sending fields that are not needed. Apply redaction or tokenization where appropriate.
Enforce access permissions at ingestion and retrieval, define retention and deletion processes, and check the policies and contractual terms of model and storage providers.
Logs, traces, embeddings, and caches may also contain sensitive information. Protect them with appropriate access controls, retention limits, and incident procedures.
Key Points
- Minimize collected and processed personal data.
- Enforce permissions throughout the pipeline.
- Include logs, embeddings, and caches in privacy reviews.
- Define retention and deletion procedures.
Q40Reliability
How should RAG handle conflicting sources?
Use source authority, freshness, provenance, and explicit uncertainty.
Answer
Conflicting documents can result from outdated policies, duplicate versions, or inconsistent sources. Store provenance and timestamps, and define which sources are authoritative for each content type.
Retrieval can prioritize approved and current sources, but the answer generator should not silently combine incompatible claims. It may need to explain the conflict or abstain.
Create test cases with conflicting passages and verify that source selection and final explanations follow the defined policy.
Key Points
- Track source provenance and freshness.
- Define authoritative source rules.
- Do not silently merge conflicting facts.
- Test conflict scenarios.
Q42Production
How do you reduce RAG latency?
Measure each stage and optimize retrieval, reranking, model calls, and context.
Answer
Measure latency separately for query embedding, vector or keyword search, filtering, reranking, prompt assembly, model time-to-first-token, generation, and network overhead.
Possible optimizations include efficient indexes, fewer unnecessary query rewrites, parallel independent searches, caching safe repeatable work, limiting irrelevant context, and selecting an appropriate model.
Evaluate tail latency and answer quality under realistic load. An optimization that reduces average latency but causes retrieval misses may not be acceptable.
Key Points
- Measure the pipeline stage by stage.
- Optimize the actual bottleneck.
- Consider tail latency and concurrency.
- Protect retrieval and answer quality.
Q45Production
How should a production RAG system handle failures?
Plan for embedding, index, provider, timeout, and malformed-output failures.
Answer
Classify failures such as ingestion errors, index unavailability, embedding-provider timeouts, model rate limits, invalid responses, and insufficient evidence.
Use bounded retries with backoff for transient errors, timeouts, circuit breakers where appropriate, and clear fallback behavior. Do not silently generate unsupported answers when retrieval fails.
Log diagnostic metadata without unnecessarily recording sensitive content, and monitor failure rate, latency, fallback use, and answer quality.
Key Points
- Classify failures by pipeline stage.
- Use bounded retries and timeouts.
- Distinguish retrieval failure from no evidence.
- Monitor reliability and safe fallback behavior.
Q46Production
What should you monitor in a production RAG system?
Track retrieval quality, freshness, latency, cost, security, and user outcomes.
Answer
Monitor query volume, retrieval latency, result counts, similarity-score distributions, reranker latency, model token usage, provider errors, and end-to-end response time.
Quality signals include sampled relevance reviews, groundedness, citation validity, unanswered rates, user feedback, and regression tests. Also monitor indexing lag, deletion propagation, and permission failures.
Use alerts tied to service objectives and segment metrics by model version, index version, tenant, or workflow where safe and useful.
Key Points
- Track performance and reliability.
- Monitor quality and freshness.
- Watch authorization and deletion behavior.
- Use actionable alerts and versioned telemetry.
Q47Architecture
When should you use RAG versus a long context window?
Choose between selective retrieval and providing a larger body of context.
Answer
A long context can be useful when the model needs to reason over a bounded set of documents that fits within the context budget. RAG is useful when the corpus is large, changes frequently, or needs selective retrieval and permission filtering.
Long context can increase token cost and does not guarantee that every detail will be used. RAG introduces retrieval misses, indexing work, and additional pipeline complexity.
Some systems combine both: retrieve relevant documents and then provide a sufficient surrounding context. Evaluate quality, latency, cost, and governance using realistic tasks.
Key Points
- Long context is useful for bounded document sets.
- RAG supports selective retrieval from larger corpora.
- Both approaches have cost and quality trade-offs.
- Hybrid designs may be appropriate.
Q48Architecture
How would you design a company knowledge assistant using RAG?
Design ingestion, retrieval, authorization, grounded answers, and operational monitoring.
Answer
Ingest approved sources through format-aware parsers, preserve metadata and permissions, chunk content, generate embeddings, and index it. Make ingestion idempotent and support updates and deletions.
At query time, authenticate the user, retrieve only authorized content using hybrid search if useful, rerank candidates, and supply a bounded evidence set to the model. Return citations and abstain when evidence is insufficient.
Add evaluation datasets, access-control tests, prompt-injection tests, monitoring, feedback collection, and index freshness alerts. Version the models, prompts, and ingestion pipeline so regressions can be diagnosed.
Key Points
- Build an updateable ingestion pipeline.
- Enforce access control before generation.
- Ground answers in cited evidence.
- Evaluate, monitor, and version every stage.
Q49Troubleshooting
RAG retrieves the wrong documents. How would you debug it?
Trace extraction, chunking, embeddings, filters, ranking, and query construction.
Answer
First inspect the exact query and the top retrieved chunks, including scores, metadata, and source text. Verify that the expected document was ingested and that its extracted text is correct.
Check chunk boundaries, embedding model compatibility, filters, index configuration, query rewriting, and top-k. Compare keyword search, vector search, and hybrid search to isolate the source of the miss.
Reproduce the issue in a small evaluation case and change one variable at a time. Track whether the fix improves a broader test set instead of overfitting to one query.
Key Points
- Inspect actual retrieved passages and scores.
- Verify ingestion and chunk quality.
- Check filters and model compatibility.
- Use repeatable tests and change one variable at a time.
Q50Troubleshooting
RAG retrieves the right documents but still answers incorrectly. What do you check?
Debug context construction, evidence conflicts, prompting, generation, and output validation.
Answer
If retrieval is correct, inspect the final context sent to the model. Check whether relevant passages were truncated, duplicated, ordered poorly, or separated from their source metadata.
Review the prompt, conflicting evidence, output limits, model choice, and whether the model was asked to distinguish facts from assumptions. Verify that citations map to the passages actually supplied.
Add a regression test for the failure, improve context selection or prompt instructions, and evaluate the change across similar questions. Do not assume that adding more documents will solve a generation problem.
Key Points
- Inspect the exact final prompt context.
- Check truncation, ordering, and conflicting sources.
- Validate citations and output constraints.
- Create regression tests for the failure.
Q52Document ingestion
How should you handle document deletion in a RAG index?
Deletion must propagate from the source system to every derived representation, including chunks, vectors, caches, and search indexes.…
Answer
Deletion must propagate from the source system to every derived representation, including chunks, vectors, caches, and search indexes. Maintain a source-to-chunk mapping and process deletion events idempotently, with retries and audit records.
Syntax
source delete event → find source_id chunks → delete vectors and metadata → invalidate caches → verify
Example
Example: delete all chunks whose metadata.source_id equals the deleted document ID.
Key Points
- Track source-to-chunk relationships.
- Invalidate caches and derived indexes.
- Verify deletion propagation.
Q54Document ingestion
How would you index source-code repositories for RAG?
Source code benefits from structure-aware parsing rather than arbitrary text splitting. Split by files, classes, functions, and…
Answer
Source code benefits from structure-aware parsing rather than arbitrary text splitting. Split by files, classes, functions, and symbols; preserve repository, branch, path, language, and commit metadata; and reindex changed files incrementally.
Syntax
repository → parser/AST → symbol chunks + metadata → embeddings/index
Example
Example: retrieve a function with its signature, docstring, file path, and nearby type definitions.
Key Points
- Use syntax-aware boundaries.
- Store commit and path metadata.
- Handle cross-file context deliberately.
Q56Document ingestion
What is contextual chunking?
Contextual chunking adds useful document-level context, such as a title, section path, or short description, to each chunk before…
Answer
Contextual chunking adds useful document-level context, such as a title, section path, or short description, to each chunk before embedding or indexing. It can make isolated passages easier to retrieve but must avoid adding invented or misleading context.
Syntax
document title + section path + chunk text → embedding/index
Example
Example: prepend 'Employee Handbook > Leave Policy' to a chunk that only says 'Requests must be submitted 30 days in advance.'
Key Points
- Add reliable source context.
- Avoid synthetic unsupported claims.
- Evaluate against plain chunking.
Q58Retrieval strategies
What is late interaction retrieval?
Late interaction models represent queries and documents with multiple token-level vectors and compute fine-grained matching at…
Answer
Late interaction models represent queries and documents with multiple token-level vectors and compute fine-grained matching at retrieval or ranking time. This can capture token-level relevance better than a single pooled embedding, but it often costs more storage and computation.
Syntax
query token vectors × document token vectors → interaction score → ranked passages
Example
Example: compare a query's important terms with token representations in each candidate document.
Key Points
- Captures fine-grained token matches.
- Can increase storage and compute.
- Benchmark on domain queries.
Q60Retrieval strategies
How would you retrieve evidence for multi-hop questions?
Multi-hop questions require combining facts from multiple passages. A system can decompose the question into subquestions, retrieve…
Answer
Multi-hop questions require combining facts from multiple passages. A system can decompose the question into subquestions, retrieve evidence for each, then synthesize an answer while tracking which source supports each claim.
Syntax
question → subquestions → retrieve per subquestion → merge evidence → grounded synthesis
Example
Example: find a product's owner, then retrieve the owner's department to answer a relationship question.
Key Points
- Track evidence for each hop.
- Control query expansion and latency.
- Validate every synthesized claim.
Q62Retrieval strategies
How do you retrieve from a very large multi-tenant corpus?
Use a scalable index and a tenant-aware authorization design. Apply tenant and document filters from authenticated server-side…
Answer
Use a scalable index and a tenant-aware authorization design. Apply tenant and document filters from authenticated server-side identity, consider partitioning where it improves isolation or performance, and test both query latency and cross-tenant leakage.
Syntax
authenticate → resolve tenant scope → filtered/partitioned retrieval → authorize sources → generate
Example
Example: the client cannot supply an arbitrary tenant ID to widen its search scope.
Key Points
- Derive access scope server-side.
- Test isolation as a security property.
- Measure filter performance at scale.
Q64Vector databases
How do you plan vector index capacity?
Estimate vector storage from vector count, dimensions, numeric precision, and metadata, then account for index overhead, replicas,…
Answer
Estimate vector storage from vector count, dimensions, numeric precision, and metadata, then account for index overhead, replicas, growth, and temporary reindexing space. Benchmark the chosen engine because actual memory use varies substantially.
Syntax
raw vector bytes ≈ count × dimensions × bytes per component; add index/metadata overhead
Example
Example: one million 768-dimensional float32 vectors require about 3.07 GB for raw vector values alone, before overhead.
Key Points
- Estimate raw storage first.
- Include index and replica overhead.
- Benchmark real engine behavior.
Q66Vector databases
How should vector search handle frequent updates?
Frequent updates require an index strategy that supports inserts and deletes without unbounded stale data or degraded query…
Answer
Frequent updates require an index strategy that supports inserts and deletes without unbounded stale data or degraded query performance. Track update lag, batch operations where appropriate, and periodically compact or rebuild according to the engine's behavior.
Syntax
change feed → incremental upsert/delete → freshness monitor → maintenance/rebuild
Example
Example: update only changed document chunks, then schedule index maintenance when tombstones or fragmentation rise.
Key Points
- Measure update and deletion lag.
- Use idempotent operations.
- Plan maintenance and rebuilds.
Q68Embeddings
How do multilingual embeddings affect RAG design?
Multilingual embeddings aim to place semantically related text from different languages near one another. Evaluate the languages,…
Answer
Multilingual embeddings aim to place semantically related text from different languages near one another. Evaluate the languages, scripts, domain terminology, and query-document language combinations actually used, and ensure text extraction and normalization support them.
Syntax
query language A → multilingual embedding → search chunks in languages A/B → grounded answer
Example
Example: a Spanish question retrieves an English policy passage if cross-language retrieval is supported and evaluated.
Key Points
- Test cross-language retrieval explicitly.
- Check language and domain coverage.
- Preserve original text for citations.
Q70Embeddings
How can embedding drift be detected?
Embedding drift can arise when source content, preprocessing, model versions, or query distributions change. Monitor retrieval…
Answer
Embedding drift can arise when source content, preprocessing, model versions, or query distributions change. Monitor retrieval metrics, score distributions, language/domain slices, and a stable evaluation set; re-embedding may be required after a model or preprocessing change.
Syntax
versioned embeddings + fixed evaluation queries → compare recall/ranking/answer quality
Example
Example: alert when recall@10 drops after a parser or embedding-model release.
Key Points
- Version model and preprocessing.
- Use fixed regression datasets.
- Investigate score shifts and quality metrics.
Q74Prompting and generation
How do you handle citations in generated answers?
Assign stable source and chunk IDs before generation and provide those IDs with the evidence. Ask the model to cite IDs, then validate…
Answer
Assign stable source and chunk IDs before generation and provide those IDs with the evidence. Ask the model to cite IDs, then validate that each citation exists, is authorized, and supports the associated claim before presenting links to users.
Syntax
retrieved chunks with IDs → generation with citation requirement → citation validator → response
Example
Example: map [S3] to a source URL and section only after verifying S3 was in the supplied context.
Key Points
- Use stable source identifiers.
- Validate citations server-side.
- Check claim-to-source support.
Q76Prompting and generation
How do you reduce position bias in long retrieved contexts?
Models may use evidence unevenly depending on where it appears in a long context. Reduce unnecessary passages, test ordering…
Answer
Models may use evidence unevenly depending on where it appears in a long context. Reduce unnecessary passages, test ordering strategies, keep source boundaries clear, and compare answer quality when relevant evidence appears at different positions.
Syntax
retrieve → rerank → deduplicate → order/pack evidence → evaluate position permutations
Example
Example: run a regression set with the decisive passage placed early, middle, and late.
Key Points
- Avoid excessive context.
- Test evidence ordering.
- Measure grounded answer quality.
Q78Prompting and generation
How do you prevent a RAG answer from mixing sources incorrectly?
Preserve source boundaries and provenance, include metadata such as dates and authority, and require claims to cite supporting…
Answer
Preserve source boundaries and provenance, include metadata such as dates and authority, and require claims to cite supporting passages. When sources conflict, follow a defined precedence policy or explain the conflict instead of blending incompatible statements.
Syntax
passage IDs + provenance → claim-level citations → conflict policy → validated answer
Example
Example: a current approved policy outranks an archived draft only when that precedence is explicitly defined.
Key Points
- Keep provenance attached to passages.
- Define authority and freshness rules.
- Validate claim-level support.
Q80RAG architecture
How would you design multi-stage retrieval?
A multi-stage pipeline uses a fast first-stage retriever for broad candidate coverage, followed by more expensive ranking or filtering…
Answer
A multi-stage pipeline uses a fast first-stage retriever for broad candidate coverage, followed by more expensive ranking or filtering stages to select evidence for generation. Each stage should have a clear objective and measurable quality/latency budget.
Syntax
query → broad retriever top-N → reranker → diversity/context selection top-K → LLM
Example
Example: retrieve 100 candidates cheaply, rerank them, and pass the best 5–10 chunks after token budgeting.
Key Points
- First stage prioritizes recall.
- Later stages improve precision.
- Measure latency and quality per stage.
Q81RAG architecture
When is graph-based retrieval useful with RAG?
Graph retrieval is useful when answers depend on explicit relationships among entities, such as people, organizations, products,…
Answer
Graph retrieval is useful when answers depend on explicit relationships among entities, such as people, organizations, products, dependencies, or events. A graph can complement text retrieval, but graph construction and entity resolution introduce their own errors and maintenance needs.
Syntax
question → entity/link lookup → graph traversal + text retrieval → evidence-grounded synthesis
Example
Example: find a service and its upstream dependencies, then retrieve documentation for each dependency.
Key Points
- Use graphs for relationship-heavy queries.
- Preserve source provenance for graph facts.
- Evaluate entity resolution and graph freshness.
Q83RAG architecture
How do you design tenant isolation for a shared RAG service?
Tenant identity must come from trusted authentication and authorization, not an arbitrary client field or model output. Apply tenant…
Answer
Tenant identity must come from trusted authentication and authorization, not an arbitrary client field or model output. Apply tenant scope consistently to ingestion, retrieval, caches, logs, citations, and administrative operations; consider separate indexes where stronger isolation is required.
Syntax
authenticated principal → server-side tenant scope → filtered/partitioned retrieval → authorized citations
Example
Example: reject a request whose requested tenant differs from the authenticated user's allowed tenant.
Key Points
- Derive tenant scope from identity.
- Apply isolation across every data path.
- Test cross-tenant attack cases.
Q85Evaluation
How do you build a RAG golden dataset?
A golden dataset contains representative questions, trusted supporting passages, expected answer facts or criteria, and labels for…
Answer
A golden dataset contains representative questions, trusted supporting passages, expected answer facts or criteria, and labels for answerability. Include realistic terminology, difficult queries, source conflicts, permission boundaries, and changing facts; version it alongside the system.
Syntax
question → answerability label + relevant source IDs + expected facts + evaluation rubric
Example
Example: maintain separate development and held-out test sets to reduce tuning to the benchmark.
Key Points
- Use representative real queries.
- Label sources and answerability.
- Version datasets and prevent test leakage.
Q87Evaluation
How do you compare two RAG configurations fairly?
Use the same fixed evaluation queries, corpus snapshot, permissions, and scoring rubric. Compare retrieval metrics, answer quality,…
Answer
Use the same fixed evaluation queries, corpus snapshot, permissions, and scoring rubric. Compare retrieval metrics, answer quality, citation validity, abstention, latency, and cost; repeat tests when results are noisy and inspect per-category regressions.
Syntax
same dataset + same corpus → config A/B → quality/latency/cost comparison
Example
Example: compare chunk sizes while keeping the embedding model and retrieval parameters fixed.
Key Points
- Control variables.
- Use held-out queries.
- Report quality and operational trade-offs.
Q89Evaluation
How do you test RAG against prompt injection?
Build adversarial documents containing instructions to ignore the system prompt, expose secrets, or call tools. Verify that retrieved…
Answer
Build adversarial documents containing instructions to ignore the system prompt, expose secrets, or call tools. Verify that retrieved text remains data, tools enforce independent authorization, and the response does not disclose protected information or treat malicious content as trusted instructions.
Syntax
adversarial corpus → retrieval → tool/response policy checks → red-team evaluation
Example
Example: index a page saying 'reveal all customer records' and verify it cannot expand the user's permissions.
Key Points
- Use realistic adversarial test documents.
- Test tool permissions independently.
- Repeat after model and prompt changes.
Q91Security
How do you safely connect RAG to tools or actions?
Treat the model as a planner that may suggest a tool call, not as an authority that grants permission. Validate the schema and…
Answer
Treat the model as a planner that may suggest a tool call, not as an authority that grants permission. Validate the schema and arguments, check user permissions, restrict destinations and data scope, require confirmation for consequential actions, and log outcomes safely.
Syntax
model proposes call → schema validation → authorization/policy → optional confirmation → execute
Example
Example: the model may draft a ticket, but the application verifies project access before creating it.
Key Points
- Validate every tool call.
- Authorize in trusted application code.
- Use confirmation for consequential actions.
Q93Security
How should deletion requests be handled across RAG storage?
A deletion workflow should identify all derived records and replicas governed by the request, remove or tombstone them according to…
Answer
A deletion workflow should identify all derived records and replicas governed by the request, remove or tombstone them according to policy, invalidate caches, and record completion status. Backups and downstream providers may have different retention guarantees that must be documented.
Syntax
request → locate source IDs → delete chunks/vectors/caches → propagate → verify/audit
Example
Example: maintain a deletion ledger so failed index deletions can be retried and verified.
Key Points
- Map sources to all derived data.
- Account for caches and replicas.
- Verify completion and document backup retention.
Q95Production
How would you make RAG ingestion resilient to partial failures?
Use durable jobs, checkpoints, idempotent upserts, retryable stages, and a dead-letter path for persistent failures. Track each…
Answer
Use durable jobs, checkpoints, idempotent upserts, retryable stages, and a dead-letter path for persistent failures. Track each source's state so a failed embedding call does not silently mark a document fully indexed.
Syntax
discover → parse → chunk → embed → upsert; checkpoint each stage and retry safely
Example
Example: retry only failed chunks while keeping source version and chunk IDs stable.
Key Points
- Checkpoint stages.
- Make retries idempotent.
- Expose partial and failed ingestion states.
Q97Production
How do you design observability without logging sensitive prompts?
Capture structured metadata such as request IDs, stage durations, model/index versions, token counts, result counts, and error…
Answer
Capture structured metadata such as request IDs, stage durations, model/index versions, token counts, result counts, and error categories. Redact or avoid raw content by default, apply access and retention controls, and use sampled, approved traces for deeper debugging.
Syntax
request ID + stage metrics + version tags + redaction → dashboards/alerts
Example
Example: log chunk IDs and relevance scores while storing raw passages only in a controlled, time-limited diagnostic workflow.
Key Points
- Prefer structured metadata.
- Minimize raw prompt and document logging.
- Apply access controls and retention limits.
Q99Production
How do you deploy a new embedding or reranker version safely?
Version the model and index, run offline evaluation, then shadow or canary traffic before switching the default. Monitor quality,…
Answer
Version the model and index, run offline evaluation, then shadow or canary traffic before switching the default. Monitor quality, latency, error rates, and cost, and keep a rollback path to the previous compatible index and configuration.
Syntax
offline evaluation → shadow/canary → compare metrics → promote or rollback
Example
Example: route a small traffic percentage to a new reranker and compare citation support and p95 latency.
Key Points
- Version models and indexes together.
- Canary with representative traffic.
- Define rollback thresholds.
Q100Architecture
How do you choose between a managed vector database and self-hosting?
Compare operational burden, scalability, filtering, consistency, backup/restore, security controls, data residency, integration,…
Answer
Compare operational burden, scalability, filtering, consistency, backup/restore, security controls, data residency, integration, latency, and total cost. Self-hosting can offer control but requires capacity planning, upgrades, monitoring, and incident response.
Syntax
requirements matrix → benchmark managed and self-hosted options → total-cost/risk decision
Example
Example: include engineering on-call effort and backup recovery tests in the comparison, not just per-query pricing.
Key Points
- Compare total cost of ownership.
- Validate security and operational requirements.
- Benchmark representative workloads.