Design a Retrieval-Augmented Chatbot with Access Control
System DesignModel answerLast updated
Build a chatbot that answers employee questions from internal docs while enforcing document-level permissions and maintaining response quality.
You're building a conversational assistant that lets employees ask questions about company knowledge—product documentation, internal policies, engineering runbooks, and compliance materials. The assistant must generate answers grounded in these documents, respect who can see what, and handle thousands of concurrent users without degrading performance.
What the System Must Do
Core Capabilities
- Accept natural language questions and return synthesized answers backed by real documents
- Show which documents were used to form each answer
- Remember earlier turns in a conversation so follow-up questions make sense
Performance and Scale
- Serve a user base of 10,000 employees with peaks during business hours
- Keep median response time under 2 seconds from question to first visible token
- Scale to 100,000 users without fundamental redesign
Security and Compliance
- Honor existing access controls: if a user cannot open a document in the source system, they must not receive answers derived from it
- Prevent information leakage through conversation history or caching
What You Should Provide
- Architecture overview — describe the main components, data flow, and how they interact (text description is fine; a diagram is not required)
- Storage approach — explain how you store documents, vector representations, metadata, and conversation state
- Permission enforcement strategy — detail how you ensure users see only what they're authorized to see, and where in the pipeline you enforce this
- Answer quality controls — describe techniques to keep answers accurate and grounded in real content rather than model confabulation
Assume the company uses standard identity providers (OIDC or SAML) and document repositories like Confluence, SharePoint, or object storage with associated permission metadata.
Hints
Hint 1
Start by estimating queries per second under realistic load patterns—clarifying scale shapes every other decision
Hint 2
Pre-filtering at retrieval time is fundamentally different from post-filtering results; consider which approach protects both performance and security
Hint 3
Think through what happens when a document's permissions change after it has been embedded and indexed
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Retrieval-Augmented Chatbot with Access Control
1. Scope and Capacity Planning
Begin by translating user counts into concrete load.
Request Volume
- 10,000 employees × 15–25 queries per day = roughly 150K–250K daily queries
- Average load: ~2–3 queries/second
- Business-hour concentration means 10–15× peak, so design for 30–50 QPS sustained
- Headroom target: support 100K users (~300–500 QPS) without architectural changes
Document Corpus
- Estimate 3–8 million documents across all sources
- Each document splits into ~8–12 retrievable chunks (paragraphs, sections)
- Total: 30–100 million chunks to search
- With 768- or 1024-dimensional embeddings at 4 bytes per dimension, raw storage is 100–400 GB; quantization reduces this 4–8×
Latency Breakdown
- Authentication and permission lookup: 30–80 ms
- Semantic search across embeddings: 100–200 ms
- Reranking top candidates: 100–200 ms
- Language model first token: 500–1000 ms depending on model size and concurrency
- Target p95 end-to-end: under 2 seconds to first token, with the rest streamed
Ask clarifying questions: which source systems hold documents? How are permissions represented—group memberships, role attributes, direct grants? What freshness is acceptable (real-time, minutes, hours)? Any regulatory data residency requirements?
2. High-Level Architecture
User → API Gateway (auth, rate limits) → Orchestration Service
↓
┌──────────────────┼──────────────────┐
↓ ↓ ↓
Permission Cache Retrieval Engine Conversation Store
(Redis/Memcached) (vector + keyword) (DynamoDB/Postgres)
↓
Reranking + LLM
↓
Response (streamed)
Ingestion Pipeline (async):
Source Systems → Change Detection → Chunking + Embedding (GPU batch)
↓
Vector Index + Metadata DB
Orchestration Service (stateless, horizontally scaled)
- Loads recent conversation turns from storage
- Resolves the user's permission set (groups, roles) from a cached identity service
- Rewrites the query if needed using conversation context
- Runs retrieval with permission filters applied
- Assembles a prompt with retrieved chunks and instructions to cite sources
- Streams the language model response back to the client
- Validates citations and logs the interaction
Retrieval Engine
- Combines vector similarity (semantic) and keyword matching (lexical/BM25) for hybrid search
- Applies access control filters directly in the search layer
- Returns top 30–50 candidates
Reranking
- Uses a cross-encoder model to score query-chunk relevance more accurately than cosine similarity alone
- Narrows results to the top 5–10 chunks for inclusion in the LLM prompt
Ingestion Pipeline
- Connectors poll or receive webhooks from source systems
- Each document is parsed, split into chunks, and embedded using a batch embedding service
- Chunks are indexed with their text, vector, parent document metadata, and allowed_principals list
- A separate reconciliation job runs periodically to catch missed updates
3. Storage Strategy
| Data Type | Storage | Rationale |
|---|---|---|
| Raw documents | Object storage (S3, GCS) with versioning | Immutable, encrypted at rest, supports audit trails |
| Document metadata | Relational DB (Postgres) or NoSQL (DynamoDB) | doc_id, source_system, version, content_hash, ACL principals, last_modified |
| Chunk embeddings + text | Vector database (Pinecone, Weaviate) or search engine (Elasticsearch, OpenSearch) with vector plugin | Must support filtered ANN search; storing text alongside vectors enables hybrid retrieval in one system |
| Conversation history | NoSQL with TTL (DynamoDB) | Partitioned by user_id; each turn includes query, answer, and cited chunk IDs; automatically expire old conversations |
| Permission cache | In-memory cache (Redis) | Flattened user → group memberships; TTL 5–10 minutes to balance freshness and load on identity provider |
Why precompute embeddings? Embedding millions of chunks at query time is infeasible. Precomputation trades ingestion cost and slight staleness (seconds to minutes) for fast retrieval. Track content hashes to detect updates and re-embed only changed chunks.
4. Access Control Enforcement
This is the critical design decision. The goal: users must never receive answers derived from documents they cannot access.
Pre-filter at Retrieval Time
Store an allowed_principals field with every chunk—a list of group IDs, role names, or individual user IDs that grant access. At query time, resolve the requesting user's full group membership (including transitive groups) and pass this set as a filter parameter to the vector search. The search engine returns only chunks where the user's principals intersect with allowed_principals.
Why pre-filter beats post-filter:
- Post-filtering can return too few results if most top matches are forbidden, degrading answer quality
- Forbidden content never enters downstream components (LLM prompt, logs, caches), reducing leakage surface area
- Performance: filtering inside the index is faster than fetching and discarding results in application code
Handling Permission Changes
When a document's ACL changes:
- Update the
allowed_principalsfield on all associated chunks without re-embedding (metadata-only update) - Prioritize revocations in the update queue for immediate effect
- Invalidate any cached responses tied to those chunks
For users in hundreds of groups, consider:
- Bitmap encoding of principals to accelerate set intersection
- Tiered indexing by sensitivity level, so high-security documents live in a separate index shard with stricter controls
Defense in Depth
- Re-verify access to cited documents against the authoritative source (or the metadata DB) before returning citations to the user
- Never share answer caches across users; include a permission fingerprint in cache keys
- Audit log every query with user ID, retrieved chunk IDs, and final citations for compliance review
Conversation Sharing
If users share conversation links, re-run retrieval under the viewer's permissions. Do not reuse answers generated for someone with different access.
5. Answer Quality and Hallucination Mitigation
Retrieval Quality
- Hybrid search: vector embeddings capture semantic similarity, BM25 keyword search catches exact terminology (product names, policy numbers, acronyms)
- Cross-encoder reranking: a second model scores query-chunk pairs more accurately than dot product, improving the final 5–10 chunks sent to the LLM
- Structure-aware chunking: keep section headers with their content; keep table rows together; preserve code blocks
Prompt Engineering
- Instruct the model to answer only using the provided chunks
- Require inline citations in the format
[chunk_3]after each claim - Explicitly instruct the model to respond "I couldn't find information on that" when the context is insufficient rather than guessing
Confidence Thresholds
If the top reranked chunk scores below a calibrated threshold, skip generation entirely and return "no confident answer found" along with the closest document titles. This prevents low-quality guesses when retrieval fails.
Citation Validation
After generation:
- Strip or flag any citation whose chunk ID was not present in the prompt
- Optionally run a secondary model to check whether the answer is entailed by the cited text (NLI-based groundedness check); run this asynchronously for a sample of queries to protect latency, or inline for high-stakes domains
Numeric and Financial Data
For questions involving figures, prefer surfacing exact table rows or extracted structured data rather than letting the model paraphrase numbers. Show direct quotations with clear attribution.
Freshness Indicators
Display each document's last-modified timestamp in citations. Boost recent versions in ranking and exclude explicitly superseded documents from search.
6. Scaling and Operational Considerations
Horizontal Scaling
The orchestration service is stateless and scales behind a load balancer. The vector index and reranking service scale by sharding (partition by document set or by user tier) and replication.
Language Model Capacity
Use provisioned throughput (e.g., AWS Bedrock, Azure OpenAI) to guarantee low latency. Under extreme load, fall back to a smaller, faster model or queue requests with estimated wait times.
Long-Running Queries
Some questions—"summarize every product launch document from Q3"—require scanning hundreds of documents and cannot meet the 2-second target. Detect these with a query classifier or explicit user scope selection, enqueue a background job, and return a job ID. Workers process each document under the user's ACL, then merge results. Notify the user when complete.
Monitoring
Track p50/p95/p99 latency for each stage (retrieval, rerank, LLM first token). Alert on permission cache miss rate, failed citation validation rate, and user-reported feedback (thumbs down). Trace every request with a correlation ID for debugging.
7. Key Trade-offs
| Decision | Trade-off |
|---|---|
| Pre-filter ACLs in retrieval | Correctness + security vs. slightly higher indexing complexity |
| Hybrid search (vector + keyword) | Better recall on exact terms vs. maintaining two indexes |
| Cross-encoder reranking | Significantly better relevance vs. 100–200 ms added latency |
| Precomputed embeddings | Fast queries vs. seconds-to-minutes staleness on updates |
| Streaming responses | Perceived speed vs. cannot validate full answer before showing it |
| Calibrated abstention | Fewer hallucinations vs. some questions go unanswered |
Common Mistakes
- Post-filtering after retrieval: allows forbidden content into logs, caches, and the LLM context
- Ignoring permission changes: cached embeddings with stale ACLs leak revoked access
- No reranking: cosine similarity alone produces mediocre top results; reranking is worth the latency cost
- Unlimited context to LLM: dumping 50 chunks into the prompt wastes tokens and dilutes signal; rerank down to 5–10
- Assuming 2 seconds means full answer: clarify whether this is time-to-first-token or full generation; 300 tokens cannot reliably generate end-to-end in 2 seconds on shared infrastructure
This design balances security, accuracy, and performance for a production-grade retrieval-augmented system.