Design a RAG System

How to design a question-answering service over company documents, covering ingestion, search, permissions, cost and evaluation, and what interviewers ask.

Case study26 minLesson 8 of 8
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A retrieval-augmented generation (RAG) system answers questions from a large set of documents. For each question it searches the documents, selects the few passages that are most relevant, and gives them to a language model with an instruction to answer only from those passages and to cite them. See RAG basics and chunking and retrieval for the building blocks.

Interviewers ask this question because calling the model is the simple part. The hard parts are keeping millions of changing documents searchable, finding the right passages quickly, never showing someone a document they are not allowed to read, and measuring answer quality. The steps below follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a system that answers employees' questions from company documents.

You

Which documents does it cover, for example a wiki, tickets and shared drives, and can every employee read all of them?

Interviewer

All three, about 10 million documents in total. Permissions vary a lot, and the HR, legal and some engineering spaces are restricted.

You

Then permission checks are a hard requirement. How many employees will use it, and how soon after an edit should the answers reflect it?

Interviewer

There are 20,000 employees, and a changed page should show up within minutes.

You

My priorities are these. The system must never show content that the asker cannot open. Every answer must cite its sources. It should say it does not know instead of guessing. The first words should appear within about 2 seconds, and the cost per question must be controlled.

  • Functional requirements: answer questions with citations using only documents the asker may read, say when the documents do not contain the answer, ingest document changes, and collect feedback on answers.
  • Non-functional requirements: no permission leaks at all, first words within 2 seconds and the full answer within about 10 seconds, edits searchable within 10 minutes, removed access effective within 5 minutes, bounded cost per question, and availability during working hours in every region.
  • Out of scope: actions such as filing tickets, fine-tuning models, and customers outside the company.

Estimate the scale

  • Chunks: 10 million documents with about 5 passages (chunks) each give 50 million chunks.
  • Questions: 20,000 employees asking 10 questions a day give 200,000 questions a day. Over an 8-hour working day (28,800 seconds) that is about 7 a second, or about 20 a second at a 3x peak.
  • Tokens: each question sends 8 chunks of about 500 tokens plus about 500 tokens for instructions, the question and the answer, which is 4,500 tokens. Over 200,000 questions that is 900 million tokens a day, which drives the cost.
Estimate: Size of the vector index

The embedding model turns each chunk into 1,024 numbers stored as 4-byte floats. How much memory do all the vectors take?

You know
  • 10 million documents, about 5 chunks each
  • 1,024 numbers per vector
  • 4 bytes per number

Show the working
  1. Chunks: 10 million × 5 = 50 million
  2. One vector: 1,024 × 4 B ≈ 4 KB
  3. All vectors: 50 × 106 × 4 KB = 200 GB

Estimate 200 GB (anything from 60 GB to 600 GB is a good answer)

Storing each number in 1 byte reduces this to about 50 GB at a small cost in accuracy. Splitting the index across machines is the other option.

Your turn: Define the API

Write the endpoints for the chat window and for the connectors that report document changes. Decide whether the answer comes back as one response or as a stream.

Compare with a model answer

The API needs an ask endpoint that streams the answer and ends with the citations, a feedback endpoint, and an internal endpoint where connectors report changes.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
POST /ask                       Authorization: the employee's identity
  body: { "question": "How do I rotate the staging DB password?", "conversation_id": "c_19"? }
  200  text/event-stream
       event: token     data: "1. Open the "
       ...
       event: done      data: { "answer_id": "a_77", "citations": [
                          { "doc_id": "wiki-4410", "title": "Staging runbook", "url": "..." } ] }
  429  too many questions from this user
  503  model unavailable; body holds the top documents as plain search results
 
POST /answers/{id}/feedback     body: { "helpful": false, "comment": "outdated" }
 
POST /ingest/events             internal, from connectors
  body: { "source": "wiki", "doc_id": "wiki-4410", "change": "updated" | "deleted" | "acl" }
  202 Accepted

The decision worth arguing is streaming. A full answer takes several seconds, but the first words can arrive after about one second, so server-sent events are what meets the 2-second target. The citations come last because the model decides which sources it uses while it writes.

Your turn: Model the data

