Design: enterprise knowledge assistant
Connectors sync documents and ACLs into a hybrid index; at query time, filter by the user's permissions, retrieve and rerank, then answer only from cited chunks, or abstain.
Fundamentals you'll use
How it works
- Size it: 50k employees, ~10M documents (~40M chunks), ~100k questions/day, first token in ~1 s.
- Normalize ACLs to principal IDs on a fast path (~1 min), and expand groups at query time.
- Search is hybrid because queries carry exact strings: BM25 catches ticket keys, dense vectors catch paraphrase.
- The worst failure is a permission leak: filter before retrieval, because the model cannot unread text.
- Test permissions with canary documents in CI; measure recall@50, nDCG@8 and groundedness on ~500 real queries.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your enterprise assistant stores, on every chunk, the expanded list of user IDs allowed to read it. A reorg moves 3,000 people between groups, and the ACL update job will take days over ~40M chunks. What should the design have been?
Go deeper
Full explanation
Requirements
Functional: answer questions over Confluence, Google Drive, Slack and Jira with citations; never surface content the user can't open in the source; support follow-ups. Non-functional: 50k employees, ~10M documents, first token in ~1 s (p95 under 2 s), revocations effective within minutes, deletions honored for legal reasons.
Questions I'd ask:
- How is each source's ACL modeled, and can a connector read it through the API?
- How fresh must answers be: minutes for Slack and Jira, hours for docs?
- Which file types and languages: scanned PDFs, slides, sheets?
- Answers only, or actions too, like creating a Jira ticket?
- May content go to an external model API, and in which region?
The highest-cost failure is a permission leak: an answer quoting the M&A deck or a salary sheet to someone who can't open it. A wrong answer is a bug; a leak is an incident.
High-level design
Offline: connectors pull content and ACLs through webhooks plus incremental crawls, with a nightly full reconcile. ACLs are normalized to principal IDs (users and groups) per document and synced on a faster path than content. Document ingestion & parsing respects structure (headings, slides, Slack threads); chunks of ~300–800 tokens get embeddings and BM25 terms and are stored with ACL and freshness metadata in one hybrid index.
Online: SSO identifies the user, whose groups are expanded and cached ~5 min; Query transformation (rewrite, HyDE) rewrites follow-ups into standalone queries; Hybrid search & RRF runs with a permission pre-filter built from identity (top 50); Reranking (cross-encoders) keeps 8; the LLM answers only from those chunks with numbered citations, or abstains and shows links when evidence is weak. The mechanism is Metadata filters & permission-aware retrieval.
Code Permission pre-filter inside hybrid search (Qdrant)
from qdrant_client import QdrantClient, models
client = QdrantClient(url=QDRANT_URL)
def retrieve(user_id: str, query: str, k: int = 50, keep: int = 8):
# Principals come from the identity provider, never from the prompt or the model
principals = principal_cache.get(user_id) or expand_groups(user_id) # ~5 min TTL
acl = models.Filter(
must=[models.FieldCondition(key="allowed_principals", match=models.MatchAny(any=principals))],
must_not=[models.FieldCondition(key="tombstoned", match=models.MatchValue(value=True))],
)
# Dense + sparse, both pre-filtered, fused with RRF
hits = client.query_points(
collection_name="chunks",
prefetch=[
models.Prefetch(query=embed(query), using="dense", filter=acl, limit=k),
models.Prefetch(query=bm25_vector(query), using="sparse", filter=acl, limit=k),
],
query=models.FusionQuery(fusion=models.Fusion.RRF),
limit=k,
).points
top = rerank(query, hits, keep=keep)
# The index's ACL copy can lag: re-check the few chunks that reach the prompt
return [h for h in top if acl_store.can_read(user_id, h.payload["doc_id"])]Real example
Priya in Finance asks "What's the per diem for a trip to Brazil?". SSO resolves her to 1 user and 42 groups (cache hit, ~5 ms). There is no history, so the query passes through unchanged. Hybrid search over ~40M chunks, pre-filtered to what she can read, returns 50 candidates in ~120 ms; the reranker (~100 ms) keeps 8: the 2025 travel policy (Drive), a Confluence FAQ and a #finance Slack thread. The live ACL check drops one Drive chunk whose share was revoked 2 minutes ago. The model reads ~4k tokens of context and streams the first token at ~1 s: "BRL 350 per day [1]; [3] notes an exception for São Paulo." Every sentence maps to a cited chunk.
Trade-offs +4 · −4
+ You gain
- Permissions are enforced in code inside retrieval, so the model never sees what the user can't open.
- Hybrid search plus rerank handles exact identifiers (ticket keys, codenames) and paraphrased questions alike.
- Citations and abstention make wrong answers rarer and checkable, which is what earns trust internally.
- Query-time group expansion: a reorg touches one cache entry, not millions of chunks.
− You pay
- Connectors are the real ongoing cost: four APIs, four permission models, rate limits and dropped webhooks.
- Revocation is only as fast as ACL sync; closing the gap with live source checks costs latency and API quota.
- A 40M-chunk hybrid index, re-embedded on every model change, is a large stateful system to operate.
- Abstention lowers the answer rate, and users read it as "the bot doesn't know" even when it is right.
Use it when
Internal Q&A across several SaaS sources with real permission boundaries, a corpus that changes daily, and answers people must be able to check.
Avoid it when
One small, uniformly public corpus (a docs site under ~1k pages fits plain RAG or even long context), or when the job is actions rather than answers.
Numbers to know 5
- Corpus: 10M docs × ~4 chunks (assumed) = 40M chunks; 1,024-dim float32 ≈ 164 GB of vectors, ~41 GB at int8.
- Load: 50k employees × 40% daily active × 5 questions = 100k/day ≈ 3.5 QPS over 8 working hours, ~7 at a 2× peak.
- LLM: 100k × (5k in + 400 out) = 0.5B in + 40M out tokens/day ≈ $2.1k/day at an assumed $3/$15 per M; ~$260 at $0.40/$1.60.
- First token: groups 20 ms (cached) + hybrid 120 ms + rerank 100 ms + prefill and queue ~700 ms ≈ 1 s.
- Full re-embed: 40M × 500 tokens = 20B tokens ≈ $400 at $0.02 per M; the real cost is the dual-index migration.
Common pitfalls 4
- Post-filtering by permission: search, then drop forbidden hits. A user who can read 1% of the corpus keeps ~1 of 100 results. Pre-filter inside the search.
- Indexing "anyone in the domain with the link" files for everyone: link access never meant discoverability. Restrict them to explicit viewers unless the owner opts in.
- Deleted content that keeps answering: an HR policy removed at the source still cited a week later. Tombstone on the delete event, then purge index, caches and logs.
- Unverified citations: a fabricated
[3]looks authoritative. Validate every index, and check support on a sample, or on all answers in HR and legal spaces.
Interview questions 3
Answer out loud first, then reveal.
Someone was removed from a private Slack channel 10 minutes ago. Can they still get its content?Show answer
I'd state the bound rather than claim zero. The membership event reaches the ACL store by webhook in about a minute; with the 5-minute group cache, the worst case is about 6 minutes, and the nightly reconcile catches dropped events. For private channels and HR spaces, the final check on the 8 chunks bypasses the cache, and for the most sensitive sources it asks the source API, adding ~100–300 ms. Zero-lag revocation on every candidate would blow the source APIs' rate limits.
How do you know the assistant is getting better, not just different?Show answer
I keep retrieval and generation scores separate, so a gain in one can't hide a regression in the other. Every change to chunking, embeddings, prompt or model runs in CI against the golden set: recall@50, nDCG@8, groundedness, citation precision and abstention accuracy, sliced by source. The permission canaries are pass/fail with zero tolerance. Online, I A/B test on thumbs-down rate and citation clicks, and the eval set grows every week from the worst production traces.
Why not give the model a search tool and let it agent its way through?Show answer
Because most questions are single-hop, and a fixed pipeline gives me predictable latency, about a second to first token, and one place to enforce permissions. An agent loop adds 2–5 LLM calls per question and new ways to fail. I'd add an agentic route only for the slice that needs it, like comparisons and multi-hop questions, once error analysis shows it is over ~10–15% of failures. Permissions don't change either way: the search tool applies the identity filter, not the model.
Deep dive 5
Connectors, ACLs and freshness
Each source has its own permission model: Confluence space permissions and page restrictions, Drive sharing (users, groups, domain-wide links), Slack public and private channels, Jira project roles and issue security levels. Normalize them all to a list of principal IDs per document, and expand groups at query time rather than writing members into every chunk: a reorg then updates one group cache instead of millions of chunks. Give ACLs their own fast path: webhooks land in an authoritative ACL store within ~1 minute, the index copy follows asynchronously, and a nightly full reconcile catches dropped events. A deletion writes a tombstone that filters instantly; hard deletes from index, caches and logs follow. Most companies exclude DMs entirely.
Parsing, chunking and hybrid retrieval
Chunk by structure: pages and docs by heading, slides one per chunk, sheets as row groups with headers repeated, Slack per thread (one message is too little context), Jira as summary + description + latest comments. Aim for ~300–800 tokens and prepend title and path (Contextual retrieval). Retrieval is hybrid because enterprise queries are full of exact strings: BM25 catches ticket keys (PAY-1234), codenames and acronyms that embeddings blur, while dense vectors catch paraphrase. Fuse with RRF, take 50 under the permission pre-filter, rerank to 8. Boost recency and authority, so an approved policy page outranks a two-year-old Slack guess.
Answers, citations and abstention
The prompt numbers each chunk with title, source, author and date, and says: answer only from these sources, cite [n] after each claim, say what is missing. After generation, verify that every cited index exists and, for high-risk spaces such as HR and legal, run an entailment check that the chunk supports the sentence (Citations & grounding). Abstain when the top rerank score is below a tuned threshold, and show the 3 best links instead of a guess. When sources conflict, prefer the newest authoritative one and say that they conflict. The model never sees chunks outside the filtered set: you cannot ask it to ignore text it already read.
Evaluation
Measure retrieval and answers separately. Retrieval: ~500 real queries sampled from logs, with relevant documents labeled by domain experts; track recall@50 and nDCG@8, sliced by source and department. Answers: correctness against references, groundedness, citation precision and abstention quality, counting both wrong abstains and answers that should have abstained (Evaluating RAG). Permissions are tested deterministically, not sampled: synthetic users with known groups query planted canary documents, and any canary in a response fails the build. Online: thumbs-down rate, citation click-through, no-answer rate per source, and a weekly Error analysis: look at your data of the 50 worst traces.
Scale, latency and cost
Assume ~4 chunks per document: 40M chunks. At 1,024 dimensions in float32 that is ~164 GB of vectors (~41 GB with int8 quantization) plus the BM25 index: a sharded cluster with replicas. Query load is modest: ~100k questions/day, ~7 QPS at peak. The first-token budget is ~1 s: groups 20 ms, hybrid search 120 ms, rerank 100 ms, prefill and queueing ~700 ms. The LLM dominates cost, so route easy lookups to a small model (Model routing & cascades) and cache the instruction prefix. The hidden bill is changing the embedding model: re-embedding 40M chunks and running two indexes during the cutover (Index freshness & lifecycle).