SYSTEM DESIGN · DESIGN PROBLEMS · AI SYSTEMS · MEDIUM · 53 OF 57

Design a RAG Chatbot over Company Documents: Ingestion, Permissions, Citations and Evals

An internal assistant that answers from wikis, PDFs, tickets and drives with citations: connectors and change detection, chunking math for 5 million documents, permissions enforced inside retrieval, hybrid search and reranking, saying I do not know, freshness, tenant isolation, evals, time to first token and cost.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
1 / 22

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • 30M chunks
  • ACL filter inside retrieval
  • hybrid search + rerank
  • cite or refuse
  • evals on every change

Notes

Listen

Listen first. Employees ask questions in a chat thread, with follow-ups. Answers come from wiki pages, PDFs, tickets and shared drives, and every answer cites its sources with links. The assistant may only use documents the asker could open in the source system, and it should say it does not know rather than guess. Users rate answers, and admins connect new sources.

The qualities. Permission leaks are the worst failure, so access checks must be exact, and a revoked share must stop working within minutes. Edits should be searchable within about fifteen minutes. The first token should stream in under two seconds. We sell this to many companies, so tenants are fully isolated. Out of scope: taking actions, understanding images, and training our own model.

Functional
  • ask questions in a chat thread with follow-ups
  • sources: wiki, PDFs, tickets, shared drives
  • every answer cites its sources
  • only use docs the asker can open
  • say "I don't know" when unsure
  • thumbs up or down per answer
  • admins connect sources
Non-functional + scope
  • no leaks: permissions exact, revocations within minutes
  • fresh: edits searchable in under 15 minutes
  • first token under 2 s
  • many customer companies: tenants fully isolated
  • out: actions like filing a ticket, image understanding, training our own model

Ask scale

Ask about scale. The largest tenant has five million documents averaging three thousand tokens, fifteen billion tokens. Cut into chunks of about five hundred tokens with some overlap, that is thirty million chunks. At a thousand twenty four dimensions in four-byte floats, vectors take a hundred twenty gigabytes, or thirty quantized to one byte. Embedding everything once costs a few hundred dollars and takes about two days, so a full re-embed is affordable but slow.

Now the query side. A hundred thousand employees, thirty percent asking five questions a day, is a hundred fifty thousand questions, about five a second in work hours and fifteen at peak. That is tiny for servers. The real costs are tokens: about six thousand in and four hundred out per answer, roughly three cents on a frontier model, so forty five hundred dollars a day. Cost and latency, not QPS, drive this design.

Corpus math (largest tenant)
5M docs × ~3,000 tokens avg
  = 15B tokens
chunks of ~500 tokens + overlap
  ≈ 30M chunks
vectors: 1,024 dims × 4 B = 4 KB
  30M × 4 KB ≈ 120 GB (+ graph)
  int8 quantized ≈ 30 GB
chunk text ≈ 60 GB
full embed: 15B tokens
  ≈ $300 at $0.02 per 1M
  ≈ 2 days at 5M tokens/min
Query + cost math
100k employees, 30% daily
  × 5 questions = 150k/day
  over 8 work hours ≈ 5 q/s
  peak ≈ 15 q/s
prompt ≈ 6k tokens in:
  1k system + history, 4k docs
  ≈ 400 tokens out
frontier: 6k × $3/1M ≈ 1.8¢
  + 400 × $15/1M ≈ 0.6¢
  ≈ 3¢ per question
  ≈ $4,500 per day

Define API

Define the API. Posting a message to a conversation returns a server-sent event stream: tokens as they are generated, then the citations, then a done event with the message id. A feedback call records thumbs up or down with a comment. Admins create connectors with a scope and a reference to stored credentials, and check sync status. Source systems push change events to a webhook endpoint.

API
POST /v1/conversations/{id}/messages
  { text } → SSE stream:
  token… citations… done
POST /v1/messages/{id}/feedback
  { rating, comment }
POST /v1/connectors
  { type, scope, secret_ref }
GET  /v1/connectors/{id}/status
POST /v1/hooks/{connector}
  change events from sources