Decide what an indexed chunk must hold so that it can be searched, cited, filtered by permission and embedded again only when its text changes.

Compare with a model answer

A chunk needs its text, its vector, the document id, a title and link for citations, the groups allowed to read it, and a hash of its text so that unchanged chunks are not embedded again.

Model the data

Documents and chunks
documents                         -- source of truth for what is indexed
  doc_id          VARCHAR(64) PRIMARY KEY     -- "wiki-4410"
  source          VARCHAR(16)
  title, url      TEXT
  allowed_groups  TEXT[]          -- copied from the source system
  content_hash    CHAR(64)
  updated_at      TIMESTAMP
 
chunks                            -- lives in the search index
  chunk_id        VARCHAR(80)     -- "wiki-4410#3"
  doc_id          VARCHAR(64)
  text            TEXT            -- about 500 tokens, about 2 KB
  embedding       VECTOR(1024)
  allowed_groups  TEXT[]          -- filter field
  text_hash       CHAR(64)        -- skip re-embedding unchanged chunks
  index_version   INT             -- which chunker and embedding model made it

The query that runs on every question is "find the nearest vectors and the best keyword matches among the chunks this person may read". That needs a search index that supports vector search, keyword search and filters in one query. A search engine with vector support or a vector database with keyword support both work.

Your turn: High-level design

Sketch both paths: how a document becomes searchable chunks, and how a question becomes a cited answer. Say where the permission check happens.

Compare with a model answer

For ingestion, workers fetch, chunk and embed changed documents and write them to the index with their allowed groups. For a question, the service embeds it, runs a filtered hybrid search, reranks the results and sends the best chunks to the model. The permission check is a filter inside the search.

High-level design

