LearnSystem design

Retrieval-augmented assistant over internal documents

Build an assistant that answers analysts’ questions using internal research notes and filings, with citations and access controls.

ML engineering8 parts

Contents

Constraints

  • 50M document chunks
  • 5k daily users
  • p95 answer latency under 6 s
  • documents updated hourly
  • strict entitlements per user

What to cover

Sketch your own design first. A complete answer has these parts; the notes say what each should settle.

  1. RequirementsBuild an assistant that answers analysts’ questions using internal research notes and filings, with citations and access controls.
  2. Estimates50M document chunks; 5k daily users; p95 answer latency under 6 s; documents updated hourly; strict entitlements per user.
  3. API
  4. Data model
  5. ArchitectureIngestion with chunking and metadata; hybrid retrieval (BM25 + embeddings); permission filtering at retrieval time.; Reranker; prompt assembly with citations; LLM generation with answer-grounding checks.; Caching; feedback capture; an evaluation harness (golden Q&A set, LLM-as-judge with human calibration).; Observability (traces, token cost).
  6. Deep dives
  7. Trade-offschunk size vs context; retrieval recall vs latency and cost; hosted vs self-served models; abstaining vs answering; freshness of the index.
  8. EvaluationOffline: retrieval recall@k on labelled queries, faithfulness/groundedness, citation accuracy, answer correctness on a golden set.; Online: thumbs-up rate, escalations, time saved.; Guardrails: entitlement-leak tests, hallucination rate.

Reference design

One way to answer it, part by part. Open a part once you have your own version of it.

Requirements

Functional: analysts ask questions in natural language (“What did our analysts say about UK utilities’ capex guidance this quarter?”) and get concise answers with citations to the exact passages in internal research notes and company filings; follow-up questions; filters by company, date, document type and author; the assistant says when the documents do not answer the question.

Non-functional

  • p95 answer latency < 6 s for a complete answer (streamed, first tokens much sooner).
  • Documents updated hourly; new research notes searchable within an hour of publication.
  • Strict entitlements: each user sees only documents they are entitled to (research desks, licensed content, information barriers between private and public sides). A leak is a compliance incident, not a quality issue.
  • Auditability: who asked what, which documents were used.

Assumptions to confirm: 50M chunks; 5k daily users at ~20 questions each; English first; entitlements available from an internal service as groups and document tags; model hosting options include self-hosted open-weight models and an approved hosted provider.

Estimates

CalculatorHow the 6 s p95 budget adds up

Generation time = Output tokens ÷ Generation rate

Total latency = Pre-LLM stages + LLM first token + Generation time + Grounding check

Headroom = p95 budget − Total latency

Worked cases
CasePre-LLM stages (s)LLM first token (s)Output tokens (tokens)Generation rate (tokens/s)Grounding check (s)p95 budget (s)Generation timeTotal latencyHeadroom
Text default0.90.83001000.563 s5.2 s0.8 s
The pre-LLM stages, first token, generation and grounding check sum to about 5.2 s against a 6 s p95 budget.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
  • Traffic: 5k users × 20 questions = 100k questions/day; over a ~12-hour global working day ≈ 2.3 QPS average, ~10 QPS peak (market open, earnings days).
  • Vector index: 50M × 1,024 dims × 1 byte (int8) ≈ 51 GB, ~80 GB with the HNSW graph — a few replicated shards. BM25 over 50M × 400 tokens = 20B tokens ≈ 150 GB.
  • Hourly updates: if ~1% of chunks change per day → 500k/day ≈ 21k chunks/hour × 400 tokens ≈ 8.4M tokens/hour to embed — minutes on one GPU.
  • Generation: 12 chunks × 400 + 1k system/history ≈ 6k input, ~300 output tokens. 100k × 6k = 600M input + 30M output tokens/day. Hosted at an assumed $3/M in, $15/M out: $1.8k + $0.45k ≈ $2.3k/day ≈ 2 cents per question. Self-hosted 70B: ~10 QPS × ~5 s ≈ 50 concurrent sequences → ~4 TP-2 replicas ≈ 8 GPUs ≈ $500/day plus operations — cheaper at scale and keeps sensitive text in-house.
  • Latency budget (p95 6 s): entitlement resolution 50 ms, query rewrite 250 ms, hybrid retrieval 200 ms, rerank 300 ms, prompt assembly 50 ms → ~0.9 s; LLM first token 0.8 s; 300 tokens at ~100 tokens/s ≈ 3 s; grounding check overlapped, ~0.5 s at the end → ~5.2 s, which forces concise answers and a fast model.