Data model

The data model. Postgres holds one row per document: tenant, source, URL, title, a content hash, the list of users and groups allowed to read it, and a deleted marker. Raw files sit in object storage. The search index holds chunks: text, vector, section heading, a hash, and a copy of the document's allowed principals so retrieval can filter on them. Messages store the cited chunk ids and a trace id.

Data model
documents (Postgres)
  tenant_id, doc_id PK, source,
  url, title, content_hash,
  acl_principals[], deleted_at
chunks (search index)
  chunk_id, tenant_id, doc_id,
  text, vector, section, hash,
  acl_principals[] (copied)
messages
  conv_id, role, text,
  cited_chunk_ids, trace_id

High-level design

Draw the ingestion path first. Connectors watch each source system, by webhook where it exists and by polling for changes otherwise, and put change events on Kafka. Ingestion workers fetch the document and its permissions, store the raw file and metadata, parse it, split it into chunks, embed the chunks, and upsert them into the search index. Everything is asynchronous and retryable.

Now the query path. The orchestrator resolves the user to their groups, rewrites the question if it is a follow-up, and asks the hybrid retriever for chunks the user is allowed to see. The retriever runs keyword and vector search together, a reranker picks the best eight, and the orchestrator sends the question and those chunks to the model, streaming tokens back to the browser.

Deep dive: ingestion

Deep dive one: ingestion. Change detection has three layers. Webhooks give near real-time updates, but events get dropped. So connectors also poll every few minutes with a change cursor, and a weekly full listing is diffed against our document table to catch anything missed, especially deletes. Hash each document and skip unchanged ones, then hash each chunk and re-embed only chunks that changed. Respect each source's rate limits with backoff.

Parsing and chunking decide answer quality more than the model does. Turn wiki HTML into headings and text, read the PDF text layer and fall back to OCR for scans, and keep tables as rows. Split on headings into chunks of three to eight hundred tokens with a little overlap. Prefix each chunk with its document title and section path, so a lone paragraph still says what it is about. A deleted document is tombstoned, its chunks removed and its raw file purged.

Finding changes
  • webhook: near real time, but events get lost
  • delta poll every 5-10 min with a change cursor
  • weekly full listing diff: catches missed deletes
  • hash the doc: same? skip
  • hash each chunk: re-embed only the changed ones
  • per-source rate limits + backoff (APIs throttle)
Parse and chunk
  • wiki: HTML → headings + text
  • PDF: text layer; OCR if scan; keep tables as rows
  • ticket: one doc per thread, resolution weighted
  • split on headings, 300-800 tokens, ~10% overlap
  • prefix: "HR Handbook > Leave > Contractors"
  • deletes: tombstone doc, drop its chunks, purge raw file

Deep dive: permissions

Deep dive two: access control, the part that gets companies in trouble. The naive design searches everything and filters out forbidden results afterwards. If the filter has a bug, the salary review deck goes straight into the prompt, and the model happily summarises it. Even when it works, post-filtering is weak: if forty-five of the top fifty hits are forbidden, the user gets five weak results. Permissions must be part of the search itself.

Store the document's allowed groups and users on each chunk, and expand the asker's group memberships at query time from a cached identity lookup. Then every search, keyword and vector, carries a mandatory filter: this tenant, and principals overlapping mine. Because chunks store groups, not expanded people, joining a group needs no re-index. A share change only rewrites the permission field, never the embedding. As defence in depth, re-check the final eight chunks against the doc store before prompting.

Keeping permissions in sync is its own pipeline. Permission events jump ahead of content events, since a revocation matters more than a typo fix. A folder share change can touch a hundred thousand documents, so it becomes a bulk metadata update. Group memberships are cached for a few minutes, and revocation events evict immediately. If a document's permissions cannot be read, it is invisible: fail closed. Anyone-with-the-link shares count as private. And never share cached answers between users.

Permission-aware retrieval
  • each chunk stores its doc's allowed groups and users
  • query: tenant = T AND principals ∩ my 180 groups
  • filter inside the vector search (filtered HNSW), not after it
  • share change → rewrite the ACL field only, no re-embed
  • final 8 → re-check live ACL