Ingestion (top) keeps the index up to date in the background. A question (bottom) is embedded with the same model, searched with a permission filter, reranked and answered.Doc sources to Ingestion workers (changes, ACLs); Ingestion workers to Embedding model (embed chunks); Ingestion workers to Hybrid search index (upsert); Employee to Answer service (POST /ask); Answer service to Embedding model (embed); Answer service to Hybrid search index (filtered search); Answer service to Reranker (top 50); Answer service to Language model (prompt + 8 chunks).Doc sourcesIngestionworkersEmbedding modelEmployeeAnswer serviceHybrid searchindexLanguage modelRerankerchanges, ACLsembed chunksupsertPOST /askembedfiltered searchtop 50prompt + 8 chunks
Ingestion (top) keeps the index up to date in the background. A question (bottom) is embedded with the same model, searched with a permission filter, reranked and answered.
A question, an edit, a permission change and an outageUse the arrows or ← → keys
  1. A question, an edit, a permission change and an outage, step 1Doc sources to Ingestion workers; Ingestion workers to Embedding model; Ingestion workers to Hybrid search index; Employee to Answer service; Answer service to Embedding model; Answer service to Hybrid search index; Answer service to Reranker; Answer service to Language model.Doc sourcesIngestionworkersEmbedding modelEmployeeAnswer serviceHybrid searchindexLanguage modelReranker
    elapsed ms
    0
    candidates
    0

    1Priya asks her question. The answer service looks up her groups in the directory, which are eng and all-staff.

  2. A question, an edit, a permission change and an outage, step 2Doc sources to Ingestion workers; Ingestion workers to Embedding model; Ingestion workers to Hybrid search index; Employee to Answer service; Answer service to Embedding model; Answer service to Hybrid search index; Answer service to Reranker; Answer service to Language model.Doc sourcesIngestionworkersEmbedding modelquery vectorEmployeeAnswer serviceHybrid searchindexLanguage modelReranker
    elapsed ms
    50
    candidates
    0

    2The service embeds the question with the same model that embedded the chunks. This is budgeted at about 50 ms.

  3. A question, an edit, a permission change and an outage, step 3Doc sources to Ingestion workers; Ingestion workers to Embedding model; Ingestion workers to Hybrid search index; Employee to Answer service; Answer service to Embedding model; Answer service to Hybrid search index; Answer service to Reranker; Answer service to Language model.Doc sourcesIngestionworkersEmbedding modelEmployeeAnswer serviceHybrid searchindexeng, all-staffLanguage modelReranker
    elapsed ms
    150
    candidates
    50

    3One search runs keyword and vector matching on the chunks that eng or all-staff may read, and fuses the results into 50 candidates. This is budgeted at about 100 ms.

  4. A question, an edit, a permission change and an outage, step 4Doc sources to Ingestion workers; Ingestion workers to Embedding model; Ingestion workers to Hybrid search index; Employee to Answer service; Answer service to Embedding model; Answer service to Hybrid search index; Answer service to Reranker; Answer service to Language model.Doc sourcesIngestionworkersEmbedding modelEmployeeAnswer serviceHybrid searchindexLanguage modelReranker50 to 8
    elapsed ms
    350
    candidates
    8

    4The reranker keeps the best 8 of the candidates, within a budget of about 200 ms.

  5. A question, an edit, a permission change and an outage, step 5Doc sources to Ingestion workers; Ingestion workers to Embedding model; Ingestion workers to Hybrid search index; Employee to Answer service; Answer service to Embedding model; Answer service to Hybrid search index; Answer service to Reranker; Answer service to Language model.Doc sourcesIngestionworkersEmbedding modelEmployeeAnswer serviceHybrid searchindexLanguage modelReranker
    elapsed ms
    1350
    candidates
    8

    5The prompt holds the instructions, the 8 numbered chunks and the question, about 4,500 tokens, and we assume the first token comes after about 1 second.

  6. A question, an edit, a permission change and an outage, step 6Doc sources to Ingestion workers; Ingestion workers to Embedding model; Ingestion workers to Hybrid search index; Employee to Answer service; Answer service to Embedding model; Answer service to Hybrid search index; Answer service to Reranker; Answer service to Language model.Doc sourcesIngestionworkersEmbedding modelEmployeeAnswer serviceHybrid searchindexLanguage modelReranker
    elapsed ms
    1350
    citations
    2

    6The tokens stream to Priya, ending with citations. Her first words appeared after 1.35 seconds.

  7. A question, an edit, a permission change and an outage, step 7Doc sources to Ingestion workers; Ingestion workers to Embedding model; Ingestion workers to Hybrid search index; Employee to Answer service; Answer service to Embedding model; Answer service to Hybrid search index; Answer service to Reranker; Answer service to Language model.Doc sourcesIngestionworkers2 of 12 changedEmbedding modelEmployeeAnswer serviceHybrid searchindexLanguage modelReranker
    chunks embedded
    2

    7Someone edits the runbook. A worker splits the page into 12 chunks and compares their hashes. Only 2 chunks changed, so only those 2 are embedded again.

  8. A question, an edit, a permission change and an outage, step 8Doc sources to Ingestion workers; Ingestion workers to Embedding model; Ingestion workers to Hybrid search index; Employee to Answer service; Answer service to Embedding model; Answer service to Hybrid search index; Answer service to Reranker; Answer service to Language model.Doc sourcesIngestionworkersEmbedding modelEmployeeAnswer serviceHybrid searchindexgroups: sreLanguage modelReranker
    chunks embedded
    0

    8The page then moves to a space that only the sre group can read. The permission event updates allowed_groups on its 12 chunks, and nothing is embedded again.

  9. A question, an edit, a permission change and an outage, step 9Doc sources to Ingestion workers; Ingestion workers to Embedding model; Ingestion workers to Hybrid search index; Employee to Answer service; Answer service to Embedding model; Answer service to Hybrid search index; Answer service to Reranker; Answer service to Language model.Doc sourcesIngestionworkersEmbedding modelEmployeeAnswer serviceHybrid searchindex0 runbook chunksLanguage modelReranker
    candidates
    50

    9Priya asks again. The filter excludes those 12 chunks, so the model never sees them.

  10. A question, an edit, a permission change and an outage, step 10Doc sources to Ingestion workers; Ingestion workers to Embedding model; Ingestion workers to Hybrid search index; Employee to Answer service; Answer service to Embedding model; Answer service to Hybrid search index; Answer service to Reranker; Answer service to Language model.Doc sourcesIngestionworkersEmbedding modelEmployeeAnswer serviceHybrid searchindexLanguage modeldownReranker
    status
    503

    10Later the language model goes down. The service still searches and reranks, and it returns the top documents as links.