API

POST /v1/ask   (SSE)
  {conversation_id?, question, filters: {tickers: ["SSE LN"], doc_types: ["research_note", "10-K"],
   from: "2026-07-01"}}
  → events: token {text} · citation {n, doc_id, title, author, published_at, page, passage}
           · final {answer, citations[], grounded: true, abstained: false, trace_id}

POST /v1/feedback {trace_id, rating: "up"|"down", reason: "wrong"|"missing_source"|"outdated"|
                   "not_entitled_content", comment}
GET  /v1/documents/{doc_id}?highlight=passage_id    (entitlement re-checked on open)
Ingestion: document events {doc_id, version, entitlement_tags, content_uri} from the publishing
           system and filings feed

User identity comes from SSO; entitlements are resolved server-side, never passed by the client.

Data model

  • Document: doc_id, type (research note, filing, transcript), source, company/tickers, author/desk, published_at, version, entitlement tags, retention class.
  • Chunk: chunk_id, doc_id, text, section path (e.g. “Risk factors > Liquidity”), page, table flag, position, embedding, entitlement tags (denormalised), published_at.
  • EntitlementMap: user → groups → allowed tags; cached with a short TTL and versioned; information-barrier rules as deny tags.
  • Conversation / Turn: question, rewritten query, retrieved and cited chunk ids, answer, model version.
  • Trace: per stage latency, token counts and cost, retrieval scores, grounding verdicts; stored under the same entitlement controls as the documents it quotes.
  • Feedback and GoldenItem (question, expected documents/passages, reference answer, answerable flag, entitlement profile of the test user).

Architecture

Flow · 6 stepsRequest path for an entitled answer

Request path for an entitled answerThe flow starts with an analyst question entering the Assistant API over SSO, then resolves entitlements from a cached, versioned map. The query is rewritten, hybrid retrieval applies the allowed tags inside the query, and a cross-encoder reranks the top 100 to the top 10-12. The LLM generates with citations, a separate grounding check drops unentailed sentences or abstains, and the final cited set is re-checked before the answer streams to the user.Analyst questionnatural languageAssistant APIPOST /v1/ask (SSE)EntitlementMapcached ≤ 5 min,versionedQuery rewritestandalone, tickernormalisationHybrid indexBM25 + vectors, entitlement tagsCross-encoder reranktop 10-12LLM generationgeneration, cites [n]Grounding checkentailed by cited passage, else dropor abstainAnswercitations re-checkedSSOresolvequestionallowed tagsquerytop 100top 10-12answerstream123456RequestRetrievalGeneration
  1. Resolve entitlements The analyst question enters the Assistant API over SSO and entitlements are resolved from the cached, versioned map.
  2. Rewrite query The question is made standalone, with ticker and company normalisation and filters applied.
  3. Retrieve Hybrid retrieval runs with the user's allowed tags inside the query, returning the top 100.
  4. Rerank A cross-encoder reranks the retrieved passages down to the top 10-12.
  5. Generate The LLM generates the answer with numbered passages and cites [n].
  6. Ground and answer Each sentence is checked against its cited passage; unentailed sentences are dropped or the assistant abstains, citations re-checked, then streamed.

An analyst's question moves through entitlement resolution, hybrid retrieval, reranking, grounded generation and a final citation re-check before the answer streams back.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Resolve entitlementsThe analyst question enters the Assistant API over SSO and entitlements are resolved from the cached, versioned map.
2Rewrite queryThe question is made standalone, with ticker and company normalisation and filters applied.
3RetrieveHybrid retrieval runs with the user's allowed tags inside the query, returning the top 100.
4RerankA cross-encoder reranks the retrieved passages down to the top 10-12.
5GenerateThe LLM generates the answer with numbered passages and cites [n].
6Ground and answerEach sentence is checked against its cited passage; unentailed sentences are dropped or the assistant abstains, citations re-checked, then streamed.

Source: This page's text

Boxes
BoxGroupDetail
Analyst questionRequestnatural language
Assistant APIRequestPOST /v1/ask (SSE)
EntitlementMapRetrievalcached ≤ 5 min, versioned
Query rewriteRequeststandalone, ticker normalisation
Hybrid indexRetrievalBM25 + vectors, entitlement tags
Cross-encoder rerankRetrievaltop 10-12
LLM generationGenerationgeneration, cites [n]
Grounding checkGenerationentailed by cited passage, else drop or abstain
AnswerGenerationcitations re-checked

Source: This page's text

Flow · 4 stepsHow documents reach the searchable index

How documents reach the searchable indexA publishing system and filings feed feed document events into ingestion. New and changed chunks are parsed, chunked with metadata and entitlement tags, embedded, and written to the hybrid index as hourly incremental updates. Deletions and re-tagging go straight from the feed to the index without re-embedding.Publishing /filings feeddocumenteventsParse &chunkPDF tables,sections,metadataDeletions &re-taggingwithoutre-embeddingEmbedmetadata +entitlementtagsHybridindexBM25 +vectors;entitlementfiltershourlydeletes, re-tagsimmediate1234IngestionIndex
How documents reach the searchable indexA publishing system and filings feed feed document events into ingestion. New and changed chunks are parsed, chunked with metadata and entitlement tags, embedded, and written to the hybrid index as hourly incremental updates. Deletions and re-tagging go straight from the feed to the index without re-embedding.Publishing / filings feeddocument eventsParse & chunkPDF tables, sections,metadataDeletions & re-taggingwithout re-embeddingEmbedmetadata + entitlement tagsHybrid indexBM25 + vectors; entitlement filtershourlydeletes, re-tagsimmediate1234IngestionIndex
  1. Document events Document events arrive from the publishing system and filings feed.
  2. Parse, chunk and embed Parse PDF tables and sections, chunk with metadata and entitlement tags, then embed.
  3. Deletions and re-tagging Deletions and re-tagging propagate immediately, without re-embedding.
  4. Index refresh New and changed chunks reach the index as hourly incremental updates; deletions and re-tagging update it immediately.

Documents flow from the publishing system and filings feed through parsing, chunking and embedding into the hybrid index, while deletions and re-tagging bypass embedding and update the index immediately.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Document eventsDocument events arrive from the publishing system and filings feed.
2Parse, chunk and embedParse PDF tables and sections, chunk with metadata and entitlement tags, then embed.
3Deletions and re-taggingDeletions and re-tagging propagate immediately, without re-embedding.
4Index refreshNew and changed chunks reach the index as hourly incremental updates; deletions and re-tagging update it immediately.

Source: This page's text

Boxes
BoxGroupDetail
Publishing / filings feedIngestiondocument events
Parse & chunkIngestionPDF tables, sections, metadata
EmbedIngestionmetadata + entitlement tags
Deletions & re-taggingIndexwithout re-embedding
Hybrid indexIndexBM25 + vectors; entitlement filters

Source: This page's text

Publishing system / filings feed ─► Ingestion: parse (PDF tables, sections),
   chunk with metadata (company, section, page), entitlement tags ─► embed
   ─► Hybrid index (BM25 + vectors, entitlement tags as filter fields), hourly
      incremental updates; deletions and re-tagging propagate immediately
User ─SSO─► Assistant API
   1. resolve entitlements (cached ≤ 5 min, versioned)
   2. query rewrite: standalone question, ticker/company normalisation, filters
   3. hybrid retrieval WITH entitlement filter (top 100) ─► fusion
   4. cross-encoder rerank ─► top 10–12
   5. prompt assembly with numbered passages ─► LLM generation, cite [n]
   6. grounding check: each sentence entailed by its cited passage; else
      remove sentence or abstain
   ─► stream to user · caches keyed by (query, entitlement version)
Evaluation harness (golden set, LLM judge calibrated by humans) · feedback store
Observability: traces per request, token cost, latency per stage, leak tests

Deep dives

Entitlements at retrieval time. Filtering after generation is too late — the model has already seen restricted text. Entitlement tags live on every chunk and the index applies the user’s allowed tags inside the retrieval query; very restrictive users who can see few documents fall back to exact search to preserve recall. Caches key on entitlement version, and the final cited set is re-checked before display. Re-tagging a document (for instance when it moves behind an information barrier) updates the index immediately, without re-embedding.

Financial documents are awkward. Filings are long, repetitive and full of tables; chunk by section with headings carried into each chunk, keep tables intact with captions, and record page numbers so citations land precisely. Normalise tickers and company names so “SSE” and “SSE plc” retrieve the same filings.

Abstention. If reranker scores are low or the grounding check removes most sentences, say the documents do not answer the question and show the closest sources, rather than guessing.

Trade-offs

  • Chunk size vs context: small chunks retrieve precisely but lose surrounding context; large chunks keep context but dilute relevance. ~300–500 tokens with section headings, plus neighbour expansion at answer time.
  • Retrieval recall vs latency and cost: retrieving 100 and reranking to 12 costs ~300 ms; retrieving fewer is faster but misses evidence. Tune on recall@k against the latency budget.
  • Hosted vs self-served models: hosted models are stronger and need no GPU operations but send sensitive text outside and cost per token; self-served open-weight models keep data in-house and are cheaper at steady volume but need serving expertise. With material non-public information in scope, self-hosting (or a dedicated private deployment) is likely required.
  • Abstaining vs answering: analysts dislike “I don’t know”, but a confident wrong figure is worse; tune the threshold per question type and show sources either way.
  • Freshness of the index: hourly incremental updates meet the requirement; a near-real-time path for breaking research notes costs more ingestion complexity.

Evaluation

  • Offline retrieval: recall@k (k = 20, 100) on labelled queries with known relevant passages, by document type and query type.
  • Offline generation: faithfulness/groundedness (claims entailed by cited passages), citation accuracy, answer correctness on a golden set built with analysts; LLM-as-judge for scale, calibrated against human ratings (agreement checked each release).
  • Guardrails: entitlement-leak tests — synthetic users with known entitlements probing restricted documents, through every cache — must find zero leaks before release; hallucination rate on unanswerable questions.
  • Online: thumbs-up rate, escalations to human research support, citation clicks, time saved (survey and task studies), abstention rate.
  • Monitoring: per-stage latency against the budget, token cost per answer, ingestion lag, grounding-check failure rate, entitlement cache staleness.

What a strong design shows

  • Enforces entitlements inside retrieval, re-checks before display and keys caches by entitlement version.
  • Builds a hybrid retrieval, rerank and grounded-generation pipeline sized to a 6 s p95 budget with explicit arithmetic.
  • Handles financial documents properly: section-aware chunking, tables, page-level citations, ticker normalisation.
  • Evaluates retrieval and generation separately, calibrates the LLM judge with humans, and runs entitlement-leak tests as a release gate.
  • Makes a reasoned hosted vs self-hosted choice given cost and data sensitivity.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.