Multi-Source Enterprise Question Answering System
Medium · System Design · Software Engineer · Technical Screen
Prompt
Architect a read-only enterprise AI research system that answers multi-hop business questions by pulling together internal company repositories—spanning structured systems of record like CRM or ticketing databases alongside unstructured wikis and file shares—and external web or licensed news feeds.
Assume traffic volume, model selection, latency budgets, and connector protocols are open for you to clarify and justify, and mutating underlying business applications is out of scope. Connected systems vary widely in schema, update lag, API quotas, uptime, and row- or file-level access controls; holding an account on a tool never grants an employee blanket visibility into every record inside it.
Scope & Expectations
- Connectivity, authorization, and query planning: Clarify when questions require structured filters versus semantic search, enforce per-user access controls across live reads and bounded-staleness indexes, and bound generated retrieval plans against runaway calls or query injection.
- Entity linking, provenance, and grounded generation: Normalize timestamps and business units across heterogeneous records, link cross-tool entities only on defensible identifiers (asking for disambiguation when names collide), and synthesize cited responses that surface uncertainty, conflicts, or missing evidence honestly.
- Operational resilience and evaluation: Manage source timeouts and strict third-party API rate budgets with transparent partial responses, design caches that honor both user permissions and staleness bounds, and evaluate retrieval recall independently from synthesis faithfulness.
Step-by-step walkthrough
Clarify requirements and permissions rules
Imagine a regional sales director asking an enterprise research assistant: "Which of our top 8 renewals closing this quarter have open Sev-1 support tickets, and did any of those accounts announce restructuring in the news?" No single search box can answer this. The platform must query a CRM (Customer Relationship Management database, such as Salesforce, where deal records live), search a support tracker or internal wiki, and check external news—then join matching accounts without leaking restricted records.
Functional requirements
- Accept a natural-language question (plus optional conversation state for follow-ups) and return a synthesized response where every factual claim cites specific records or passages.
- Query three families of repositories:
- Structured internal systems: transactional databases with typed schemas, such as Salesforce (CRM), Jira/Zendesk (support tickets), and billing ledgers.
- Unstructured internal content: free-text corpora such as engineering wikis, Google Drive or SharePoint folders, and chat archives.
- External feeds: public web search and licensed financial or news wires.
- Read-only boundary: the assistant strictly reads authorized records and documents; mutating data in underlying business applications is out of scope.
- Report provenance (the exact record link, version, and retrieval timestamp of each cited item) alongside coverage (which repositories answered, which failed or timed out, and which were skipped).
Non-functional requirements
- Zero permission leaks (top priority): an employee must never see a number, text snippet, or existence hint from a record they could not open directly in the origin tool. Missing a file is a recall gap; exposing an unauthorized deal value is a security incident.
- Bounded staleness: each repository defines a maximum acceptable data age, or staleness bound (for example, real-time reads for CRM opportunities, up to 1 hour for wiki text).
- Predictable latency: emit the retrieval plan within ~1 second, begin streaming answer text within ~5 seconds at the median (p50, meaning half of requests start faster), and finish within ~20 seconds at p95 (95% of requests).
- Strict multi-tenant isolation: in a multi-tenant deployment (one platform serving many independent enterprise customers, or tenants), each tenant's credentials, search indexes, and caches remain isolated so records can never cross company boundaries.
Core product and permission decisions
- Hybrid structured + unstructured routing: questions like "sum of Q1 renewal values" need typed filters and exact arithmetic, whereas "what SLA carve-out did legal approve?" requires semantic text search, and multi-hop questions combine both in one plan.
- Live reads vs. bounded-staleness indexing: execute live user-delegated reads against fast-changing, complex-ACL systems like Salesforce, and maintain a bounded-staleness search index over large document stores—paired with a live permission re-check on the ~12 shortlisted chunks immediately before synthesis.
- Disambiguation over guessing: whenever "Northstar" matches two unrelated accounts or a term like "active account" lacks a single definition in the tenant glossary, return one concise clarifying prompt listing concrete options rather than guessing silently.
- Explicit citations and outage transparency: every factual claim links to its origin record with an
as_oftimestamp, and unreachable tools are named explicitly in both prose and structured metadata rather than treated as "zero matches."
Back-of-the-envelope numbers
Because the prompt leaves scale open, state concrete sizing assumptions for one large enterprise tenant (20,000 employees) and show what bottlenecks emerge.
Users and query traffic (one large enterprise tenant) Total employees 20,000 Daily active askers 5,000 users x 8 questions/day = 40,000 questions/day Average rate (8-hour workday) 40,000 / 28,800 s = ~1.4 questions/s Peak rate (3x busy-hour burst) ~4.2 questions/s (round to ~4 questions/s) Retrieval fan-out per question Query plan size average 4 source calls/question, hard cap 8 Peak retrieval rate 4 questions/s x 4 calls = ~16 source calls/s Salesforce (CRM) API quota — the scarcest resource Questions needing CRM 40% of questions x 2 calls = 0.8 CRM calls/question CRM usage per 24 hours 40,000 x 0.8 = 32,000 calls per rolling 24h window Admin-allocated CRM budget assume 50,000 calls / 24h (shared with other integrations) -> 64% of budget on normal days: strict plan caps and short-lived caching are mandatory! Unstructured document index Documents 5M docs (wikis, files, tickets) x ~8 chunks/doc = 40M chunks Embeddings (1,024 dimensions) int8 (1 byte/dim): 40M x 1,024 B = ~41 GB (~45 GB with graph links) float32 (4 B/dim): 40M x 4,096 B = ~164 GB Daily document churn 1% updated/day = 50,000 docs/day = ~0.6 docs/s LLM synthesis latency and concurrency Synthesis input 12 evidence items x 500 tokens + 1,500 prompt tokens = ~7,500 tokens Synthesis output ~500 tokens; at ~50 tokens/s, full answer takes ~10 s -> must stream! Time to first answer token ~0.8 s fast planner + ~2.5 s parallel retrieval + ~0.2 s live ACL check + ~0.7 s prompt prefill = ~4.2 s (meets the ~5 s p50 target) Peak concurrent LLM streams 4 questions/s x 10 s duration = ~40 in-flight generations (Little's law)Three design decisions follow directly from this math:
- API rate limits fail before servers do: 4 queries/s is tiny for web servers, but 32,000 Salesforce calls/day already consumes 64% of our 24-hour quota. Without hard step limits and caching, one runaway agent loop would lock out the whole company.
- Quantized vectors fit in memory on one machine: storing embeddings (lists of numbers representing text meaning) as 1-byte integers (
int8) instead of 4-byte floats (float32) shrinks 40 million chunks to ~45 GB, fitting comfortably in RAM on a dedicated per-tenant replica pair. - LLM generation dominates wall-clock time: parallel retrieval finishes in 1–3 seconds, whereas writing 500 tokens takes ~10 seconds. Streaming output and using a small, fast model (~150+ tokens/s) for the initial JSON plan are essential to hit the 5-second first-token target.
API and streaming contract
Users authenticate via SSO (Single Sign-On, the company's central login system), so the server extracts
tenant_idanduser_idfrom the authenticated token rather than trusting request body fields. Because answers take several seconds,POST /v1/askstreams progress over SSE (Server-Sent Events, a standard HTTP stream that pushes JSON events from server to browser).POST /v1/ask (Authorization: Bearer <SSO_JWT>) { "question": "Which top 8 renewals closing this quarter have open Sev-1 tickets or restructuring news?", "conversation_id": "conv_504", "sources": ["salesforce", "jira", "wiki", "web_news"], "max_staleness_s": 3600 } -> 200 OK (Content-Type: text/event-stream) event: plan data: {"steps": [{"id": "s1", "source": "salesforce", "status": "running"}, {"id": "s2", "source": "jira", "status": "queued"}, {"id": "s3", "source": "web_news", "status": "queued"}]} event: step data: {"id": "s1", "status": "ok", "records": 8} event: step data: {"id": "s3", "status": "failed", "reason": "SOURCE_TIMEOUT"} # If an entity or business term is ambiguous, ask instead of guessing and close stream: event: clarify data: {"question": "Did you mean Northstar Health (US, northstarhealth.com) or Northstar Health Ltd (UK, northstar.co.uk)?", "options": [{"label": "Northstar Health (US)", "entity_id": "ent_11"}, {"label": "Northstar Health Ltd (UK)", "entity_id": "ent_12"}]} # Otherwise, stream verified sentences carrying server-assigned evidence IDs: event: answer_delta data: {"text": "Two of the top 8 Q1 renewals have open Sev-1 support tickets [E2][E6]. "} event: final data: { "answer_id": "ans_72c8", "status": "partial", "evidence": [ {"id": "E2", "source": "salesforce", "kind": "record", "ref": "Opportunity/006N410", "link": "https://tenant.my.salesforce.com/006N410", "source_version": "2026-12-01T09:14:22Z", "as_of": "2026-12-01T09:40:05Z"} ], "coverage": { "consulted": ["salesforce", "jira", "wiki"], "failed": [{"source": "web_news", "reason": "SOURCE_TIMEOUT"}], "skipped": [] }, "unsupported_claims_removed": 0 }Key contract details:
partialis a first-class status: whenweb_newstimes out, the user still gets the Salesforce + Jira answer immediately, withcoverage.failedclearly explaining why news is omitted.- Server-minted citation IDs (
E1,E2): the LLM can only cite IDs from the authorized evidence set built for this request; it cannot invent arbitrary URLs. - No raw query strings in the API: clients can restrict which
sourcesto consult, but cannot inject raw SQL or Salesforce query text.
Data model for connectors, permissions, and entities
Every stored chunk, entity mapping, and cached answer carries tenant isolation, permission metadata, and timestamps.
connectors (tenant_id, connector_id, type, mode: live | indexed, auth_mode: user_oauth | service_crawl, rolling_24h_budget, freshness_slo_s, authority_rank_by_field) identity_map (tenant_id, sso_user_id, connector_id, source_principal_id) # Maps one employee's SSO login -> Salesforce User ID, Jira ID, Google email group_membership (tenant_id, principal_id, group_id, synced_at) # Expanded at login into user_principals[] and cached for 5 minutes chunks (tenant_id, chunk_id, doc_id, connector_id, source_ref, source_version, modified_at, fetched_at, text, embedding int8[1024], allowed_principals[], denied_principals[], acl_epoch, entity_ids[]) entities (tenant_id, entity_id, type: account | person | product, canonical_name, domain, country, legal_registry_id) entity_links (tenant_id, entity_id, connector_id, source_record_id, match_evidence: shared_foreign_key | legal_id | verified_domain | human_approved, confidence, created_by, created_at) metric_glossary (tenant_id, term, canonical_metric, unit, period_type: fiscal | calendar, authoritative_connector_id) answers (tenant_id, answer_id, user_id, question, plan_json, evidence_ids[], evidence_versions[], status, coverage_json, created_at) answer_cache key: (tenant_id, user_id, normalized_question) value: (answer_id, cited_evidence_ids[], evidence_versions[], cached_at)Notice two careful design choices:
- Permission lists (
allowed_principals,denied_principals) live directly on eachchunksrow alongsideacl_epoch(a counter incremented whenever permissions change), so unauthorized chunks are filtered out during search. answer_cachekeys on(tenant_id, user_id, normalized_question), while storingcited_evidence_idsandevidence_versionsin the value. Because we do not know which records a question touches before running its plan, source versions cannot be part of the lookup key; instead, on a cache hit, we validate those stored IDs against current permissions and freshness bounds before returning the answer.
- Permission lists (
High-level architecture
Deterministic code enforces identity, query safety, entity linking, arithmetic, and permission checks; LLMs are used only for planning and prose synthesis, with validators checking both outputs.
Employee Browser / Chat App | POST /v1/ask (SSO token) v [ API Gateway: SSO auth, tenant isolation, rate limit ] | v [ Query Orchestrator ] |-- (1) Expand user -> groups & source IDs ---------> [ Identity & Group Service ] |-- (2) Generate JSON retrieval plan (fast LLM) ----> [ Deterministic Plan Validator ] |-- (3) Execute DAG steps in parallel (per-step timeouts & token-bucket budgets) | |--> [ Salesforce Connector (live, user OAuth) ] ---> Salesforce REST API | |--> [ Hybrid Search (BM25 + int8 Vector + ACL) ] --> [ Tenant Chunk Index ] | |--> [ External News/Web Connector (service key) ] -> News / Search APIs | '--> [ Typed Calculator: sums, counts, FX math ] |-- (4) Normalize units/timestamps & resolve entities -------> [ Entity & Glossary Store ] |-- (5) Live ACL re-check on final ~12 indexed items --------> Source Permission APIs |-- (6) Synthesize cited answer (LLM, sentence-buffered) '-- (7) Verify citations, numbers, & entailment -------------> SSE Stream to User Background / Offline Pipelines Source webhooks + crawlers --> [ Parse, Chunk, Embed, Map ACLs ] --> [ Tenant Chunk Index ] ACL sync (every ~5-15 min) + daily full reconciliation ------------> Updates acl_epoch Hourly permission canaries + golden-set eval runner ---------------> Quality & Security AlertsWalking through one request:
- Identity expansion translates the user's SSO token into their Salesforce identity and their group list (
user_principals). - Validated planning turns the question into a small DAG (Directed Acyclic Graph, a multi-step dependency plan with no loops) of typed tool calls, checked by deterministic code before any call runs.
- Parallel execution + live safety check fetches records, links cross-system entities, re-verifies permissions on the top ~12 indexed chunks, and hands only authorized, timestamped evidence (
E1...E12) to the synthesis LLM.
- Identity expansion translates the user's SSO token into their Salesforce identity and their group list (
Deep dive 1: Connectors, permissions, and live vs. indexed reads
Enterprise sources fall into two permission patterns, and mixing them up causes data leaks:
- Delegated user access (live OAuth on behalf of the user): used for Salesforce and complex transactional systems. Salesforce permissions combine role hierarchies, record ownership, manual sharing rules, and field-level security (for example, hiding
Margin__cwhile showingAmount). Copying that logic into our own database is error-prone, so we pass the user's delegated OAuth token (a scoped credential acting strictly as that user) directly to Salesforce at query time. - Service-account crawl + mirrored ACLs (indexed search): used for Google Drive, Confluence, or Jira documents where each file has an explicit ACL (Access Control List, the list of users and groups allowed or denied read access). A background crawler indexes chunks and tags each chunk with
allowed_principalsanddenied_principals. - Fail-closed rule: if a connector cannot prove a user's permission (for instance, an unmapped SSO user or an unsupported custom sharing rule), that source returns zero items—never falling back to an admin account's view.
Explicit trade-off: live source reads vs. indexed search
Dimension Live Read (User OAuth) Indexed Search (Mirrored ACL) --------------------- ---------------------------------- -------------------------------------- Data freshness Real-time (0 lag) Content <= 1 hr; ACL sync <= 15 min Permission fidelity Exact (enforced by source engine) Mirrored copy; needs live re-check Query latency 300 ms - 3,000 ms (variable) 50 ms - 200 ms (predictable) Source API quota Every user question spends quota Crawled once per document edit Search ranking Often weak keyword/filter search Hybrid BM25 keyword + semantic vector Source outage impact Source down -> step fails Serves last snapshot with clear ageHow the two work together safely for unstructured search:
- Hybrid search combines BM25 (exact keyword scoring for product codes and error strings) with vector similarity (semantic matching for paraphrases), filtering chunks where
allowed_principalsoverlapsuser_principalsanddenied_principalsdoes not. - Selective-ACL fallback: standard ANN (Approximate Nearest Neighbor) graph search slows down or misses results when a user can access only 0.01% of the 40M chunks (4,000 chunks), because most graph neighbors are unauthorized dead ends. When a user's accessible count is small (say
< 50,000chunks), we skip the graph and score their exact accessibleint8vectors directly (4,000 x 1,024byte operations takes< 2 mson CPU). - Pre-synthesis live ACL re-check: right before synthesis, we make one batched permission check per source for the ~12 winning document IDs (~150 ms). Even if someone revoked file access 10 seconds ago—before the 15-minute ACL sync ran—the chunk is dropped before the LLM ever sees it.
- Delegated user access (live OAuth on behalf of the user): used for Salesforce and complex transactional systems. Salesforce permissions combine role hierarchies, record ownership, manual sharing rules, and field-level security (for example, hiding
Deep dive 2: Bounded query plans and safe tool execution
Letting an LLM write raw SQL or SOQL (Salesforce Object Query Language) invites syntax crashes, runaway full-table scans, and prompt injection (malicious instructions hidden inside a retrieved web page or ticket trying to trick the LLM into stealing internal data). Instead, the planner emits a JSON DAG restricted to a fixed catalog of read-only operations:
Pre-planner context injected by code: current_date = "2026-12-01", tenant_fiscal_quarter = "FY27-Q1 (2026-10-01 to 2026-12-31)" Generated JSON plan: s1: salesforce.list_opportunities( close_date_from="2026-10-01", close_date_to="2026-12-31", opp_type="Renewal", order_by="amount_desc", limit=8) s2: jira.search_tickets( entity_ids_from="s1.entity_id", priority="Sev-1", status="Open", limit=100) s3: web_news.search_company_news( entity_ids_from="s1.entity_id", topic="restructuring", published_after="2026-09-01")Deterministic code validates four guardrails before executing a single step:
- Fiscal calendar & glossary pre-resolution: code resolves "this quarter" from the tenant's
metric_glossary(2026-10-01to2026-12-31) before planning so the LLM never guesses calendar Q4 instead of fiscal Q1. - Hard execution bounds: maximum 8 steps total, at most 3 dependency levels,
limit <= 200rows per step, fan-out<= 25IDs passed viaentity_ids_from, 4-second timeout per step, and 15-second ceiling across all retrieval (allowing at most 1 bounded follow-up retrieval round if initial docs reference a specific contract ID). - Parameterized templates, never raw query strings: Salesforce's REST
/queryendpoint accepts a SOQL string without SQL-style bind variables, so the connector validates types strictly (18-character Salesforce IDs, ISO dates, allowlisted enum fields) and escapes quotes, backslashes,%, and_in any free-text filter. An input likeNorthstar' OR Name LIKE '%stays an inert literal string. - Exfiltration-safe external queries:
web_news.search_company_newsdoes not accept free-form strings generated after reading internal docs. It accepts onlyentity_ids(which deterministic code maps to public company names/domains) plus topic keywords present in the user's original question. A malicious prompt inside an internal ticket cannot smuggle secret deal sizes out to a search engine URL.
- Fiscal calendar & glossary pre-resolution: code resolves "this quarter" from the tenant's
Deep dive 3: Entity resolution and evidence normalization
Identical or similar display names never establish that two records refer to the same organization. Suppose Salesforce holds an account
"Northstar", Jira has a ticket filed under"Northstar Health", and a news wire reports clinic closures at"Northstar Health Ltd". Joining on fuzzy string similarity would falsely warn an account executive that their Boston hospital network is restructuring when the article actually describes an unrelated UK clinic group.We link cross-source records using a strict 5-rung evidence ladder:
Rung Matching Evidence Across Sources System Action ---- --------------------------------------------------- ---------------------------------------- 1 Explicit cross-system ID (jira.sf_account_id == Id) Auto-link (high confidence) 2 Shared legal identifier (LEI, DUNS, tax/registry #) Auto-link (high confidence) 3 Verified corporate web domain + matching country Link as "medium confidence"; cite domain (both use northstarhealth.com, US, no conflicts) match explicitly in the answer 4 Human-confirmed link stored in entity_links Auto-link (auditable: who & when) 5 Similar display name only ("Northstar" vs. "...Ltd") NEVER auto-merge! Ask user to clarify or report records separatelyConcrete trace of why Rung 5 and corporate hierarchy tracking prevent silent corruption:
Salesforce Opportunity 006N410: Account = "Northstar Health", Website = "northstarhealth.com", HQ = "MA, US" News Article N44: Headline = "Northstar Health Ltd closes 6 UK clinics", Domain = "northstar.co.uk" -> Rung 1-4 all fail (domains northstarhealth.com != northstar.co.uk, countries US != UK). -> Result: N44 is excluded from Northstar Health's restructuring check (or triggers a clarify event if the user simply asked "Tell me about Northstar"). Also, corporate parent/subsidiary links (such as a shared parent stock ticker) are stored as parent-child edges rather than merged into one entity, so a subsidiary's ticket count is not silently conflated with the parent's contract unless requested.Evidence and measure normalization: before synthesis, every record is wrapped in a canonical envelope carrying
source_version,as_of,entity_id, and typed numeric facts (metric,value,currency,period). Arithmetic runs inside the deterministic Typed Calculator, which refuses to add incompatible metrics—for example, Salesforce ARR (Annual Recurring Revenue, annualized subscription run-rate) is never added to GAAP revenue (accounting revenue recognized in public financial filings), and EUR deals are converted to USD only via an explicit dated exchange-rate evidence item.Deep dive 4: Grounded synthesis, provenance, and reliability
Grounded generation and verification
The synthesis LLM receives only the numbered, authorized evidence envelopes (
E1...E12) andcoverage. To keep first-token latency fast (~5 s) without flashing fabricated numbers on screen, the orchestrator buffers output one sentence at a time (~25 tokens, ~0.5 s) and runs three checks:- Citation check: every factual sentence must cite valid IDs (
[E2]) from this request's evidence map. - Exact number check: code normalizes numbers (
"$120K"->120000) and verifies every number appears either in its cited evidence or in a Typed Calculator output (including counts like "2 of the 10 renewals"). - Entailment check: a fast NLI (Natural Language Inference) classifier—a small model trained to judge whether a premise text logically supports a hypothesis sentence—checks each claim against its cited snippet. Unsupported claims are stripped (or trigger one regeneration if >20% fail).
Handling missing, contradictory, and partial evidence
- Missing vs. failed: if Jira succeeded with 0 hits, state "No open Sev-1 tickets were found in Jira as of 09:40 UTC." If
web_newstimed out, state "External news timed out, so restructuring announcements could not be checked" (status: "partial"). Never report a failed source as "none found." - Contradictions: if Salesforce lists
$180,000and a wiki page says$150,000,authority_rank_by_fieldprefers Salesforce for deal amounts while citing both values and their dates.
Retries, quota protection, and authorization-aware caches
- Bounded retries & circuit breakers: retry timeouts, HTTP
429(rate limit), and5xxerrors at most twice with jittered backoff (~200 ms, ~800 ms plus random milliseconds so retries do not synchronize) inside the step's 4 s deadline. Never retry permanent errors like Salesforce HTTP403 REQUEST_LIMIT_EXCEEDED(rolling 24h org quota exhausted). A circuit breaker (an automatic switch that stops calling a failing dependency) opens per(tenant, source)if >50% of calls fail over 30 s, probing once every 30 s. - Token-bucket quota shedding: track each tenant's rolling 24-hour CRM budget in a token bucket (a counter reserving capacity for bursts while enforcing a sustained ceiling), prioritizing interactive user questions over background crawls. Above 80% usage, tighten fan-out limits (
limit=5) and lean on short-TTL caches. - Permission-scoped caches:
Cache Layer Lookup Key TTL & Hit Validation ----------------- --------------------------------------------------- ------------------------------- Source responses (tenant, source, user_id, op, normalized_args) Salesforce: 5 min; Web: 1 hr Index retrieval (tenant, hash(user_principals), query, index_ver) Invalidated on acl_epoch bump Synthesized ans. (tenant, user_id, normalized_question) 15 min; re-check cited IDs live Query embeddings (tenant, model_ver, query_text) 7 days (tenant-isolated!)- Citation check: every factual sentence must cite valid IDs (
Evaluation: separating retrieval coverage from synthesis quality
When an answer is wrong, an end-to-end grade cannot tell whether retrieval missed the right record or the LLM hallucinated over good records. Measure the two stages independently on a golden evaluation set (~400 real-world questions per pilot tenant, each tested under multiple user roles with different permissions):
- Retrieval metrics: evidence recall@k (fraction of human-labeled gold records present in
E1...Ek), plan validity & budget adherence, and entity-link precision (precision outweighs recall because a false entity merge creates confident falsehoods). - Synthesis metrics: claim support rate (percentage of atomic claims supported by cited evidence), key-fact recall, and abstention accuracy (returning
insufficient_evidencewhen evidence is absent). - The oracle-retrieval diagnostic: run the synthesis pipeline by feeding it the exact gold evidence directly. If quality jumps to 98% with oracle evidence but sits at 70% end-to-end, retrieval/planning is the bottleneck; if oracle synthesis is still 75%, fix the synthesis prompt or verifier.
- Permission canary blockers: plant synthetic restricted documents containing unique canary strings (such as
PROJECT-COBALT-7732) invisible to test user B. Any canary appearance in user B's answers blocks deployment immediately and triggers alerts in hourly production checks.
- Retrieval metrics: evidence recall@k (fraction of human-labeled gold records present in
Intuition & how it works
Think of this system as an executive research analyst who borrows your personal employee security badge before walking into any filing room, writes down the exact folder ID and timestamp next to every note, refuses to assume two folders labeled "Northstar" are the same organization without checking their legal registry ID or web domain, and hands you a memo with footnotes attached to every single sentence.
The naive approach—copying every Salesforce record, Jira ticket, and wiki page with an admin account into one giant vector database (a search store matching text by numerical meaning) and feeding the top 10 chunks into an LLM—fails catastrophically in an enterprise. First, copying Salesforce data without complex per-user sharing rules leaks confidential deals across teams; second, indexed deal numbers go stale within minutes; third, string-matching "Northstar" merges unrelated organizations and sums incompatible financial numbers.
Walk through a tiny concrete trace with 4 items to see how our pipeline prevents all three failures:
- Question & plan: Account director Maya asks, "Do our top 2 renewals closing this quarter have open Sev-1 tickets or restructuring news?" Code resolves "this quarter" to fiscal
2026-10-01..2026-12-31, and a fast planner LLM emits a validated 3-step plan (salesforce->jira+web_news). - Permission-safe retrieval: Step 1 queries Salesforce live using Maya's delegated OAuth token (a scoped credential acting strictly as Maya), returning
Opp-1(Northstar Health,northstarhealth.com, US,$180K) andOpp-2(Vanguard Logistics,vanguardlog.io, US,$95K) while Salesforce automatically hidesOpp-3, which Maya is not permitted to view. - Entity resolution: Step 2 finds a Sev-1 Jira ticket linked to
Opp-1by shared foreign key (sf_account_id), and Step 3 finds a news story about "Northstar Health Ltd (northstar.co.uk, UK) clinic closures." Becausenorthstarhealth.com(US) conflicts withnorthstar.co.uk(UK), the entity resolver refuses to attach the UK restructuring article toNorthstar Health. - Verified synthesis: Right before synthesis, any indexed doc chunks pass a live ACL (Access Control List—who can read a file) re-check, and the LLM streams "Northstar Health (
$180Krenewal [E1]) has 1 open Sev-1 ticket [E2], and neither account has verified restructuring news [E3]," with code checking every citation and number sentence by sentence.
Key trade-offs
- Live user-authenticated reads vs. indexed search. Live reads run with the user's own OAuth token so the source enforces exact permissions and zero staleness, at the cost of slower latency (0.3–3 s) and spending scarce API quota (the source system's rolling request allowance) on every question. Indexing chunks in advance gives fast (~100 ms) hybrid search (combining exact BM25 keyword matching with semantic vector matching) and survives source outages, at the cost of mirroring ACLs and tolerating bounded staleness. Reading structured systems of record (Salesforce) live while indexing unstructured docs—plus live re-checking the final ~12 doc IDs—gets the best of both.
- Typed plan operations vs. unconstrained LLM queries. Restricting the planner to a schema-validated catalog of read-only operations with hard fan-out caps makes API quota and security predictable, and blocks prompt injection (malicious text inside a document trying to hijack tool calls). The trade-off is that unusual ad-hoc questions may require narrowing or a clarifying turn.
- Entity-linking precision vs. recall. Linking cross-system records only on shared system IDs, legal registry numbers, or verified domain + country misses some real matches where metadata is messy (lower recall), whereas fuzzy name matching causes confident false joins (lower precision). In enterprise QA, false joins destroy trust, so strict precision wins and ambiguity triggers a clarifying question.
- Sentence-buffered verification vs. raw token streaming. Checking citations, numbers, and entailment (whether the cited text logically supports the claim, scored by a small classifier) one sentence at a time adds ~0.5 s before the first words appear, compared to unverified token-by-token streaming, but prevents hallucinated numbers from flashing on screen.
- Partial answers vs. all-or-nothing timeouts. Returning a
"partial"answer when an external news API times out keeps latency bounded and delivers useful internal data, providedcoverage.failedand the prose both state clearly what could not be checked so silence is never misread as "nothing found."
Common mistakes
- Equating connector access with full table access: assuming that because an employee has a Salesforce login they may read every Salesforce account, ignoring record ownership, role hierarchies, and field-level security.
- Post-filtering top-k vector results without a fallback: fetching the global top 20 chunks and dropping unauthorized ones afterward, which returns empty results when a user can only read a small slice of the corpus (or leaks document existence via counts).
- Letting the LLM write raw SQL or SOQL (Salesforce Object Query Language), or interpolating retrieved internal text into external web search queries where third-party search providers can log confidential deal terms.
- Unbounded agent loops ("keep searching until confident") that exhaust the organization's shared 24-hour Salesforce API allowance in a single afternoon.
- Fuzzy-joining company names or summing incompatible metrics, such as adding CRM ARR (Annual Recurring Revenue) to GAAP revenue (accounting revenue from financial statements) or mixing fiscal and calendar quarters.
- Caching answers by normalized question alone, which serves an executive's authorized answer to an intern who asks the exact same question five minutes later.
- Evaluating only end-to-end answer quality, making it impossible to tell whether bad answers come from missed retrieval or hallucinated synthesis.
Follow-up questions
- When an employee loses read access to a document or CRM record, how do you prevent stale search indexes and response caches from leaking it? For indexed document chunks, an incremental ACL webhook or sync worker (running within ~15 minutes, backed by a daily full reconciliation) strips the user or group from
allowed_principalsand incrementsacl_epoch, invalidating retrieval caches; across that 15-minute sync window, the mandatory pre-synthesis live permission check on the ~12 shortlisted chunks catches the revocation immediately so the passage never reaches the generator. On everyanswer_cachehit, the orchestrator re-verifies all storedcited_evidence_idsagainst the caller's current permissions—checkingacl_epochand live file ACLs for indexed items and executing one batched user-OAuth read for CRM record IDs—evicting and recomputing the response if any check fails (with high-security tenants able to disable even the 5-minute per-user CRM read cache). - How should the system behave when combining a real-time system of record with a secondary data store whose latest sync is multiple days behind? Every normalized evidence envelope carries explicit
source_versionandas_oftimestamps, and the synthesis prompt surfaces concrete dates whenever repositories differ noticeably in recency (for instance, "Salesforce live as of Dec 1; billing warehouse synced Nov 27"). Whenever an older repository breaches the caller'smax_staleness_sbound and supports live reads within quota, the orchestrator refreshes those specific IDs live; otherwise it flags the affected claims as potentially stale or setsstatus: "partial". Above all, the deterministic Typed Calculator refuses to add or subtract point-in-time figures across mismatched dates (such as live pipeline minus four-day-old invoices) without labeling the date gap explicitly. - How can you catch cases where the generator attaches valid, on-topic citations to a factual statement that those cited passages never actually substantiate? Verify faithfulness at the atomic claim level rather than checking mere topical overlap with the cited document. Split each buffered sentence into individual factual assertions, run a deterministic number checker confirming every numeric figure appears in its cited
[Ei]envelope or a Typed Calculator output, and evaluate each assertion against strictly its cited snippet via a calibrated NLI (Natural Language Inference) entailment classifier. Unsubstantiated claims are stripped before streaming (or trigger one bounded regeneration), while the liveunsupported_claims_removedcounter triggers regression alerts and offline oracle-retrieval benchmarks measure generator hallucination rates on exact human-curated evidence.
Follow-up questions
- When an employee loses read access to a document or CRM record, how do you prevent stale search indexes and response caches from leaking it?
- How should the system behave when combining a real-time system of record with a secondary data store whose latest sync is multiple days behind?
- How can you catch cases where the generator attaches valid, on-topic citations to a factual statement that those cited passages never actually substantiate?
Similar questions
- Front-End Architecture for a Live Comment Feed with Optimistic Rendering
- Live Comment Threads with Optimistic Client Writes
- Payment Card Input Controller with Cross-Field Validation
- Text-Game Action Agent with LLM Retries
- Critiquing and Defending Your Published ML Research
- Largest Value After Removing One '5'
More Cohere interview questions
- Payment Card Input Controller with Cross-Field Validation Medium
- Text-Game Action Agent with LLM Retries Medium
- Critiquing and Defending Your Published ML Research Medium Pro
- Largest Value After Removing One '5' Medium Pro
- Teaching an LLM to Handle Post-Cutoff Questions Medium Pro
- Live Comment Threads with Optimistic Client Writes Medium Pro
- End-to-End Post-Training Architecture for a 7B Enterprise Coding Model Medium Pro
- Front-End Architecture for a Live Comment Feed with Optimistic Rendering Medium Pro
- From Pre-Training to Alignment: The LLM Lifecycle Medium Pro
- Top-k and Nucleus (Top-p) Probability Filtering Medium Pro