ACL sync rules
  • ACL events go on a priority queue ahead of content
  • folder share change: 100k docs → bulk metadata update
  • group cache TTL ~5 min; revocation events evict now
  • unknown ACL → doc invisible (fail closed)
  • "anyone with link" → private
  • answer cache keyed by user, never shared across users

Deep dive: query path

Deep dive three: the query path. A follow-up like what about contractors means nothing alone, so a small fast model rewrites it into a standalone question using the chat history. Then run keyword search and vector search in parallel. Keywords catch ticket numbers, error codes and product names that embeddings blur; vectors catch paraphrases. Merge the lists with reciprocal rank fusion, and a cross-encoder reranker scores each candidate against the question to keep the best eight.

Assemble the prompt against a fixed budget: rules, a summary of older turns instead of the whole history, eight chunks of about five hundred tokens, and the question. Number each chunk and tell the model to answer only from them and cite the number after each claim. Afterwards, drop any citation that does not match a provided chunk, and link the rest to the document and section. If even the best rerank score is low, skip the model and say you could not find it, with the closest documents.

The latency budget for the first token. The cached group lookup is twenty milliseconds. The rewrite is three hundred, and skipped when there is no history. Embedding the query and running both searches in parallel is about a hundred twenty. Reranking is a hundred fifty. The model's prefill on six thousand tokens is roughly seven hundred, helped by caching the fixed system prompt prefix. That is about 1.3 seconds, then tokens stream over server-sent events.

Retrieval steps
  • rewrite: "what about contractors?" → full query (small fast model)
  • keyword: ticket ids, error codes, product names
  • vector: paraphrases
  • fuse with reciprocal rank
  • rerank 80 → 8 with a cross-encoder (~150 ms)
Context + citations
budget (of 6k input tokens):
  system + rules      800
  history summary     700
  8 chunks × ~500   4,000
  question            100
chunks numbered [1]..[8]
rule: answer only from sources,
  cite [n] after each claim
drop citations not in the set
top rerank score < 0.3 → skip
  the model: "I couldn't find…"
Time to first token
auth + groups (cached)    20 ms
rewrite (small model)    300 ms
  skip on the first turn
embed query               40 ms
BM25 ∥ vector search      80 ms
rerank 80 candidates     150 ms
build prompt              10 ms
model prefill, 6k tok    700 ms
  cached prefix helps
total ≈ 1.3 s → stream SSE

Deep dive: evaluation

Deep dive four: evaluation. Build a golden set of a few hundred real questions, each labelled with the documents that answer it. Measure retrieval alone with recall at eight: is the right document in the context? Then faithfulness: is every claim supported by the chunk it cites? A judge model scores that, calibrated against human labels. Run this on every change to chunking, embeddings, prompts or models. Online, track thumbs, citation clicks and no-answer rates, and turn bad answers into new golden questions.

Evals and feedback loop
  • golden set: 500 questions with the right source docs
  • retrieval: recall@8, MRR
  • faithful: each claim backed by its cited chunk (judge model, checked by humans)
  • also: refusal correctness
  • online: thumbs, citation clicks, "no answer" rate
  • bad answers → review queue → new golden questions

Deep dive: tenancy

Tenancy and safety. A large tenant gets its own index shard; small tenants share one with a tenant filter the retriever adds itself, never the caller. Use per-tenant encryption keys, key every cache by tenant, and lock down traces, because they contain document text. Documents are untrusted input: a wiki page can say ignore your instructions. Delimit sources in the prompt, give the model no tools with side effects, and strip external image links so an answer cannot leak data through a URL.

Tenancy and safety
  • big tenant: own index shard
  • small tenants: shared index, mandatory tenant filter
  • per-tenant encryption keys
  • caches and traces keyed by tenant; traces access-locked
  • no training on customer data
  • docs may hold injected instructions: delimit them, no side-effect tools, strip external image links

Trade-offs

