Design a RAG System
Understanding the Problem
📚 What is a RAG system? Retrieval-augmented generation (RAG) answers a question by first searching a document collection for the passages most likely to contain the answer, then giving those passages to a large language model and asking it to answer from them, with citations. The model supplies language and reasoning; the documents supply facts it was never trained on, such as a company's contracts, wiki or support tickets. A RAG system is everything that makes that loop work at scale: ingestion, indexing, retrieval, generation and keeping it all up to date.
You'll get this question in a few forms: "design a RAG pipeline," "design enterprise RAG over millions of documents," or "design a legal research assistant like Harvey." They are one system. Enterprise RAG adds scale and multi-tenancy; legal RAG raises the bar on precision, citations and confidentiality. We'll design the general platform and then cover what changes for legal work in its own deep dive.
The retrieval building blocks (chunking strategies, embedding models, hybrid search, reranking) are explained in RAG Fundamentals. Here we focus on the system: how documents flow in, how the index scales and stays fresh, and how answers stay grounded.
Functional Requirements
We're building a multi-tenant RAG platform. Each customer (a company or a law firm) connects its document stores, and its employees ask questions.
Core Requirements
- Admins should be able to add documents (upload, or connect sources such as S3, SharePoint or Google Drive), and new, changed and deleted documents should be reflected in answers.
- Users should be able to ask a natural-language question, including follow-ups in a conversation, and get an answer generated from their organization's documents.
- Answers should cite the passages they rely on, and users should be able to open each source at the cited page.
- Users should only get answers from documents they are allowed to read.
Below the line (out of scope)
- Building and operating connectors for dozens of SaaS apps, and the full permission model behind them. That's Enterprise Search.
- Fine-tuning the LLM on customer data.
- Multi-step agents that take actions. We'll cover multi-step retrieval for hard questions, not tools.
- Document editing and drafting workflows.
Non-Functional Requirements
Ask your interviewer for scale. We'll design for 1,000 tenants with 200M documents in total; the largest tenant has 20M. Documents average about 10 pages.
Core Requirements
- Answers should be grounded: every factual claim should be supported by a cited passage, and when the documents don't contain the answer, the system should say so instead of guessing.
- The system should start streaming an answer within 2 seconds (retrieval itself under 300 ms at p95) and handle 500 queries per second at peak.
- New and changed documents should be searchable within 10 minutes. Deletions and permission removals should take effect within 1 minute.
- Tenants must be strictly isolated: no query can ever retrieve another tenant's content.
- Ingestion should keep up with about 5M document changes a day and handle bulk backfills of millions of documents when a tenant joins.
Below the line (out of scope)
- Multi-region replication and data residency (important for legal customers, but a separate discussion).
- Choosing the LLM. We'll assume a strong hosted or self-hosted model behind a gateway.
The back-of-the-envelope is about the index, and it's bigger than people expect:
- 10 pages is roughly 5,000 tokens. At about 500 tokens per chunk, that's 10 chunks per document, so 2B chunks.
- A 1,024-dimension float32 embedding is 4 KB. 2B x 4 KB = 8 TB of vectors, before the graph structure an HNSW index adds on top. That doesn't fit in one machine's memory, or cheaply in a cluster's. Quantizing to int8 brings it to 2 TB; product quantization can bring it well under 1 TB.
- Embedding the corpus once is real but bounded GPU work. At on the order of 2,000 chunks per second per GPU for a mid-size embedding model, 2B chunks is about 280 GPU-hours. That matters when we change embedding models: it's a planned migration, not a config flip.
- Queries are modest: 500 QPS of retrieval is easy for a sharded index. The LLM is the expensive part per query, with 5-20k tokens of retrieved context per answer.
The query side of RAG gets most of the attention in interviews, but most production problems are on the ingestion side: badly parsed PDFs, stale chunks after an edit, a deleted document that still shows up in answers. A candidate who designs ingestion carefully stands out.
The Set Up
Planning the Approach
We'll build the ingestion pipeline first, then the query path, then citations and permissions. The deep dives cover retrieval quality, scaling the index, freshness and deletes, grounding, and legal RAG.
Defining the Core Entities
- Tenant: a customer organization. Everything else is scoped to one.
- Source: a connected repository (an S3 bucket, a SharePoint site, an upload folder) with sync state.
- Document: one file, with a stable ID, a version, a content hash, its access control list (ACL) and metadata (title, author, date, type, matter or project).
- Chunk: a passage of a document version, with its text, its position (page, section, character offsets) and its embedding. Chunks are what we retrieve and cite.
- Query and Answer: a user's question in a conversation, the chunks retrieved for it, and the generated answer with citations. We keep these for debugging and evaluation.
API or System Interface
POST /sources { type, config, schedule } -> { sourceId }
POST /documents multipart file + metadata -> { documentId, version }
DELETE /documents/{documentId}
POST /conversations/{id}/questions { question, filters? } (streams via SSE)
-> event: answer_delta data: { text: "The indemnity cap is ..." }
-> event: citation data: { n: 1, chunkId, documentId, title, page, quote }
-> event: done
GET /documents/{documentId}/view?page=14&highlight=chunkId
filters lets users scope a question ("only contracts with Acme," "only 2024 board minutes"). The user's identity and tenant come from the auth token, never from the request body.
High-Level Design
1) Admins should be able to add documents, and changes should show up in answers
Start with the simplest version: on upload, the API parses the file, splits it into chunks, embeds them and writes them to a vector database, all inside the request. That breaks on the first 300-page PDF (parsing and embedding take minutes) and on the first bulk import (a million files at once). Ingestion is a pipeline, so build it as one.
- Land the raw file. Uploads and connector syncs write the original file to S3 (keyed by tenant, document and version) and a row to the Document Store (Postgres): ID, version, hash, ACL, metadata, status
pending. Then they publish adocument_changedevent to Kafka. - Parse. Parser workers turn files into structured text: PDF text extraction with layout (headings, tables, page numbers), OCR for scanned pages, and converters for Word, HTML, email and slides. The output is a normalized document with sections and page coordinates, also stored in S3. Parsing is where quality is won or lost: a table flattened into word soup can't be retrieved or quoted.
- Chunk. Split by structure first (sections, headings, paragraphs, table rows), then by size (around 300-800 tokens, with a little overlap). Each chunk keeps its document ID, version, page and offsets, and a short header (document title and section path) so a chunk makes sense on its own.
- Embed. Embedding workers on GPUs batch chunks and call the embedding model. Batching matters: a GPU embeds thousands of chunks per second in large batches and far fewer one at a time.
- Index. Write each chunk to the Search Index, which holds both a vector index and a keyword (BM25) index, with tenant, document, ACL and metadata fields for filtering. Mark the document
indexed.
Every stage reads from a queue and writes its output somewhere durable before acknowledging, so a crash just means a retry. Each stage scales on its own: parsing is CPU-heavy, embedding is GPU-heavy, indexing is I/O-heavy. Bulk backfills from a new tenant go on a separate low-priority topic so they don't delay the 10-minute freshness target for everyone else.
2) Users should be able to ask questions and get answers from their documents
The query path has four steps:
- Rewrite the question. In a conversation, "what about the 2023 one?" means nothing on its own. A small, fast LLM call rewrites it into a standalone query ("indemnification cap in the 2023 Acme master services agreement") using the conversation history. It can also extract filters (date ranges, document types) and split a compound question into sub-queries.
- Retrieve. Run the rewritten query against the Search Index in two ways at once: a vector search for semantic matches and a BM25 search for exact terms (names, clause numbers, product codes), both filtered to the user's tenant and permissions. Merge the two lists (reciprocal rank fusion is a simple, strong default) and keep the top ~100.
- Rerank. A cross-encoder reranker scores each (query, chunk) pair together, which is much more accurate than comparing two separate embeddings. Keep the top 8-20 chunks.
- Generate. Build a prompt with instructions, the numbered chunks and the conversation, and stream the LLM's answer back to the client.
The latency budget for the first token, roughly:
| Step | Typical latency |
|---|---|
| Query rewrite (small LLM) | 200-400 ms |
| Embed query | 10-30 ms |
| Hybrid retrieval with filters | 50-150 ms |
| Rerank 100 chunks (GPU cross-encoder) | 50-150 ms |
| LLM prefill on ~10k tokens, first token | 400-1,000 ms |
That's about 1-2 seconds to the first token, which meets the target. The rewrite step is the easiest to skip for the first turn of a conversation, where the question usually stands on its own.
3) Answers should cite their sources
Citations are part of the prompt design, not something bolted on afterwards. Each retrieved chunk goes into the prompt with a number:
[1] (Acme MSA 2023, §9.2 Limitation of Liability, p. 14)
"Except for obligations under Section 8, each party's aggregate liability ..."
[2] (Acme MSA 2023 Amendment No. 1, §2, p. 2)
"Section 9.2 of the Agreement is amended to replace 'twelve (12) months' with ..."
The instructions tell the model to answer only from the sources, put a marker like [2] after each claim, and say "I couldn't find this in the documents" when they don't cover the question. As the answer streams, the Query Service parses the markers and emits citation events that map each number to a chunk ID, document, page and quote. The client renders them as links; clicking one opens the document viewer at that page with the chunk's offsets highlighted.
Two checks happen after generation (we'll go deeper in the grounding deep dive): every cited number must be one we actually provided, and the quoted text must exist in that chunk. An answer that cites [7] when we gave the model six sources is a bug we want to catch, not show.
4) Users should only see answers from documents they can read
Every chunk carries the tenant ID and the document's ACL, as a list of principals (user and group IDs) allowed to read it. At query time we resolve the user's principals (their user ID and every group they belong to, cached for a few minutes) and add a filter to both retrievals: tenant_id = T AND acl_principals IN (user's principals).
The rule is that permissions are enforced inside retrieval, before anything reaches the LLM. Filtering the answer afterwards doesn't work: once a restricted chunk is in the prompt, the model can paraphrase it, and no post-filter will catch that reliably.
Tenant isolation is stronger than a filter: we'll give each tenant its own index partition (next deep dive), so a bug in a filter can't leak across companies. Permission sync from source systems, which is the hard part when you connect SharePoint or Google Drive, is covered in Enterprise Search.
Potential Deep Dives
1) How do we retrieve the right passages from millions of documents?
Retrieval quality caps answer quality. If the right chunk isn't in the top 10, the model can't use it, and it will often confidently answer from the wrong one.
Bad Solution: Vector Search Only
Approach
Embed the question and take the top 5 chunks by cosine similarity.
Challenges
Embeddings are good at meaning and bad at exact identifiers. "What does section 14.3 say?" or "invoices from vendor 88213" retrieve passages that are about similar things, not the ones with that number. The top 5 from a 20M-document corpus are also often near-duplicates: five versions of the same template, all saying the same thing. And without filters, the question "what did the 2022 audit find?" happily returns the 2019 audit.
Good Solution: Hybrid Retrieval With Metadata Filters
Approach
Run BM25 and vector search in parallel and fuse them, as in the high-level design. Extract structured filters from the question (dates, document types, parties) and apply them in both searches. Deduplicate near-identical chunks by content hash or embedding similarity before taking the top results.
Challenges
Fusion ranks are crude: a chunk that ranks 3rd in BM25 and 40th in vectors may be the best one, or not. Five chunks is often too few for questions that need several passages (a clause plus its amendment plus a definition), and fifty is too many to put in front of the model without diluting it.
Great Solution: Hybrid Retrieval, Reranking and Multi-Step Queries
Approach
Retrieve wide, then rank narrow. Hybrid retrieval returns ~100-200 candidates cheaply; a cross-encoder reranker (a fine-tuned BERT-class model or a hosted reranking API) scores each against the query and keeps the best 8-20. That recovers most of the recall lost by a small top-k without flooding the prompt.
For questions that need more than one hop ("which of our vendor contracts have a liability cap lower than the one in our Acme MSA?"), let the LLM plan: retrieve the Acme cap first, then issue a second retrieval with that number, possibly over many documents. A bounded loop of 2-3 retrievals covers most such questions without becoming a full agent.
Expand context around the winners: if chunk 14 of a contract wins, include its section heading and, for definitions-heavy text, the definitions it refers to. Storing each chunk's neighbors and section path makes this a cheap lookup.
Challenges
The reranker adds 50-150 ms and GPU cost per query; it's almost always worth it. Multi-step retrieval multiplies latency, so trigger it only when the planner decides one pass isn't enough, and stream a "searching..." status so the wait feels intentional. Measure all of this with a labeled set of questions and known-relevant chunks per tenant type (recall@k for retrieval, then answer quality), or you're tuning blind. See LLM Evaluation.
2) How do we scale the index to billions of chunks and a thousand tenants?
We worked out 2B chunks and 8 TB of raw vectors. Tenants vary by four orders of magnitude, from a 2,000-document startup to a 20M-document bank.
Bad Solution: One Big Index for Everyone
Approach
Put every chunk in one giant HNSW index in a vector database and filter by tenant_id at query time.
Challenges
Everything is wrong at once. Memory: HNSW wants the vectors and graph in RAM, which is tens of terabytes with overhead. Filtering: a filter that matches 0.01% of the index (one small tenant) makes graph search slow or inaccurate, because most of the neighbors it walks are filtered out. Isolation: one filter bug leaks data between companies. Operations: a rebuild or reindex touches every tenant at once.
Good Solution: Partition by Tenant
Approach
Give each tenant its own index (a namespace, collection or set of shards, depending on the engine). Small tenants share physical nodes but have separate logical indexes; queries only ever touch the caller's index, so isolation is structural, not a filter. Within a tenant, the ACL filter is selective enough that filtered vector search works well.
Challenges
The largest tenants still don't fit on one node: 20M documents is 200M chunks, 800 GB of float32 vectors. And thousands of small indexes, each mostly idle, waste memory if every one is kept hot.
Great Solution: Tenant Partitions, Sharded Large Tenants, Quantization and Tiering
Approach
Combine a few techniques:
- Shard large tenants by document ID hash across several nodes; a query fans out to that tenant's shards and merges results. Small tenants are packed many to a node.
- Quantize. Store int8 or product-quantized vectors in the index and keep full-precision vectors on SSD or in S3 for re-scoring the top few hundred candidates. This cuts memory 4-16x for a small recall loss, which the rescoring and reranker mostly win back. Smaller embedding dimensions (models trained to truncate to 256 or 512 dimensions) help further.
- Disk-based indexes such as DiskANN, or IVF-PQ, keep most of the index on NVMe SSD with a small in-memory structure, trading a few milliseconds of latency for an order of magnitude less RAM. Use them for big, rarely queried tenants.
- Tier by activity. Tenants with recent queries stay in memory; idle tenants are loaded on demand. A cold start of a few seconds on the first query of the day is acceptable for a small tenant.
Engines like Elasticsearch or OpenSearch (BM25 plus HNSW in one place), Vespa, Milvus, or a managed service like Pinecone can all do this; the design matters more than the brand. Keeping BM25 and vectors in one engine avoids a second fan-out and lets one filter apply to both. Vector Databases compares them.
Challenges
Sharding a tenant means every query fans out, so p99 is set by the slowest shard; keep shard counts modest and replicate hot tenants. Moving tenants between nodes as they grow needs a rebalancing process (copy, dual-write, switch the routing table, delete). And quantization levels need to be validated against the tenant's own evaluation set, not assumed.
3) How do we keep the index fresh as documents change and get deleted?
Documents are edited, replaced and deleted constantly, and permission changes are just as frequent. A stale index gives wrong answers; a deleted document that still appears in answers is a security incident.
Bad Solution: Nightly Full Re-Index
Approach
Every night, re-crawl every source, re-parse and re-embed everything, and swap in the new index.
Challenges
Re-embedding 2B chunks is 280 GPU-hours a night for mostly unchanged text, and the index is up to a day stale. A document deleted at 9 a.m. keeps showing up in answers until tomorrow.
Good Solution: Incremental Updates From Change Events
Approach
Connectors detect changes (webhooks, change feeds such as Google Drive's changes API or Microsoft Graph delta queries, or periodic listing with modification times) and publish document_changed or document_deleted events. We compare the new content hash with the stored one and skip unchanged files. Changed documents are re-processed; their old chunks are deleted from the index and new ones added.
Challenges
"Delete old, add new" has a gap where the document is half there or appears twice, and if the delete fails, stale chunks linger forever. A tiny edit to a 300-page contract re-embeds all 300 pages. And deletion speed depends on how fast the index applies deletes, which in segment-based engines can lag.
Great Solution: Versioned Documents, Chunk-Level Diffs and a Deletion Fast Path
Approach
- Versioned, atomic switches. Each chunk is stored with its document version. When version 8 is fully indexed, we update the Document Store's
current_versionto 8 in one write. Queries filter on, or post-check,version = current_versionusing a small, cached lookup, so readers see either all of v7 or all of v8, never a mix. A cleanup job removes old-version chunks afterwards. - Chunk-level diffs. Chunk boundaries are deterministic (based on structure), so most chunks of an edited document have the same text as before. Hash each chunk's text and reuse existing embeddings for unchanged hashes; only new or changed chunks hit the GPUs. A typo fix re-embeds one chunk, not 300 pages.
- Deletion fast path. Deletes and permission removals skip the pipeline queue and go on a high-priority topic. The Document Store marks the document deleted (or updates its ACL) immediately, and the query path checks retrieved document IDs against a deny list cached in Redis before building the prompt. That makes the 1-minute target independent of how quickly the index physically purges the chunks.
- Embedding model migrations. Changing the embedding model invalidates every vector. Build a new index alongside the old one (backfill at low priority, dual-write new changes to both), evaluate it on the tenant's question set, then flip an alias and retire the old one. This is a planned multi-day project at 280 GPU-hours, which is fine as long as nobody pretends it's instant.
Challenges
More moving parts: version lookups on the query path, a deny list to keep in sync, cleanup jobs to monitor. A periodic reconciliation job (list each source, compare with the Document Store, fix differences) catches events that were missed, because webhooks do get dropped.
Interviewers love asking "a user deletes a document; how long until it stops appearing in answers, and how do you know?" Have a number, a mechanism (the deny list), and a way to verify (reconciliation plus a test that queries for deleted documents).
4) How do we keep answers grounded and catch hallucinations?
Retrieval gets the right passages into the prompt. The model can still ignore them, blend them with what it remembers from training, or cite the wrong one.
Constrain the model. The system prompt says to answer only from the numbered sources, cite each claim, quote exact language for anything legal or numerical, and say plainly when the sources don't answer the question. Put the sources before the question in the prompt and keep their order stable; it helps both the model and prompt caching.
Abstain when retrieval is weak. If the reranker's best score is below a threshold, don't generate a confident answer. Say that nothing relevant was found and show the closest documents. A clear "I don't know" is worth more than a fluent wrong answer, especially in legal or financial settings.
Verify citations after generation. For each claim with a citation:
- the cited source number must exist in the prompt;
- quoted text must appear in that chunk (a normalized string match);
- optionally, a small NLI or judge model checks that the chunk supports the claim. Unsupported claims get flagged in the UI or trigger a regenerate.
Measure continuously. Keep a labeled set of questions per domain with expected answers and supporting chunks. Track retrieval recall@k, citation precision (cited chunks that support their claims), faithfulness (claims supported by some source) and abstention accuracy. Sample production answers for review and collect thumbs up/down with the retrieved context, so a bad answer can be traced to parsing, retrieval or generation. This is the job of an LLM evaluation system.
5) What changes for legal RAG?
Legal work is RAG at its most demanding. A lawyer will rely on the answer in front of a client or a judge, a wrong citation can be sanctionable, and the documents are among the most confidential a company holds. The architecture stays the same; the requirements tighten.
- Matter-level isolation and ethical walls. Law firms work for clients on opposite sides of deals. A lawyer walled off from a matter must never retrieve its documents. Treat the matter as a first-class security boundary: every document carries a
matter_id, walls are enforced as ACLs in retrieval, and queries are scoped to one matter (or an explicit set) by default. - Structure-aware parsing and chunking. Contracts have numbered sections, defined terms, schedules and amendments. Chunk by clause, keep the section path ("Article 9 > 9.2 Limitation of Liability") on every chunk, and link defined terms to their definitions so a clause that says "Losses" brings the definition of "Losses" with it. Amendments must be linked to the clauses they change, or the system will confidently report the superseded cap.
- Precision over fluency. Prefer exact quotes over paraphrase, cite at the pinpoint level (page and paragraph), and abstain more readily. Show retrieved passages side by side with the answer so the lawyer can check it.
- Whole-document tasks. "Review this 80-page contract against our playbook" isn't a retrieval question. Every clause matters. With long-context models, send the whole document (or process it section by section and aggregate), and use retrieval only to bring in the playbook and precedents. A good system routes between "search the corpus" and "read this document" based on the task.
- Case law and statutes. For public legal research, retrieval runs over a licensed case law corpus, and citations must point to real cases that say what the answer claims. Verify every case citation against the corpus (does this case exist, does the quoted passage appear in it) before showing it. Hallucinated case citations are the most famous failure mode of legal AI.
- Confidentiality and audit. No customer data is used to train shared models; LLM providers are used under zero-data-retention terms or the model is self-hosted; every query, retrieved document and answer is logged for audit; and data stays in the region the firm requires.
If you're asked the Harvey version, lead with the ethical wall and citation verification. They show you understand what makes legal different, and they're more interesting to the interviewer than another round of chunk-size tuning.
Final Design
The full flow:
- Uploads and connectors write raw files to S3 and document rows (version, hash, ACL, metadata) to the Document Store, and publish change events to Kafka. Deletes and permission removals go on a fast-path topic that updates the deny list within seconds.
- Parser workers extract structured text with page coordinates; chunkers split by structure; embedding workers embed only chunks whose text hash changed; the indexer writes chunks to the tenant's partition of the Search Index (BM25 plus quantized vectors) and flips the document's current version.
- A user's question goes to the Query Service, which rewrites it into a standalone query with filters and resolves the user's principals.
- Hybrid retrieval runs inside the tenant's partition with ACL and metadata filters; results are checked against the deny list and current versions, then reranked by a cross-encoder.
- The LLM, behind a gateway, receives numbered sources and streams an answer with citations; the Query Service maps citations to documents and pages, verifies them and streams them to the client.
- Queries, retrieved chunks, answers and feedback are logged to an evaluation store that tracks retrieval recall, faithfulness and citation precision over time.
What is Expected at Each Level?
Mid-level
You should describe the basic pipeline end to end: parse, chunk, embed, store in a vector database, retrieve top-k, put chunks in the prompt and generate with citations. You should know why chunk size matters and that the LLM's context is limited. With prompting, you should handle updates (re-index changed documents) and apply a tenant filter at query time.
Senior
You should design ingestion as an asynchronous, retryable pipeline and treat parsing as a first-class quality problem. Expect to argue for hybrid retrieval plus reranking, size the index (chunks, bytes per vector, memory), partition by tenant, and enforce permissions inside retrieval rather than after generation. You should have a concrete answer for deletes and edits, and a plan to measure retrieval and answer quality.
Staff+
You should drive the trade-offs that decide whether this works in production: index tiering and quantization against recall, embedding model migrations as planned projects, a deletion fast path with a verifiable SLA, reconciliation for missed events, and an evaluation program that attributes failures to parsing, retrieval or generation. For legal or other high-stakes domains, you should raise ethical walls, structure-aware chunking, citation verification and data handling without being asked, and know when the task calls for reading a whole document instead of retrieving from many.