A company docs Q&A assistant answers employees' questions using the company's internal documents. An employee asks a question in plain language and receives a short answer with citations linking to the original sources.
Examples: Glean, Microsoft 365 Copilot, Atlassian Rovo, Slack AI
Most companies spread their knowledge across several tools. The onboarding guide might live in Confluence, the travel policy in a Google Drive PDF, and the fix for a recurring deployment error in an old Jira ticket. Even a simple question like "Which team owns the billing service?" might have its answer buried in a Slack thread. Finding that answer often means searching several places or asking a colleague.
In this chapter, we'll design an assistant that brings this information together. We'll start with the requirements and high-level architecture, then look closely at access control, incremental updates and deletes, retrieval quality, grounded answers, citations, and evaluation.
Let's begin by clarifying what the system needs to do.
"Design a Q&A assistant over company documents" leaves several questions open. Which sources should it search? How quickly should changes appear? And how do we make sure employees only see information they're allowed to access?
Here's how that discussion might unfold in an interview:
Candidate: "Which sources should the assistant cover? Each has its own API, change notifications, and permission model."
Interviewer: "Confluence, Google Drive, SharePoint, Jira, and public Slack channels."
Candidate: "How many employees and documents should we design for?"
Interviewer: "About 100,000 employees and 10 million documents."
Candidate: "Do employees have different levels of access?"
Interviewer: "Yes. The assistant must respect each source's permissions."
Candidate: "How quickly should content and permission changes take effect?"
Interviewer: "Content edits should appear within 15 minutes. Permission removals need to take effect within 5 minutes."
Candidate: "Should employees be able to ask follow-up questions?"
Interviewer: "Yes, within the same conversation."
Candidate: "Can the assistant take actions, such as filing a ticket?"
Interviewer: "No. It's read-only."
Candidate: "Can we send document content to a hosted model provider?"
Interviewer: "Yes, under an enterprise agreement with zero data retention."
These answers give us enough scope to define the functional and non-functional requirements.
Actions such as filing tickets, image understanding beyond text extraction, and answering external customers are out of scope.
One requirement needs an explicit distinction. A 5-minute revocation target allows a short period when local permissions may be stale. If access must stop immediately after a source-side revocation, the design needs a current authorization check against that source.
Uptime and latency tell us whether the assistant is available and responsive. They don't tell us whether its answers are useful or correct. We therefore measure retrieval, answer quality, security, system performance, and product outcomes.
Abstention needs to be measured in both directions. An assistant that says "I don't know" to questions it could answer may avoid unsupported claims, but employees will soon stop relying on it. The evaluation set should include both answerable and unanswerable questions so we can balance unnecessary refusals against unsupported answers.
A few estimates help us identify which parts of the system need the most attention. We'll start with query traffic.
Twenty-five queries per second is a modest load for the API servers. The larger concern is the amount of model capacity those requests consume, which we'll estimate after sizing the corpus.
These are estimates for the underlying data. The deployed cluster also needs space for the keyword index, vector index structures, replicas, and operational headroom. Even so, this is a manageable workload for a small search cluster.
At an illustrative embedding price of $0.02 per million tokens, processing roughly 16.5 billion tokens, including overlap, costs about $330. If 2% of documents change each day, embedding the changed content costs only a few dollars per day. Parsing, OCR, storage, and connector operations add separate costs.
The initial backfill is more likely to be limited by source APIs than by embedding cost. SaaS tools throttle requests, and each document must be downloaded, parsed, and sometimes processed with OCR. At a sustained rate of 50 documents per second across all connectors, loading 10 million documents takes about 200,000 seconds, or 2.3 days. That backfill must not delay normal updates.
Now let's estimate generation cost.
Two points stand out. First, generation dominates the estimated cost, so avoiding unnecessary calls to the large model can produce meaningful savings. Second, the provider must support about 8.3 million input tokens per minute at peak, along with the output throughput and roughly 200 concurrent generations. We need to confirm that capacity before launch.
The system has three main paths:
Ingestion runs continuously in the background. Query processing runs whenever an employee asks a question. The two paths share the search index and authorization data, so keeping those stores consistent is central to the design.
Each source has a connector that can list documents, fetch content, read permissions, and detect changes. Connectors publish change events to a queue rather than processing documents directly. This lets change detection continue even when parsing slows down or the embedding service is unavailable.
Workers consume those events and process each document:
A separate identity service synchronizes users and groups from the company's identity provider, such as Okta or Microsoft Entra ID. It also tracks source-specific groups and memberships, including Confluence groups and Slack channels.
When an employee asks a question, the request follows these steps:
A planning budget for time to first token might look like this:
This leaves some room under the 2-second target. These are planning estimates, and the actual p95 must be measured across complete requests rather than inferred by adding component percentiles.
Model generation takes the largest share of the budget, so the earlier stages need to remain fast. First-turn questions usually don't need rewriting, which saves about 300 ms on those requests. Any checks that hold generated text before display also need to fit within the user-visible latency budget.
We'll now examine the parts of this design that need the most care, starting with permissions.
Suppose an employee asks, "What's the plan for the reorganization next quarter?" A draft plan exists in a restricted HR folder. If that document enters the model's context, the model may summarize it for someone who should never have seen it.
A prompt instruction such as "Don't reveal restricted content" cannot enforce authorization. The system must prevent unauthorized content from entering the model's context in the first place.
There are three common approaches.
Retrieve the highest-ranked results without permission filters, then check each result against the source system and remove anything the employee cannot access.
This can use the source's current authorization decision, but it has two drawbacks. First, each query triggers several live API calls, adding latency and consuming source API quotas. Second, employees with limited access may lose most or all of the retrieved candidates. The top 50 results could all be restricted, even when useful documents exist farther down the ranking.
Build a dedicated index for each user or group, containing only the documents they can access.
This can provide strong isolation, but overlapping permissions make it difficult to maintain. A user may belong to many groups, and a shared document may need to appear in many indexes. Every content update then touches multiple copies, while permission changes require careful coordination across indexes.
Store permission metadata with each chunk during ingestion. At query time, resolve the employee's principals and apply an authorization filter to both keyword and vector search.
For documents governed by simple allow lists, a chunk is eligible when its allowed principals overlap with the employee's principals. More complex source rules may require additional policy checks.
Filtering during search is the best default for this system. Making it reliable requires several additional decisions.
If a document is shared with group:eng-platform, store that group on its chunks rather than listing all 400 members. When an employee joins or leaves, the identity service updates their membership. The document's chunks don't need to change.
The identity service maintains a precomputed mapping from users to their principals, including nested groups, and caches it briefly. An employee in 300 groups produces a filter containing roughly 300 IDs. We should benchmark this with the chosen search engine, especially for users with unusually large group memberships.
Permissions may depend on a combination of space access, parent-page restrictions, project roles, and issue-level rules. A flat allow list works only when it preserves those semantics. Where access requires multiple conditions, the connector must retain those conditions or use an equivalent policy representation. This translation deserves dedicated tests because an overly broad rule can expose entire collections.
A file shared with "anyone in the company with the link" may be accessible to every employee, but its owner may expect it to be found only by people who receive the link. Making it searchable changes that expectation. A conservative default is to index it only for explicitly authorized users and groups unless the company approves broader discovery.
Approximate nearest neighbor indexes such as HNSW search only part of a graph. If permission filters exclude nearly everything, some implementations may struggle to return enough relevant results efficiently. Search engines can address this with filter-aware traversal or exact search over a small allowed subset. Test the behavior for the most restricted users, not just typical employees.
Permission metadata in the index can become stale. If Bob loses access at 10:00 but the index updates at 10:04, a query at 10:02 could still retrieve the document.
To reduce this window, permission changes use a priority path that updates the ACL store before the search index. After reranking, the orchestrator checks the final candidates against that store before including them in the prompt. Batched key-value lookups make this check inexpensive.
This protects against stale index metadata once the ACL store has received the change. It does not eliminate the delay between a source-side revocation and its detection. For sensitive sources that require immediate enforcement, verify the final candidates against the source API and accept the additional latency.
The system must also fail closed. If the identity service is unavailable and cached memberships have expired, it should reject the request rather than search without permission filters. The same principle applies when required authorization data is unavailable or too stale.
Retrieval is only one place where restricted content can escape.
A shared response cache might return an answer built from documents another employee cannot access. Debugging traces may contain full prompts and retrieved passages. A "share this answer" link may expose content to a new viewer. Even conversation history can contain information whose permissions have since changed.
These paths need the same controls as retrieval: access-aware caching, permission checks when reusing history or sharing answers, and restricted trace access with appropriate redaction and retention.
Permissions and content both change over time. Next, we'll look at how the system keeps up with those changes.
A nightly full crawl is not enough for this workload. With 10 million documents and rate-limited source APIs, a complete crawl could take days. It also cannot meet a 15-minute content freshness target.
Instead, the system processes changes incrementally and uses periodic reconciliation to catch anything it missed.
Sources expose different change-detection mechanisms. A reliable connector combines the available mechanisms because each covers gaps in the others.
A change cursor lets the connector resume from where it last stopped. For example, Google Drive exposes page tokens for its changes API, while Microsoft Graph supports delta queries for supported resources. Polling every few minutes helps recover changes that webhook processing missed.
Reconciliation compares the source's document inventory with the indexed inventory. If a document is confirmed to be gone or no longer accessible to the connector, it should be removed from retrieval. The process must distinguish that case from an incomplete listing or temporary API failure, which should not trigger mass deletion.
All detection methods produce normalized jobs keyed by document ID. Processing a duplicate event should be harmless, and an older job must never overwrite a newer result.
Coalescing prevents repeated edits from creating unnecessary work. If a page is edited 20 times in ten minutes, the connector can combine nearby events into fewer jobs that fetch the latest version, while still meeting the freshness target.
Jobs are divided into three lanes:
Without separate lanes, importing a SharePoint site with two million documents could push permission revocations to the back of the queue. Workers should reserve capacity and source API quota for priority work. Per-source rate limits and backoff prevent retries or backfills from overwhelming a connector's quota.
For content updates, the pipeline compares the extracted text's hash with the stored hash. If the text is unchanged, it skips embedding. If it has changed, the pipeline re-chunks the document and compares chunk hashes to reuse existing embeddings where possible. An edit may affect several chunk boundaries, but it should not automatically require re-embedding the entire document.
Events can arrive out of order, and workers may finish out of order too. A slow job for an older version must not replace a newer version already in the index.
Each update therefore carries a source version or another reliable revision identifier. The writer uses a conditional update to reject stale work. Partitioning the queue by document ID helps preserve order, but version checks are still needed for retries and concurrent processing.
For a content update, the writer first adds chunks tagged with the new version. Once those chunks are searchable, it marks that version as active in the document store. Old chunks are removed afterward.
During the transition, both versions may exist physically. Retrieval must validate candidates against the active document version, using an index filter or a document-state check, so old and new passages are not mixed in one answer.
A deleted document must stop contributing to answers promptly, even if physical cleanup takes longer.
This gives us a current, permission-aware corpus. The next challenge is finding the passages that actually answer each question.
Many incorrect answers begin with a retrieval failure. If the right passage never reaches the model, the model may abstain or answer using information that sounds relevant but addresses a different question.
Company documents present two common retrieval challenges.
Questions may contain ticket IDs such as PLAT-4521, error codes, product codenames, and team acronyms. Embeddings may not distinguish these identifiers reliably. Keyword search can match them directly.
"Can I expense a home office chair?" should match a section titled "Remote Work Equipment Reimbursement." Vector search can recognize that relationship even when the wording differs.
This is why we use hybrid search. Keyword and vector searches run in parallel with the same permission constraints. Their results are combined using Reciprocal Rank Fusion (RRF), which assigns each chunk a score based on its position in each result list:
Here, L represents a result list, and k is a smoothing constant commonly set to 60. Because RRF uses ranks, the keyword and vector scores do not need to share a scale.
The cross-encoder reranker reads the question and each candidate passage together, then scores their relevance. Unlike a vector retriever that compares independently generated embeddings, it can evaluate detailed interactions between the question and passage. This is too expensive to run across the whole corpus, but practical for a small candidate set.
Reranking 50 candidates might add roughly 50 to 200 ms, depending on the model, hardware, and passage lengths. We validate that cost against the improvement in retrieval and answer quality.
Chunking determines what the reranker receives. A fixed token boundary can split a table or separate a heading from the paragraph it explains. Structure-aware chunking follows sections in wiki pages, meaningful fields in tickets, and conversational boundaries in Slack threads. Large sections or threads still need to be split to fit the chunk budget.
Each chunk should also include its title and section path. A prefix such as "Travel Policy > International Travel > Per Diem" gives the embedding model, reranker, and answer model context that an isolated paragraph may lack.
Finally, relevance alone does not establish which source to trust. "Travel Policy 2023" and "Travel Policy 2025" may both closely match a question about per diem rates. Ranking should consider whether a document is current, approved, archived, or deprecated, and whether it comes from an authoritative policy space or a personal note. Modification time helps, but it should not override an explicit effective date or approval status.
Good retrieval gives the model useful evidence. We still need to control how it uses that evidence.
The model has a specific job: answer the employee's question using the supplied passages and cite the evidence for its claims. The prompt should state that clearly.
Each source includes a title, date, and useful status metadata. The application maintains the mapping from source IDs to URLs so citation links point to the actual retrieved documents.
Keeping the instruction prefix stable may also make it eligible for provider prompt caching, subject to the provider's minimum prefix length and cache behavior.
Some questions can be rejected before calling the large model. If the strongest retrieved passages score below a calibrated relevance threshold, the assistant can respond with "I couldn't find this in the documents you have access to." It can then show up to three related documents, provided they are useful enough to display.
This avoids spending generation tokens when retrieval has found little evidence. We tune the threshold on the evaluation set, balancing correct abstentions against answerable questions that the gate wrongly rejects.
A relevance score is not proof that a passage contains the answer, however. A question about the 2026 bonus structure may retrieve a highly relevant 2025 bonus document. The model must still recognize when the supplied evidence is incomplete or out of date and abstain during generation.
A citation can point to a real source and still fail to support the claim. Verification therefore has two parts.
The structural check confirms that cited IDs appeared in the prompt and that factual statements include citations. Source-ID validation is deterministic. Detecting every factual statement is less exact, but sentence-level rules or a lightweight classifier can identify likely omissions.
The support check asks whether the cited passage actually supports the claim. A natural language inference model or an LLM judge compares the statement with its evidence. This can catch cases where the model cites an on-topic passage that does not justify what it says.
Checking every claim synchronously adds latency and cost. For high-risk content, such as HR or legal policies, the system can buffer completed sentences and check them before releasing them. Generation may continue while a sentence is checked, but unchecked claims should remain hidden if the goal is to prevent unsupported text from reaching the user.
For lower-risk answers, the system can run support checks asynchronously on a sample of responses. Those checks help measure quality and investigate failures, but they cannot prevent an unsupported claim that has already been displayed.
These controls evaluate individual answers. To understand whether the system improves over time, we also need a repeatable evaluation process.
A change can reduce answer quality without causing an exception or increasing latency. A new chunking strategy might separate useful context. A prompt edit might encourage overconfident answers. A model upgrade might change citation behavior.
Evaluation helps us detect these regressions before they reach employees.
Start with questions employees actually ask. Helpdesk tickets and channels such as #ask-it and #ask-hr often contain realistic questions and useful answers. Subject-matter experts can label the expected answer and the documents that support it.
A few hundred carefully labeled questions are enough for an initial evaluation set. Each case should record the relevant user permissions and source versions so the expected result is clear.
The set should deliberately include:
An end-to-end score tells us that quality changed. Stage-level metrics help explain why.
To measure faithfulness, an LLM judge splits an answer into individual claims and checks each against the cited evidence. The score is the fraction of claims supported by those sources.
The judge also needs evaluation. Have humans label a few hundred claims, compare their judgments with the model's, and inspect disagreements. Automated scores are useful only when we understand where the judge is reliable and where it makes mistakes.
Authorization has a clear expected outcome for each test user and document. We can use that to build automated checks.
Create canary documents in each source, each containing a unique random string and accessible only to a dedicated test group. Then issue queries as users outside that group, both in CI and on a production schedule.
If a canary appears in unauthorized retrieved content, model context, or answers, treat it as a high-severity incident. Tests should also cover restricted titles and snippets, inherited permissions, group membership changes, revocations, cached responses, and shared conversations.
Canaries help detect real failures, but passing them does not prove that every permission rule is correct. They complement connector tests, authorization audits, and monitoring.
After deployment, ratings and user behavior help identify problems that the offline set missed.
A thumbs-down rating or an immediate rephrasing of the same question may indicate a poor answer. Citation clicks can show whether employees inspect the evidence, though a lack of clicks does not necessarily mean an answer was unhelpful.
A daily sample of traces goes through automated judging and targeted human review. Confirmed failures are added to the evaluation set so future releases are tested against them.
Embedding-model changes need particular care. Vectors from different models generally do not share a compatible space, so changing models requires re-embedding the corpus. Build the new index alongside the old one, compare them using offline evaluations and shadow traffic, and switch only after the new index meets the quality, latency, and security requirements.
With the main design decisions covered, we can return to the estimates and consider how the system behaves in production.
The API servers and orchestrator are stateless, so they can scale horizontally. The search cluster holds roughly 33 million chunks, distributed across enough shards to fit its memory and storage requirements. Replicas provide availability and additional query capacity.
At the estimated query volume, index memory, permission-filter behavior, and failover capacity may matter more than raw QPS. Load tests should include users with restrictive permissions and queries with large candidate sets.
Ingestion workers scale separately based on queue depth and freshness lag. A large backfill can add processing capacity without changing the query path, although worker scaling remains limited by source API and embedding quotas.
At roughly $150,000 per month in the illustrative estimate, generation is the largest expense. The main opportunities are:
Caching needs invalidation for content updates, deletions, and permission changes. A correct answer can become unsafe to reuse even when its wording has not changed.
A company docs Q&A assistant uses RAG, but most of the design work happens around the model. Here is how the design handles each of the main requirements:
Cost follows from the same choices. Abstaining early, routing simpler questions to cheaper models, and caching answers only where permissions allow it keep the cost per question down.
20 quizzes