Review the trade-offs. Bigger chunks carry more context but blur retrieval. Reranking costs a hundred fifty milliseconds and is usually the cheapest big quality win. Routing easy questions to a small model cuts cost around tenfold. Changing the embedding model means re-embedding everything into a new index and swapping over, because vectors from different models do not mix. If the model API fails, fall back to a second provider. If retrieval fails, say so instead of answering from the model's memory.

Trade-offs and failures
  • bigger chunks: more context, fewer, blurrier hits
  • rerank: +150 ms, big recall win
  • small model for easy questions: ~10x cheaper, route by intent
  • new embedding model: re-embed all, blue-green index swap
  • model API down → second provider, same prompt
  • index down → say so, never answer from memory

Interview summary

The thirty-second summary. Five million documents become thirty million chunks and about a hundred twenty gigabytes of vectors. Peak load is fifteen questions a second at about three cents each. Ingest with webhooks, polling and a full diff, hashing to skip unchanged content. Put permissions on every chunk and filter inside the search. Rewrite, run hybrid search, rerank to eight, answer with citations or say you do not know, and prove it with recall and faithfulness evals.

Interview summary
  • 5M docs → 30M chunks, 120 GB
  • 15 q/s peak, ~3¢ per answer
  • ingest: webhooks + polling + full diff, hash to skip
  • chunk by headings, add titles
  • ACL principals on each chunk, filter inside the search
  • rewrite → hybrid → rerank 8
  • cite or say "I don't know"
  • evals: recall@8, faithfulness

Interview questions

Q1Why not just put all the documents in a long context window instead of retrieving?

Fifteen billion tokens will never fit, and even a large slice would cost dollars and many seconds per question while ignoring permissions. Retrieval narrows it to a few thousand tokens the user is allowed to see, which is cheaper, faster and auditable through citations.

Q2How do you enforce document permissions in a vector search?

Copy each document's allowed users and groups onto its chunks, expand the asker's groups at query time, and apply a mandatory tenant and principal filter inside both the keyword and vector search, then re-check the final chunks against the live ACL before building the prompt. Fail closed when an ACL is unknown.

Q3A folder is unshared from a team. How quickly does the bot stop using it, and how?

The connector receives or polls the permission change and puts it on a priority queue; workers bulk-update the ACL field on affected chunks without re-embedding, and group caches are evicted, so it takes effect within minutes. The final live ACL re-check covers the gap.

Q4Why hybrid search instead of only embeddings?

Embeddings are good at paraphrases but blur exact tokens such as ticket numbers, error codes, acronyms and product names. BM25 catches those. Running both and merging with reciprocal rank fusion gives better recall than either alone, and a reranker then fixes the ordering.

Q5How do you choose the chunk size?

Split on document structure such as headings, target a few hundred tokens with a little overlap, and prefix each chunk with its title and section path. Then tune size against retrieval recall on a golden set rather than by intuition.

Q6How does the bot decide to say it does not know?

If the best reranker score is below a calibrated threshold, skip generation and say nothing relevant was found, showing the closest documents. Otherwise the prompt instructs the model to answer only from the numbered sources and to say so when they do not contain the answer.

Q7How do you evaluate a RAG system?

Separate retrieval from generation. Measure recall at k and MRR against a labelled golden set, then faithfulness and citation accuracy with a judge model calibrated against human labels, plus refusal correctness. Run it offline on every change and watch online signals like thumbs, citation clicks and no-answer rate.

Q8What happens when you switch to a new embedding model?

Vectors from different models live in different spaces, so you re-embed the whole corpus into a new index in the background, validate recall on the golden set, then switch reads over and delete the old index. For 15 billion tokens that is a few hundred dollars and about two days.

Q9How do you defend against prompt injection inside documents?

Treat retrieved text as data: delimit it clearly, give the model no tools with side effects, never let a document widen what the user can see, and sanitize output such as external image links that could exfiltrate data. Log and review suspicious documents.

Q10How would you cut the cost per question?

Route simple questions to a small model, cache the fixed system prompt prefix, keep the context budget tight with reranking to fewer chunks, summarize old chat turns, and cache embeddings and per-user answers for repeated questions within a short window.