1 / 10

Deep dives

The ingestion pipeline

The index has to follow the documents, which are edited, moved and deleted all the time. Each source system sends change events to a connector, and the connector also crawls the source on a schedule to catch any events that were lost. Every change becomes a message on a queue, and workers process the messages in four steps.

  1. The worker fetches the document and extracts its text, including from PDFs and slides.
  2. The worker splits the text into chunks of about 500 tokens along the headings, with a little overlap between neighbours. It puts the document title and section heading at the top of each chunk so that it makes sense alone.
  3. The worker embeds, in batches, only the chunks whose hash is new. Most edits change only a few chunks.
  4. The worker writes the new and changed chunks to the index by doc_id and deletes the chunks that no longer exist.

Changing the embedding model or the chunking rules is a larger event, because the old and new vectors cannot be compared. The approach is to build a second index tagged with a new index_version and write every live change to both. When it is complete and checked against the evaluation set below, the answer service switches to it.

Chunking

Chunk size decides what retrieval can find. A chunk that is too small, such as one sentence, loses the context that makes it meaningful, and a chunk that is too large mixes several topics, so its vector matches none of them well and it spends prompt tokens on text that is not relevant. About 500 tokens is a common starting point, and the golden set below is used to compare sizes.

Fixed-size chunking cuts the text every N tokens with some overlap. It is simple and works for any format, but it cuts through sentences and tables, so a step of a procedure can be separated from the heading that explains it. Structure-aware chunking splits along headings, paragraphs, list items and table boundaries, and keeps each table or code block whole. It needs a parser for each format, but it produces chunks that can be read alone, so it is the better default for company documents.

Choosing the retrieval method

The retrieval step decides which 8 chunks the model sees, so it limits the quality of every answer. There are three options.

Vector search compares the embedding of the question with the embedding of each chunk and returns the nearest ones. It finds passages with the same meaning in different words, so "reset my login" matches a page about password recovery. Its weakness is exact terms: an embedding model gives an error code or ticket number little meaning, so such a query can return vaguely related chunks.

Keyword search scores chunks by the words they contain. It is excellent for exact identifiers, and it misses a passage that uses different words from the question. Company questions contain both exact terms and paraphrases, so neither method is enough alone.

Hybrid search runs both searches and merges the two ranked lists. A common way is reciprocal rank fusion, where each list gives a chunk 1 ÷ (60 + rank) points and the chunks are sorted by their total, so a chunk that both lists rank well comes first.

Hybrid search returns 50 candidates cheaply, but its order is approximate. A reranker is a model that reads the question and one candidate chunk together and gives a more accurate relevance score. It is too slow to run over millions of chunks, but it takes about 200 ms for 50 candidates. The 8 chunks it keeps are more relevant than the first 8 of the fused list, so the prompt can be shorter without losing the passage that answers the question.

Retrieval pipelines
OptionGood atBad atPick it when
Vector search onlyIt finds paraphrases with one fast query.It misses exact identifiers such as error codes or ticket numbers.Use it for prose with few special terms.
Hybrid searchIt catches meaning and exact terms at almost no extra latency.It has two scorers to tune.Use it when latency is tight.
Hybrid search plus reranker Usual defaultIt gives the best top 8 chunks.It adds about 200 ms and one more model to run.Use it when answers take seconds anyway.

This design uses hybrid search plus a reranker, because 200 ms is small next to the second the model needs to start answering.

Enforcing permissions

Text that the asker may not read must never reach the prompt, because anything in the prompt can appear in the answer. Every chunk therefore carries the groups allowed to read its document, copied from the source system, and the question is answered only from chunks that match the asker's groups. There are three places to apply that check.

Filtering after the search means searching everything and then dropping the chunks the user cannot read. It fails in practice: for someone in a small team, most of the top 50 results may be restricted, so few or none remain although readable documents exist.

Filtering inside the search applies the group condition as part of the query, so the engine returns the 50 best chunks among the readable ones. This is the choice for this design.

A separate index for each group gives strong isolation, but chunks readable by many groups are stored many times and a permission change means rewriting copies, so it suits only a few large, strictly separate tenants.

