Notes
Listen
Listen first. Employees ask questions in a chat thread, with follow-ups. Answers come from wiki pages, PDFs, tickets and shared drives, and every answer cites its sources with links. The assistant may only use documents the asker could open in the source system, and it should say it does not know rather than guess. Users rate answers, and admins connect new sources.
The qualities. Permission leaks are the worst failure, so access checks must be exact, and a revoked share must stop working within minutes. Edits should be searchable within about fifteen minutes. The first token should stream in under two seconds. We sell this to many companies, so tenants are fully isolated. Out of scope: taking actions, understanding images, and training our own model.
- ask questions in a chat thread with follow-ups
- sources: wiki, PDFs, tickets, shared drives
- every answer cites its sources
- only use docs the asker can open
- say "I don't know" when unsure
- thumbs up or down per answer
- admins connect sources
- no leaks: permissions exact, revocations within minutes
- fresh: edits searchable in under 15 minutes
- first token under 2 s
- many customer companies: tenants fully isolated
- out: actions like filing a ticket, image understanding, training our own model
Ask scale
Ask about scale. The largest tenant has five million documents averaging three thousand tokens, fifteen billion tokens. Cut into chunks of about five hundred tokens with some overlap, that is thirty million chunks. At a thousand twenty four dimensions in four-byte floats, vectors take a hundred twenty gigabytes, or thirty quantized to one byte. Embedding everything once costs a few hundred dollars and takes about two days, so a full re-embed is affordable but slow.
Now the query side. A hundred thousand employees, thirty percent asking five questions a day, is a hundred fifty thousand questions, about five a second in work hours and fifteen at peak. That is tiny for servers. The real costs are tokens: about six thousand in and four hundred out per answer, roughly three cents on a frontier model, so forty five hundred dollars a day. Cost and latency, not QPS, drive this design.
5M docs × ~3,000 tokens avg = 15B tokens chunks of ~500 tokens + overlap ≈ 30M chunks vectors: 1,024 dims × 4 B = 4 KB 30M × 4 KB ≈ 120 GB (+ graph) int8 quantized ≈ 30 GB chunk text ≈ 60 GB full embed: 15B tokens ≈ $300 at $0.02 per 1M ≈ 2 days at 5M tokens/min
100k employees, 30% daily × 5 questions = 150k/day over 8 work hours ≈ 5 q/s peak ≈ 15 q/s prompt ≈ 6k tokens in: 1k system + history, 4k docs ≈ 400 tokens out frontier: 6k × $3/1M ≈ 1.8¢ + 400 × $15/1M ≈ 0.6¢ ≈ 3¢ per question ≈ $4,500 per day
Define API
Define the API. Posting a message to a conversation returns a server-sent event stream: tokens as they are generated, then the citations, then a done event with the message id. A feedback call records thumbs up or down with a comment. Admins create connectors with a scope and a reference to stored credentials, and check sync status. Source systems push change events to a webhook endpoint.
POST /v1/conversations/{id}/messages
{ text } → SSE stream:
token… citations… done
POST /v1/messages/{id}/feedback
{ rating, comment }
POST /v1/connectors
{ type, scope, secret_ref }
GET /v1/connectors/{id}/status
POST /v1/hooks/{connector}
change events from sources Data model
The data model. Postgres holds one row per document: tenant, source, URL, title, a content hash, the list of users and groups allowed to read it, and a deleted marker. Raw files sit in object storage. The search index holds chunks: text, vector, section heading, a hash, and a copy of the document's allowed principals so retrieval can filter on them. Messages store the cited chunk ids and a trace id.
documents (Postgres) tenant_id, doc_id PK, source, url, title, content_hash, acl_principals[], deleted_at chunks (search index) chunk_id, tenant_id, doc_id, text, vector, section, hash, acl_principals[] (copied) messages conv_id, role, text, cited_chunk_ids, trace_id
High-level design
Draw the ingestion path first. Connectors watch each source system, by webhook where it exists and by polling for changes otherwise, and put change events on Kafka. Ingestion workers fetch the document and its permissions, store the raw file and metadata, parse it, split it into chunks, embed the chunks, and upsert them into the search index. Everything is asynchronous and retryable.
Now the query path. The orchestrator resolves the user to their groups, rewrites the question if it is a follow-up, and asks the hybrid retriever for chunks the user is allowed to see. The retriever runs keyword and vector search together, a reranker picks the best eight, and the orchestrator sends the question and those chunks to the model, streaming tokens back to the browser.
Deep dive: ingestion
Deep dive one: ingestion. Change detection has three layers. Webhooks give near real-time updates, but events get dropped. So connectors also poll every few minutes with a change cursor, and a weekly full listing is diffed against our document table to catch anything missed, especially deletes. Hash each document and skip unchanged ones, then hash each chunk and re-embed only chunks that changed. Respect each source's rate limits with backoff.
Parsing and chunking decide answer quality more than the model does. Turn wiki HTML into headings and text, read the PDF text layer and fall back to OCR for scans, and keep tables as rows. Split on headings into chunks of three to eight hundred tokens with a little overlap. Prefix each chunk with its document title and section path, so a lone paragraph still says what it is about. A deleted document is tombstoned, its chunks removed and its raw file purged.
- webhook: near real time, but events get lost
- delta poll every 5-10 min with a change cursor
- weekly full listing diff: catches missed deletes
- hash the doc: same? skip
- hash each chunk: re-embed only the changed ones
- per-source rate limits + backoff (APIs throttle)
- wiki: HTML → headings + text
- PDF: text layer; OCR if scan; keep tables as rows
- ticket: one doc per thread, resolution weighted
- split on headings, 300-800 tokens, ~10% overlap
- prefix: "HR Handbook > Leave > Contractors"
- deletes: tombstone doc, drop its chunks, purge raw file
Deep dive: permissions
Deep dive two: access control, the part that gets companies in trouble. The naive design searches everything and filters out forbidden results afterwards. If the filter has a bug, the salary review deck goes straight into the prompt, and the model happily summarises it. Even when it works, post-filtering is weak: if forty-five of the top fifty hits are forbidden, the user gets five weak results. Permissions must be part of the search itself.
Store the document's allowed groups and users on each chunk, and expand the asker's group memberships at query time from a cached identity lookup. Then every search, keyword and vector, carries a mandatory filter: this tenant, and principals overlapping mine. Because chunks store groups, not expanded people, joining a group needs no re-index. A share change only rewrites the permission field, never the embedding. As defence in depth, re-check the final eight chunks against the doc store before prompting.
Keeping permissions in sync is its own pipeline. Permission events jump ahead of content events, since a revocation matters more than a typo fix. A folder share change can touch a hundred thousand documents, so it becomes a bulk metadata update. Group memberships are cached for a few minutes, and revocation events evict immediately. If a document's permissions cannot be read, it is invisible: fail closed. Anyone-with-the-link shares count as private. And never share cached answers between users.
- each chunk stores its doc's allowed groups and users
- query: tenant = T AND principals ∩ my 180 groups
- filter inside the vector search (filtered HNSW), not after it
- share change → rewrite the ACL field only, no re-embed
- final 8 → re-check live ACL
- ACL events go on a priority queue ahead of content
- folder share change: 100k docs → bulk metadata update
- group cache TTL ~5 min; revocation events evict now
- unknown ACL → doc invisible (fail closed)
- "anyone with link" → private
- answer cache keyed by user, never shared across users
Deep dive: query path
Deep dive three: the query path. A follow-up like what about contractors means nothing alone, so a small fast model rewrites it into a standalone question using the chat history. Then run keyword search and vector search in parallel. Keywords catch ticket numbers, error codes and product names that embeddings blur; vectors catch paraphrases. Merge the lists with reciprocal rank fusion, and a cross-encoder reranker scores each candidate against the question to keep the best eight.
Assemble the prompt against a fixed budget: rules, a summary of older turns instead of the whole history, eight chunks of about five hundred tokens, and the question. Number each chunk and tell the model to answer only from them and cite the number after each claim. Afterwards, drop any citation that does not match a provided chunk, and link the rest to the document and section. If even the best rerank score is low, skip the model and say you could not find it, with the closest documents.
The latency budget for the first token. The cached group lookup is twenty milliseconds. The rewrite is three hundred, and skipped when there is no history. Embedding the query and running both searches in parallel is about a hundred twenty. Reranking is a hundred fifty. The model's prefill on six thousand tokens is roughly seven hundred, helped by caching the fixed system prompt prefix. That is about 1.3 seconds, then tokens stream over server-sent events.
- rewrite: "what about contractors?" → full query (small fast model)
- keyword: ticket ids, error codes, product names
- vector: paraphrases
- fuse with reciprocal rank
- rerank 80 → 8 with a cross-encoder (~150 ms)
budget (of 6k input tokens): system + rules 800 history summary 700 8 chunks × ~500 4,000 question 100 chunks numbered [1]..[8] rule: answer only from sources, cite [n] after each claim drop citations not in the set top rerank score < 0.3 → skip the model: "I couldn't find…"
auth + groups (cached) 20 ms rewrite (small model) 300 ms skip on the first turn embed query 40 ms BM25 ∥ vector search 80 ms rerank 80 candidates 150 ms build prompt 10 ms model prefill, 6k tok 700 ms cached prefix helps total ≈ 1.3 s → stream SSE
Deep dive: evaluation
Deep dive four: evaluation. Build a golden set of a few hundred real questions, each labelled with the documents that answer it. Measure retrieval alone with recall at eight: is the right document in the context? Then faithfulness: is every claim supported by the chunk it cites? A judge model scores that, calibrated against human labels. Run this on every change to chunking, embeddings, prompts or models. Online, track thumbs, citation clicks and no-answer rates, and turn bad answers into new golden questions.
- golden set: 500 questions with the right source docs
- retrieval: recall@8, MRR
- faithful: each claim backed by its cited chunk (judge model, checked by humans)
- also: refusal correctness
- online: thumbs, citation clicks, "no answer" rate
- bad answers → review queue → new golden questions
Deep dive: tenancy
Tenancy and safety. A large tenant gets its own index shard; small tenants share one with a tenant filter the retriever adds itself, never the caller. Use per-tenant encryption keys, key every cache by tenant, and lock down traces, because they contain document text. Documents are untrusted input: a wiki page can say ignore your instructions. Delimit sources in the prompt, give the model no tools with side effects, and strip external image links so an answer cannot leak data through a URL.
- big tenant: own index shard
- small tenants: shared index, mandatory tenant filter
- per-tenant encryption keys
- caches and traces keyed by tenant; traces access-locked
- no training on customer data
- docs may hold injected instructions: delimit them, no side-effect tools, strip external image links
Trade-offs
Review the trade-offs. Bigger chunks carry more context but blur retrieval. Reranking costs a hundred fifty milliseconds and is usually the cheapest big quality win. Routing easy questions to a small model cuts cost around tenfold. Changing the embedding model means re-embedding everything into a new index and swapping over, because vectors from different models do not mix. If the model API fails, fall back to a second provider. If retrieval fails, say so instead of answering from the model's memory.
- bigger chunks: more context, fewer, blurrier hits
- rerank: +150 ms, big recall win
- small model for easy questions: ~10x cheaper, route by intent
- new embedding model: re-embed all, blue-green index swap
- model API down → second provider, same prompt
- index down → say so, never answer from memory
Interview summary
The thirty-second summary. Five million documents become thirty million chunks and about a hundred twenty gigabytes of vectors. Peak load is fifteen questions a second at about three cents each. Ingest with webhooks, polling and a full diff, hashing to skip unchanged content. Put permissions on every chunk and filter inside the search. Rewrite, run hybrid search, rerank to eight, answer with citations or say you do not know, and prove it with recall and faithfulness evals.
- 5M docs → 30M chunks, 120 GB
- 15 q/s peak, ~3¢ per answer
- ingest: webhooks + polling + full diff, hash to skip
- chunk by headings, add titles
- ACL principals on each chunk, filter inside the search
- rewrite → hybrid → rerank 8
- cite or say "I don't know"
- evals: recall@8, faithfulness