Document-Grounded Chat at Scale: Upload, Index, and Serve Sessions
System DesignModel answerLast updated
Design a multi-document chat backend where each session accepts up to 200 files, covering async indexing, latency budgets, safe caching, and rate-limit-aware admission control.
You are designing the backend for an enterprise assistant that answers questions over user-supplied files. In a single session a user can upload up to 200 documents (PDF, DOCX, TXT, CSV) totaling hundreds of megabytes, then ask questions across them and continue a multi-turn conversation with streamed answers.
Stated targets:
- More than 100,000 active sessions.
- Response time under 3 seconds end to end.
- Time to first streamed token under 500 ms.
- Uploaded documents and their vectors expire after 24 hours.
Several facts are not given: page counts, parsing complexity, output length, request arrival rate, and model-provider quotas. Active sessions are not the same as simultaneous generations, and upload, parsing, chunking, embedding, retrieval and generation are separate stages.
Explain how you would interpret, budget and validate these targets, and how you would stop document processing or provider throttling from overwhelming the service.
Part 1 - Upload and asynchronous ingestion. Design the path from upload to a searchable index without buffering or parsing files in the web gateway. Cover status reporting, retries, and what boundary of "indexed" queries can see.
Part 2 - Meeting and measuring query latency. Allocate the critical path across retrieval, context assembly and generation. Describe caching, including when a semantic cache may safely reuse an answer and when it may not.
Part 3 - Scaling under quota pressure. Describe admission control, handling of provider 429 responses, and backpressure between ingestion and interactive queries.
State the clarifying questions you would ask first and the assumptions you adopt.
Hints
Hint 1
Start by pinning down what each target measures: does the 3 s figure include the last generated token, does it apply only after ingestion finishes, and at which percentile? Convert 'active sessions' into an estimate of concurrent requests.
Hint 2
Keep the gateway thin: issue scoped, time-limited direct-to-object-store uploads, then drive idempotent per-document stages through a queue. Give each document a state and give queries an explicit corpus version or a declared partial-readiness rule.
Hint 3
Any cache key must encode who is asking and what they are allowed to see: tenant, user, session corpus version, conversation context, prompt and model version. Reserve provider capacity for interactive traffic and give ingestion a separate, lower-priority budget.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Interpret the targets first
- Active is not concurrent. With 100k active sessions and, say, one question per session every 60 s, that is about 1,700 queries/s at peak before burstiness. If generation lasts 5 s, Little's law gives roughly 8,000 in-flight generations. I would state this as an assumption and validate it with load tests, not take it as given.
- Scope of the targets. I would propose: the 500 ms TTFT and 3 s total apply to queries against an already-indexed corpus, at p95 (p50 reported too), with output capped (for example 300 tokens). Ingestion has its own targets (time until a document is "ready"). Without an output cap, a 3 s total can't be promised because decode speed bounds it.
- Feasibility, not guarantee. A 3 s total is only reachable if provider decode speed times the output cap fits the remaining budget. I would measure this rather than promise it.
2. Part 1: Upload and asynchronous ingestion
Upload path
- The client asks the API to create an upload. The API checks authorization, per-session limits (200 files, size caps, allowed types) and returns a presigned, short-lived URL for direct upload to object storage. The gateway never touches file bytes.
- A storage event (or client "complete" call that the server verifies) creates a document record:
uploaded -> parsing -> chunking -> embedding -> indexed | failed. - Large files use multipart upload with resumability. Content hashes support dedupe within a tenant and safe re-upload.
Pipeline
- Each stage is a queue-driven worker pool, keyed by
(document_id, stage, attempt). Stages are idempotent: outputs are written under deterministic keys (chunk IDs derived from document ID + offset + parser version), so a retry overwrites rather than duplicates. - Retries use exponential backoff with jitter and a max attempt count; poison documents go to a dead-letter queue and surface as
failedwith a reason (encrypted, corrupt, too large, unsupported). - Parsing runs in sandboxed workers with CPU/memory/time limits (PDFs and DOCX are an attack surface). Embedding is batched to use provider or GPU throughput well.
- Per-tenant and per-session fairness: a user who uploads 200 files must not starve others. Use weighted fair queuing or per-tenant concurrency caps.
Status and readiness
- Push per-document status over the session's stream (SSE/WebSocket) with polling as fallback, plus aggregate progress ("137/200 ready").
- Choose a readiness policy explicitly. My default is partial readiness with a corpus generation: each time a document becomes indexed, the session's
corpus_versionincrements. A query pins the version at admission and searches only chunks from that version, and the answer tells the user which documents were included ("3 of 200 still processing"). The strict alternative (block until all are ready) gives complete answers but poor UX; offer it as an option for compliance-sensitive flows. - Index writes must be visible atomically per document: write all chunks, then flip the document to
indexedin one step. A query never sees half a document.
Expiry
- Every object, chunk, vector and cache entry carries
expires_at = created + 24h. Use storage lifecycle rules and per-session vector namespaces/partitions so deletion is dropping a namespace. Retrieval also filters onexpires_at, so expiry is enforced even if cleanup lags.
3. Part 2: Query latency
Illustrative budget (p95, indexed corpus)
| Stage | Budget |
|---|---|
| Auth, session load, admission | 20-30 ms |
| Query rewrite using history (small model or heuristic) | 0-100 ms |
| Query embedding | 30-50 ms |
| Vector search, session-scoped, top-k plus optional hybrid BM25 | 50-100 ms |
| Rerank (optional, small cross-encoder) | 50-100 ms |
| Prompt assembly | 10-20 ms |
| Provider queueing + prefill to first token | 150-250 ms |
| TTFT total | < 500 ms |
| Decode remaining tokens | ~2.5 s |
Decode of N tokens at R tokens/s must fit: N/R ≲ 2.5 s, so at 80 tokens/s the output cap is around 200 tokens. Longer answers need either a relaxed total target or a different promise ("first token < 500 ms, completion depends on length").
Tactics
- Stream from the first token; send retrieval citations early.
- Run query embedding and conversation-summary lookup in parallel.
- Keep the vector index per session small (a few thousand chunks), which makes search fast and isolation simple.
- Cap context (top-k, token budget) and keep a rolling conversation summary instead of full history.
- Use prompt/prefix caching at the provider for the stable system prompt.
- Skip the rewrite and rerank steps when the budget is tight.
Caching and its correctness
- Embedding cache keyed by (model version, normalized text): safe broadly.
- Retrieval cache keyed by (tenant, session, corpus_version, query embedding hash, filters).
- Answer/semantic cache is the risky one. Safe reuse requires the same authorization scope, same corpus_version (so newly indexed documents invalidate it), same model and prompt version, and no dependence on conversation state. A follow-up like "what about the second one?" depends on history, so it must not hit a cache keyed only on text similarity. Semantic similarity thresholds must be conservative, and answers must never cross users, tenants or sessions unless the corpus is genuinely shared and ACLs match. All entries have TTL ≤ session expiry.
- Do not cache failures or degraded answers.
Validation
- Instrument per-stage histograms and TTFT/total at p50/p95/p99, by output length bucket.
- Load test with realistic session mix, replayed conversations and injected provider latency/429s. Report the target as met or not met per percentile, never assumed.
4. Part 3: Scaling under quota pressure
- Admission control. Limit active requests, not sessions. Use a token-bucket on provider requests/minute and tokens/minute (estimate tokens = prompt + max output), shared across the fleet through a central limiter or per-node slices of the quota.
- Traffic classes. Interactive queries have reserved capacity and priority; ingestion embedding and background work use a separate lower-priority pool, so a bulk upload slows indexing instead of chat. Allow ingestion to borrow idle capacity but be preempted.
- Fairness. Per-tenant and per-user concurrency caps; weighted fair queuing so one tenant cannot consume the quota.
- Handling 429s. Honor
Retry-After; use exponential backoff with full jitter; cap retries by remaining latency budget (an interactive request that cannot finish usefully should fail fast). Use a circuit breaker per provider/region and fail over to a secondary region or model if allowed by data policy. Avoid retry storms with a retry budget (for example, retries ≤ 10% of traffic). - Backpressure. Bounded queues with load shedding: when ingestion queues grow, slow acceptance of uploads (429 to client with guidance) rather than letting them balloon. For queries, return a clear "busy, queued" status or a smaller-model/shorter-answer degraded mode.
- Visible degradation. Label degraded responses (fewer chunks, no rerank, smaller model, truncated answer) and record them as SLO misses, not hidden successes. Report SLO attainment separately for full-quality and degraded paths.
5. Common mistakes
- Treating 100k active sessions as 100k simultaneous generations (or ignoring it entirely).
- Parsing or buffering files in the web tier.
- Non-idempotent stages that duplicate chunks on retry.
- Querying a half-indexed document or an unversioned corpus.
- A semantic cache keyed only by question text, leaking across users or ignoring conversation context and new uploads.
- Retrying 429s immediately and amplifying the overload.
- Promising 3 s total without bounding output length.
- Forgetting that caches and vectors must also expire at 24 hours.