The filter is only as good as the permission data behind it, so three more rules apply. A permission change only has to update the allowed_groups field and does not need any embedding, which makes it cheap, so it runs on its own path and more often than content sync to meet the 5-minute target. The asker's groups come from the directory with a cache of about a minute, not from a login token that lives for hours. For highly sensitive sources such as HR and legal, the service also asks the source system at answer time whether the user can still open each cited document, which closes the gap before the next sync.

Caching and controlling cost

The cost is driven by the 900 million tokens a day. One way to reduce it is to send fewer and better chunks, since 6 chunks instead of 8 cut the prompt from 4,500 to 3,500 tokens. Another is to cache answers to repeated questions. The cache key must contain the normalized question and the asker's group set, because without the groups an answer built from restricted documents could be served to someone without access. An entry is evicted whenever a document it cites is changed or has its permissions changed.

Evaluating quality

The team builds a golden set of a few hundred real questions, each labelled with the documents that answer it, and scores every change against it before release (see evals). Three measurements matter.

  • Retrieval recall at 8 is how often a correct chunk is among the 8 sent to the model. When it is low, no prompt can rescue the answer, so this is checked first.
  • Faithfulness is whether every claim in the answer is supported by a cited chunk. A model can grade this at scale.
  • Correct refusals are measured with questions the documents cannot answer, scoring whether the system says it does not know.

Bottlenecks and failures

At 10 times the questions, about 200 a second at peak, the language model and the reranker run out of capacity first. The fixes are more model capacity, more caching and fewer tokens per question. At 10 times the documents, the vectors take 2 TB at 4 bytes per number, so the index is split into shards by chunk, the shards are queried in parallel, and the numbers are stored in 1 byte each.

Component that failsWhat happensWhat you do
The language modelNo generated answers can be produced.Return the reranked documents as search results with a notice.
The rerankerThe candidates arrive in the fused order.Send the top 8 fused chunks to the model, so quality drops a little but nothing breaks.
An index shardThe chunks on that shard are missing from the results.Keep replicas of every shard, and if one is lost, answer from the remaining shards and say so.
The ingestion pipelineThe index stops updating and answers grow stale.Keep changes on a durable queue and catch up later. Permission sync runs on its own path, so removed access still applies.
The directory that supplies group membershipThe service cannot tell which chunks the asker may read.Refuse to answer instead of searching without a filter, because a permission leak is worse than an outage.
A connector misses eventsSome edits never arrive.The scheduled crawl finds them.

What a strong answer sounds like

LevelWhat the answer does
JuniorThe candidate chunks documents, stores embeddings in a vector database and sends the top results to a model.
Mid-levelThe candidate also adds incremental ingestion, hybrid search, a reranker with a latency budget, and streamed answers with citations.
SeniorThe candidate filters permissions inside retrieval with a fast, separate permission sync, estimates cost in tokens, plans re-indexing, and measures quality before shipping.
Restricted documentsStrong answer
Interviewer

Some documents are visible only to HR. How do you handle that?

You

Every chunk carries the allowed groups of its document. Retrieval filters on the asker's groups inside the search, so restricted text never reaches the prompt. Permission changes sync on a fast path of its own, within 5 minutes.

Interviewer

And what happens during those 5 minutes?

You

For HR and legal documents, I would also ask the source system at answer time whether the person can still open each cited document.

Follow-up questions

How do you handle follow-up questions in a conversation?

The system rewrites the follow-up into a standalone question using the recent turns, so "And for production?" becomes "How do I rotate the production database password?", and retrieves with that. The raw follow-up has no topic words to match.

The answer is wrong but the right document exists. How do you debug it?

Start with retrieval. Check whether the right chunk was among the 50 candidates and among the final 8. If it was not, the problem is in chunking, search or ranking, and the fix is there. If it was, the problem is in the prompt or the model.

How do you reduce wrong answers that sound confident?

The prompt tells the model to answer only from the numbered chunks, to cite them, and to say it does not know when they do not contain the answer. The service can also refuse before calling the model when the best reranker score is below a threshold. The golden set includes questions that the documents cannot answer, so these refusals are measured instead of assumed.

Self-review: RAG system0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure