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.
- RequirementsBuild an assistant that answers analysts’ questions using internal research notes and filings, with citations and access controls.
- Estimates50M document chunks; 5k daily users; p95 answer latency under 6 s; documents updated hourly; strict entitlements per user.
- API
- Data model
- 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).
- Deep dives
- Trade-offschunk size vs context; retrieval recall vs latency and cost; hosted vs self-served models; abstaining vs answering; freshness of the index.
- 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
- 3 s
- Total latency
- 5.2 s
- Headroom
- 0.8 s
Generation time = Output tokens ÷ Generation rate = 3 s
Total latency = Pre-LLM stages + LLM first token + Generation time + Grounding check = 5.2 s
Headroom = p95 budget − Total latency = 0.8 s
| Case | Pre-LLM stages (s) | LLM first token (s) | Output tokens (tokens) | Generation rate (tokens/s) | Grounding check (s) | p95 budget (s) | Generation time | Total latency | Headroom |
|---|---|---|---|---|---|---|---|---|---|
| Text default | 0.9 | 0.8 | 300 | 100 | 0.5 | 6 | 3 s | 5.2 s | 0.8 s |
- 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
- Resolve entitlements The analyst question enters the Assistant API over SSO and entitlements are resolved from the cached, versioned map.
- Rewrite query The question is made standalone, with ticker and company normalisation and filters applied.
- Retrieve Hybrid retrieval runs with the user's allowed tags inside the query, returning the top 100.
- Rerank A cross-encoder reranks the retrieved passages down to the top 10-12.
- Generate The LLM generates the answer with numbered passages and cites [n].
- Ground and answer Each sentence is checked against its cited passage; unentailed sentences are dropped or the assistant abstains, citations re-checked, then streamed.
Data
| Step | Title | What happens |
|---|---|---|
| 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. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Analyst question | Request | natural language |
| Assistant API | Request | POST /v1/ask (SSE) |
| EntitlementMap | Retrieval | cached ≤ 5 min, versioned |
| Query rewrite | Request | standalone, ticker normalisation |
| Hybrid index | Retrieval | BM25 + vectors, entitlement tags |
| Cross-encoder rerank | Retrieval | top 10-12 |
| LLM generation | Generation | generation, cites [n] |
| Grounding check | Generation | entailed by cited passage, else drop or abstain |
| Answer | Generation | citations re-checked |
Source: This page's text
Flow · 4 stepsHow documents reach the searchable index
- Document events Document events arrive from the publishing system and filings feed.
- Parse, chunk and embed Parse PDF tables and sections, chunk with metadata and entitlement tags, then embed.
- Deletions and re-tagging Deletions and re-tagging propagate immediately, without re-embedding.
- Index refresh New and changed chunks reach the index as hourly incremental updates; deletions and re-tagging update it immediately.
Data
| Step | Title | What happens |
|---|---|---|
| 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. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Publishing / filings feed | Ingestion | document events |
| Parse & chunk | Ingestion | PDF tables, sections, metadata |
| Embed | Ingestion | metadata + entitlement tags |
| Deletions & re-tagging | Index | without re-embedding |
| Hybrid index | Index | BM25 + 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 testsDeep 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.