High-Scale RAG Ingestion and Low-Latency Serving for 200-File Sessions
Hard · System Design · Software Engineer · Onsite
Prompt
Design both the document-ingestion pipeline and the live conversational serving path for an enterprise RAG platform. Within a single workspace session, a user can upload up to 200 files across PDF, DOCX, TXT, and CSV formats totaling several hundred megabytes, then hold multi-turn Q&A conversations grounded in those files. For instance, in workspace ws_704, an analyst might upload a deal room containing msa_draft.pdf, rate_card.csv, scanned_exhibit.pdf, and 197 supporting attachments, ask "What is the H1 unit rate?", and follow up on the next turn with "And for H2?".
Stakeholders state three headline goals: supporting over 100,000 active sessions, keeping time to first streamed token (TTFT) below 500 milliseconds, and finishing end-to-end responses in under 3 seconds, while enforcing a 24-hour expiration window on all uploaded files and vectors.
Explain how you interpret, budget, and empirically validate these targets while preventing heavy 200-file ingestion bursts and upstream model-provider rate limits (HTTP 429 throttling) from degrading live chats:
- Key workload inputs—average page counts, OCR versus digital text mix, answer token lengths, request arrival rates, regional network hops, and model-provider RPM/TPM quotas—are not specified upfront and must be surfaced and bounded explicitly.
- Over 100,000 live sessions within a 24-hour window does not mean 100,000 simultaneous LLM generations in flight.
- File upload, text extraction, chunking, embedding, retrieval, and token streaming are separate phases; define clearly which phases the
< 500 msand< 3 sbudgets measure, and distinguish an uploaded session from a fully searchable 200-file corpus. - Clarify whether users may query ready subsets while remaining files are still indexing or must wait for full 200-file readiness, and ensure every retrieval path and cache respects the 24-hour expiry boundary.
Scope & Expectations
- Bounded upload and asynchronous indexing: Keep bulky file transfers out of web gateways, handle heterogeneous formats (
PDF,DOCX,TXT,CSV) idempotently with per-file progress, and define an explicit corpus-readiness contract across up to 200 documents. - Latency budgeting and validation: Separate first-token and full-turn budgets with clear percentile and output-length bounds, walk through retrieval and prompt assembly, and describe how to benchmark feasibility against real provider prefill and decode speeds.
- Context- and expiry-safe caching: Specify exact cache keys and boundaries across authorization, corpus updates, multi-turn conversation context, model versions, and the 24-hour file expiration rule.
- Quota isolation and backpressure: Separate active sessions from concurrent requests, isolate interactive query capacity from background embedding spikes, and handle provider
429throttling with transparent degradation rather than masking missed SLAs.
Step-by-step walkthrough
Clarify requirements and make the latency targets measurable
Three headline targets anchor this system—>100,000 active sessions, < 500 ms TTFT (Time To First Token) (the delay from sending a question until the first real word of the answer arrives), and < 3 seconds end-to-end response time. None of those targets can be engineered or verified until we define exact measurement boundaries and separate what we control from external provider limits.
Functional requirements
- Allow a session to upload up to 200 documents (
PDF,DOCX,TXT,CSV) totaling hundreds of megabytes without passing file bytes through the web gateway. - Parse, chunk, and embed documents asynchronously while reporting real-time per-document status.
- Serve multi-turn conversational Q&A with streaming tokens and document/page citations.
- Enforce a strict 24-hour expiration across raw files, parsed chunks, vector indexes, and every cache layer.
Non-functional requirements
- Isolate interactive query latency from background ingestion bursts and large 200-file uploads.
- Degrade visibly under provider rate limits (explicit queue notice, labeled compact mode, or
HTTP 429withRetry-After)—never hang silently or hide shed traffic from SLA metrics. - Enforce strict session and tenant isolation across indexes and caches.
Answers assumed for the clarifying questions
- Which stages do
< 500 msTTFT and< 3 stotal cover? They apply strictly to interactive queries on already-searchable documents, measured at our API gateway from request acceptance to first answer-text token (TTFT) and final token (total), reported at p95 (meaning 95% of requests beat the target; browser network RTT is tracked alongside as a separate client metric). Sending an empty"thinking..."metadata event does not count as first token. Ingestion has its own time-to-ready SLA (first small files searchable within< 15–30 s; typical 30-file session ready within< 2 minp95). - Partial vs. complete corpus queries? Supported via an explicit request flag:
coverage = "ready_subset"(default) answers immediately from ready files while displaying"Searched 164 of 200 documents; 36 still processing", whereascoverage = "require_all"returns409 CORPUS_NOT_READY(or queues a background run) until all 200 files reachREADYwith zero failures. - Active sessions, arrival rate, and output length?
100,000 active sessionsmeans live sessions within their 24-hour window—most are reading or idle at any instant. Furthermore, becausetotal_time = TTFT + output_tokens / decode_speed,< 3 stotal is physically achievable only up to a bounded output length (e.g.,<= 200 tokensat80 tokens/s), so total-latency SLAs are bucketed by output token count. - 24-hour clock and provider quotas? Each document expires strictly at
uploaded_at + 24h(and the session itself atcreated_at + 24h); if documents in one session were uploaded hours apart, retrieval filtersdoc.expires_at > nowand caches cap their TTL at the earliestexpires_atamong used documents. Provider TPM (Tokens Per Minute) and RPM (Requests Per Minute) quotas are treated as explicit capacity inputs.
- Allow a session to upload up to 200 documents (
Back-of-the-envelope sizing
1. Session & document shape (baseline assumptions to validate in production) Live sessions (< 24 h old) 100,000 sessions Typical session 30 documents, 60 MB total, ~1,500 pages (~500 tokens/page) Maximum session 200 documents, 500 MB cap, ~10,000 pages (~10,000 chunks) 2. Ingestion pipeline throughput New sessions 100,000 / 86,400 s = ~1.2 sessions/s avg (~3.5/s at 3x peak) Direct upload bandwidth 100,000 x 60 MB = 6 TB/day -> ~70 MB/s avg, ~210 MB/s (~1.7 Gbps) peak Text parsing CPU (~0.1 s/page) 1,500 pages x 0.1 s = 150 core-s/session -> ~525 CPU cores at 3x peak Scanned PDF OCR (~2.0 s/page) 20x heavier per page -> isolated OCR worker pool & queue! Ingestion embedding rate 750,000 tokens/session x 3.5/s = ~2.6M tokens/s (~156M TPM) at peak Self-hosted ~335M-param embedder ~0.7 GFLOP/token x 2.6M/s = ~1.8 PFLOP/s -> ~12-18 A100-class GPUs (at ~35% of 312 TFLOP/s FP16 peak) 3. Live 24-hour memory & storage footprint Vectors (1,024 float32 = 4 KB) 1,500 chunks x 4 KB = 6 MB/avg session -> ~600 GB across 100k sessions Chunk text + keyword postings ~2 KB/chunk -> ~300 GB across 100k sessions Largest 200-doc session vectors 10,000 chunks x 4 KB = ~41 MB contiguous float32 array Raw uploaded files (24 h object) ~6 TB in object storage 4. Interactive query load (stress scenario: every live session asks 1 question per 100 seconds) Peak query arrival rate 100,000 / 100 s = 1,000 queries/s Concurrent open streams Little's Law (rate x duration): 1,000/s x 3 s = ~3,000 active streams Tokens per query ~500 system + ~500 history + (8 chunks x 500) = ~5,000 input, ~200 output LLM provider demand at 1,000 QPS 5M input tokens/s (300M TPM!) + 200k output tokens/s (12M TPM)Four architectural decisions fall straight out of this math
- 100,000 active sessions != 100,000 concurrent LLM calls: By Little's Law (average items in flight equals arrival rate multiplied by average duration), even a heavy 1,000 QPS peak keeps only ~3,000 HTTP streams open at once.
- Per-session exact search beats a giant global ANN index: Even a maxed-out 200-document session holds just
41 MBof vectors (6 MBon average). Streaming41 MBthrough a server core with~20 GB/smemory bandwidth takes~2 ms(< 0.5 msfor an average session), giving 100% recall, instant per-session isolation, and O(1) partition drop at 24-hour expiry! - Ingestion embeddings (~156M TPM peak) rival interactive LLM tokens (~300M TPM peak): Sharing one provider quota pool would let an upload spike starve live chats immediately—so embeddings either run on self-hosted GPUs or sit behind a strict quota wall.
- Provider TPM dictates sustainable QPS: Given granted input quota
Q_tpm, maximum sustainable throughput isQ_tpm / (60 x 5,000)QPS; cutting prompt context in half doubles QPS capacity.
API for direct-to-storage uploads and streaming queries
1. Create session POST /v1/sessions -> 201 { session_id, created_at, expires_at } 2. Authorize bounded direct uploads (gateway never touches file bytes!) POST /v1/sessions/{sid}/documents:prepare Body: { files: [{ client_file_id, name, size_bytes, content_type, sha256 }] } -> 200 { documents: [{ document_id, presigned_put_url, max_bytes, url_expires_at }] } -> 422 LIMIT_EXCEEDED (> 200 total docs in session, > 500 MB cumulative bytes, or unsupported type) 3. Client uploads directly to Object Storage PUT <presigned_put_url> (S3/GCS enforces exact Content-Length, Content-Type, SHA-256, and 10-min expiry) 4. Storage event (or explicit `:complete` callback) triggers async ingestion POST /v1/sessions/{sid}/documents/{did}:complete -> 202 { state: "UPLOADED" } 5. Poll or subscribe (SSE) to corpus readiness GET /v1/sessions/{sid}/corpus -> 200 { corpus_generation: 17, total: 200, ready: 164, processing: 34, failed: 2, documents: [{ document_id, name, state, error_code, chunk_count, expires_at }] } 6. Ask a streaming multi-turn question POST /v1/sessions/{sid}/conversations/{cid}/messages Headers: Idempotency-Key: <uuid> Body: { text, coverage: "ready_subset" | "require_all" } -> 200 text/event-stream event: meta { message_id, corpus_generation: 17, docs_searched: 164, docs_pending: 34 } event: token { text: "..." } event: citations [{ document_id, doc_name, page_or_row, chunk_id }] event: done { input_tokens, output_tokens, ttft_ms, total_ms, degraded: false } -> 409 CORPUS_NOT_READY (when coverage == "require_all" and ready < total or failed > 0) -> 410 SESSION_EXPIRED (past 24-hour boundary) -> 429 RATE_LIMITED Retry-After: 2- Presigned URLs (short-lived cryptographic URLs signed by our backend that let the browser
PUTbytes straight into object storage with hard size/hash constraints) keep hundreds of megabytes out of API gateway memory. Idempotency-Keyensures a browser retrying after a brief Wi-Fi drop reconnects to the exact samemessage_idanswer rather than billing a duplicate LLM generation.
- Presigned URLs (short-lived cryptographic URLs signed by our backend that let the browser
Data model and per-document state machine
sessions session_id PK, tenant_id, owner_user_id, created_at, expires_at, corpus_generation INT, total_doc_count, ready_doc_count, failed_doc_count, total_bytes documents document_id PK, session_id, name, content_type, size_bytes, sha256, object_key, state, attempt_count, error_code, parser_version, embed_model_version, page_count, chunk_count, ready_generation NULL, uploaded_at, ready_at, expires_at INDEX (session_id, state) corpus_generations (session_id, generation) PK, ready_document_ids_bitmap, min_doc_expires_at, created_at chunks -- Partitioned in memory by hash(session_id) chunk_id PK = sha256(document_id, parser_version, chunk_ordinal), session_id, document_id, page_or_row_range, text, vector, expires_at conversations conversation_id PK, session_id, rolling_summary, turn_count, updated_at messages message_id PK (= Idempotency-Key), conversation_id, role, text, corpus_generation, citations_json, ttft_ms, total_ms, degraded_flagPer-document lifecycle (never tracked as a single coarse session boolean)
UPLOAD_PENDING --> UPLOADED --> PARSING --> PARSED --> EMBEDDING --> READY (published in generation G) | | | | +--(URL TTL expired)---------+----------+-----------+--> FAILED (explicit error_code after 3 tries)READYis atomic per document: While a 200-page PDF is inEMBEDDINGwith 90 of its 200 chunks written, queries see zero chunks of that PDF until all 200 chunks are confirmed searchable and published in a newcorpus_generation.- Deterministic
chunk_idmakes retries overwrite the exact same chunk keys via upsert rather than inserting duplicate chunks that would skew retrieval rankings. - Abandoned uploads cannot hang
require_allforever: If a file staysUPLOAD_PENDINGpast its 10-minute upload URL expiry, a sweeper marks itFAILED (UPLOAD_EXPIRED)so the user sees which file needs re-uploading.
High-level architecture
+--- Direct PUT (<= 500 MB) ---> [ Object Storage (24h prefix) ] | | Client Browser ---------+ object-created event | | v | HTTPS / SSE +--> [ Stateless API Gateway ] [ Per-Session Fair Queue ] v | | | (Auth, SSE stream) :prepare / :corpus | query +-----+------+ v v v v [ Metadata DB ] <---+--- [ CPU Parse Pool ] [ OCR Pool ] (sessions, docs, | (PDF/DOCX/CSV) (scanned) generations) | \ / | v v | [ Batch Embedding GPU Pool ] | (model v3, high throughput) | | v v upsert, then bump generation [ Query Service ] -----> [ Session-Sharded Vector + BM25 ] | | | (in-RAM exact scan per session) +--------------------------+ | +------------------------+ v v v [ Low-Latency Query Embed ] [ Scoped Retrieval/Answer ] [ Quota Manager (Token Buckets) ] (model v3, micro-batched) (keyed by gen + expires_at) (70% floor for interactive) | v [ Multi-Region LLM Providers ]Deep dive 1: Format-aware idempotent ingestion and corpus generations
A critical distinction governs correctness here: completing file uploads does not mean all 200 files are searchable.
1. Format-aware streaming parsers (PDF, DOCX, TXT, and CSV)
Workers stream byte ranges from object storage without loading entire 500 MB archives at once, and tailor chunking to each file type: -
PDF/DOCX/TXT: Split into ~500-token chunks with ~50-token overlap while prepending the document title and current section heading ("msa_draft.pdf > Section 4.2 Termination: ...") and recording page numbers. Pages with near-zero extractable text are routed to the isolated OCR worker pool so one 300-page scanned PDF cannot stall fast digital files. -CSVtables: Naive 500-token character slicing cuts rows in half and strips column names from chunks 2..N, making rows like42, 19.5, "Pending"unsearchable! Instead, the CSV parser groups complete rows (~25–40 rows per chunk) and prepends the column header row and filename to every single chunk (plus generates one table-summary chunk listing column names, types, and row counts).2. Idempotent stages, poison-pill isolation, and session-fair queuing
- Queue messages hold only
(session_id, document_id, stage, attempt). Workers claim leases and advance state via conditional SQL (UPDATE documents SET state='EMBEDDING' WHERE document_id=? AND state='PARSED'). - Provider
HTTP 429throttling returns the job to a delayed queue without incrementingattempt_count. Parser crashes or timeouts incrementattempt_countand move poison files toFAILEDon attempt 3; deterministic errors (ENCRYPTED_PDF,CORRUPT_ARCHIVE) fail immediately on attempt 1. - Instead of a global FIFO queue where one 200-file upload starves 50 single-file users, the dispatcher round-robins across active sessions (capping each session at e.g. 4 concurrent document jobs) and schedules smallest files first within each session so users can start chatting within seconds.
3. Atomic
corpus_generationsnapshots- Embedding worker upserts all chunks of
doc_kand waits for shard read-your-writes confirmation. - Inside one DB transaction:
SELECT ... FOR UPDATEon thesessionsrow (serializing concurrent document completions in the same session), setdoc_k.state = 'READY', incrementcorpus_generation(17 -> 18), and insertcorpus_generations(s_id, 18, prev_bitmap + doc_k, min_expires_at). - Every query reads
corpus_generationonce at start and filtersdocument_id IN gen_18_docs AND expires_at > now. Half-embedded files are completely invisible, and a query may claim full 200-document coverage only whenready_doc_count == total_doc_count AND failed_doc_count == 0.
- Queue messages hold only
Deep dive 2: Budgeting TTFT (< 500 ms), total latency (< 3 s), and validating feasibility
1. Critical-path p95 TTFT budget (
< 500 msat gateway)Critical-Path Stage p95 Budget Engineering Mechanism --------------------------------------------------- ----------- ---------------------------------------------- 1. Auth, session & corpus_generation read 15 ms In-memory session cache + fast expiry check 2. Quota admission (token reservation) 5 ms Local shard token bucket check 3. Multi-turn pronoun check / fast query rewrite 0 - 5 ms Tiny classifier checks if turn has pronouns; avoids 150 ms LLM call on standalone questions! 4. Query embedding 25 ms Dedicated low-latency GPU pool (same model v3) 5. Hybrid retrieval (exact vector + BM25 keyword) 20 ms Single-session RAM partition (<= 41 MB scan) 6. Lightweight cross-encoder rerank (top 40 -> 8) 50 ms Distilled FP16 reranker on query GPU pool 7. Prompt assembly (system + summary + 8 chunks) 10 ms Prompt ordered for provider prefix caching 8. LLM provider queueing + ~5,000-token prefill ~300 ms Dominant external item — MUST be benchmarked! 9. First answer token flushed over SSE 20 ms Same-region keep-alive HTTP/2 connection pool --------------------------------------------------- ----------- ---------------------------------------------- Total sum of p95 budgets ~450 ms (Leaves ~50 ms slack; no room for extra LLM hop!)Look at what this budget proves immediately: - You cannot put a 150–250 ms LLM query-rewrite call unconditionally on the critical path! For follow-up turns (
"What is its termination fee?"), a< 5 mslightweight token classifier detects coreference (its,the second one,that table). Only when triggered do we run a tiny fast rewrite model (~80 ms) while skipping the 50 ms reranker (or searching raw + last-turn entities in parallel) to stay inside 500 ms. - Provider prefill (~300 ms) dominates: If load testing against the real provider region shows 5,000-token prefill already takes 420 ms at p95,< 500 msis physically unreachable without shrinking context (e.g., 6 chunks = ~3,500 tokens), using provisioned throughput, or picking a faster model tier.2. Total response time (
< 3,000 ms) and honest SLA validationtotal_time_ms = ttft_ms + (output_tokens / decode_tokens_per_s) * 1000 Example at 500 ms TTFT and 80 tokens/s decode speed: 2,500 ms remaining * 80 tokens/s = 200 output tokens maximum!A 600-token detailed table takes
500 ms + 7,500 ms = 8.0 secondseven on a perfectly healthy cluster. Therefore: - Default prompts instruct concise cited answers (max_tokens = 200) with a UI "Expand details" button (tracked under an extended-response SLA), and dashboards segment p50/p95/p99 total time by output-length bucket (<= 200,201–500,> 500tokens). - Before promising capacity, we replay Poisson-distributed multi-turn workloads at rising QPS against the real provider deployment to find the throughput knee where p95 TTFT crosses 500 ms—and always displayHTTP 429shed rate anddegraded: truerate right beside latency percentiles so load shedding never fakes a green SLA.Deep dive 3: Safe cache identity and strict 24-hour expiry
In multi-turn session RAG, an answer is a deterministic function of six inputs—omitting any one serves wrong, stale, or leaked data:
cache_identity = ( tenant_id, user_authz_epoch, -- prevents cross-tenant or post-revocation leaks session_id, corpus_generation, -- prevents serving a 10-doc answer after 200 docs finish! conversation_context_hash, -- prevents mixing up "it" / "that clause" across turns! question_representation, model_id, prompt_ver, retrieval_ver, generation_params_hash -- temperature, max_tokens, coverage mode )Four cache tiers (from highest value-to-risk to lowest)
- Provider KV prompt-prefix cache: Structure prompts with static parts first (
[System instructions] -> [Rolling conversation summary] -> [Retrieved chunks] -> [Latest user question]) so multi-turn chats reuse prefix compute inside the provider's own KV cache. - Query embedding cache
(tenant_id, embed_model_ver, normalized_question): Saves ~25 ms; tenant-scoped so hit timing never leaks another customer's questions. - Session retrieval cache
(session_id, corpus_generation, query_vec_hash, retrieval_ver): Automatically misses the instant document #165 bumpscorpus_generationfrom 17 to 18. - Answer cache (exact & intra-session semantic): Cross-session semantic reuse is forbidden because every session's 200-doc corpus is private. Within the same
(session_id, corpus_generation), semantic reuse is safe only if: (a) the turn is standalone (no pronouns/ellipsis) orconversation_context_hashmatches identically, and (b) similarity exceeds a high-precision threshold plus exact match on extracted numbers, dates, and named entities (so"H1 rate"never returns cached"H2 rate"). Explicit user"Regenerate"clicks bypass answer caches.
Leak-proof 24-hour expiration
- Write-time cap: Every cache entry sets
expires_at = min(corpus_generation.min_doc_expires_at, now + 1h), ensuring no cached answer can outlive the earliest-expiring document in the snapshot that produced it. - Read-time gate: Cache hits still verify
now < entry.expires_atandnow < session.expires_atbefore returning a single byte, eliminating lazy-eviction races. - Active 24-hour purge: A scheduled expiry worker deletes the session's Redis key prefix, drops its in-memory vector/BM25 partition, and issues batch
DeleteObjectson its object-storage prefix right at 24h (relying on S3 lifecycle rules strictly as a backstop, since cloud lifecycle sweeps often lag by hours).
- Provider KV prompt-prefix cache: Structure prompts with static parts first (
Deep dive 4: Quota isolation, 429 handling, and visible degradation
1. Hard wall between ingestion traffic and interactive queries
- Separate embedding pools, identical model version: Batch ingestion embeddings run on high-throughput batch GPUs, while interactive query embeddings run on a dedicated, low-utilization GPU pool running the exact same
embed_model_version(so vector spaces match 100% while a 200-file upload never adds 1 ms to query embedding). - Tiered LLM token buckets: If embeddings or background summarization share a provider account with interactive chat, the Quota Manager enforces strict class budgets:
Traffic Class Quota Allocation Behavior When Budget Depletes --------------------- ----------------------------------- ------------------------------------------------- Interactive Chat 70% reserved TPM/RPM floor + unused Queue <= 50 ms -> compact degrade -> explicit 429 Background Summaries Borrows idle tokens in tiny slices Preempted within 1-2 s when interactive rises Ingestion Embeddings Dedicated GPU pool or separate acct Pauses queue consumers; docs stay in EMBEDDING- Reservation + fairness: After prompt assembly, Query Service reserves
exact_input_tokens + max_tokensfrom its tenant's weighted token bucket (capping each session at<= 2concurrent streams) and refundsmax_tokens - actual_output_tokenswhen streaming completes.
2. Provider HTTP 429 handling and visible degradation ladder
- On
HTTP 429, honorRetry-After(plus random full jitter[0, backoff]and AIMD—cutting the local bucket rate by 30% and ramping back slowly) so workers never hammer a throttled deployment in lockstep. - Interactive retry rule: Never use speculative hedging (sending duplicate requests wastes 2x quota!). Allow at most 1 failover retry to a secondary regional deployment only if
< 150 mshas elapsed so the 500 ms TTFT budget remains reachable. - Visible degradation ladder: When interactive quota runs tight:
- Hold in a tiny bounded admission queue (
<= 50 ms). - Switch to compact mode (
4chunks instead of8, or a faster small model tier) while settingdegraded: truein thedoneevent and UI badge. - Return
HTTP 429withRetry-Afterimmediately rather than queueing for 10 seconds and quietly missing< 500 ms.
- Hold in a tiny bounded admission queue (
- Ingestion backpressure: Bound the ingestion backlog by estimated pages and tokens, not file count. When estimated time-to-ready exceeds 15 minutes, warn in
:prepare; above the hard ceiling, return503 Retry-Afterper tenant so worker queues never blow up.
- Separate embedding pools, identical model version: Batch ingestion embeddings run on high-throughput batch GPUs, while interactive query embeddings run on a dedicated, low-utilization GPU pool running the exact same
Scaling, failure handling, and trade-off summary
Horizontal scaling summary
- Stateless API Gateways & Query Service: ~3,000 open SSE streams at 1,000 QPS easily run on 6–10 async gateway pods.
- Session-sharded Vector + BM25 Store: ~900 GB total live state (
600 GBvectors +300 GBtext/postings) across 100,000 sessions fits comfortably in RAM across 10 shards x 2 replicas of 128 GB nodes, routing each session byhash(session_id)for sub-5 ms local hybrid search and instant 24h partition eviction. - Parse, OCR, and Batch Embed Workers: Autoscale independently on page/token backlog metrics.
Failure handling summary
Failure Mode System Behavior ------------------------------------ ---------------------------------------------------------------------- Parse or embed worker crashes Visibility lease expires; another worker reruns stage; deterministic `chunk_id` upserts + conditional state updates prevent duplicates. Encrypted / corrupt / 2,000-page PDF Marked `FAILED` with clear `error_code`; `require_all` refuses to lie that all 200 docs were searched until user removes or replaces file. Embedding spike or outage New docs remain `EMBEDDING`; interactive queries keep serving at <500ms on current `corpus_generation` with explicit partial-coverage notice. Client disconnects mid-SSE stream Generation finishes and saves under `message_id` (`Idempotency-Key`) so reconnecting replays the answer; explicit UI "Stop" cancels stream early. 24-hour document or session expiry Query read filter (`expires_at > now`) + cache read check block access at the exact second; background sweeper drops cache, vectors, and blobs.
Intuition & how it works
Think of this system like a legal war-room where back-room paralegals unpack 200 boxes of evidence while a lead attorney answers live rapid-fire questions at the conference table. Heavy delivery trucks never carry boxes through the front reception lobby—instead, clients drop files straight at the loading dock (presigned direct-to-storage PUT URLs). In the back room, workers parse text, preserve CSV table headers, compute vector embeddings, and publish numbered catalog editions (corpus_generation snapshots): until every page of Document #165 is shelved, live answers read Edition #17 so half-indexed files never corrupt search results, while clearly telling the user "164 of 200 files ready." At the conference table, the attorney keeps only this room's 200-file binder right on the desk in RAM (per-session partitioned exact search taking ~2 ms) and uses a dedicated phone line (isolated interactive quota floor + dedicated query-embedding GPUs) so a 200-box delivery in the back room never delays the TTFT (Time To First Token)—the milliseconds until the first answer word appears—past 500 ms.
Why do naive architectures fail? Uploading and parsing hundreds of megabytes inside web gateways exhausts server RAM on just a handful of concurrent uploads, while treating "upload finished" as "searchable" causes early questions to silently miss 90% of the files. Sharing one undifferentiated provider quota between background ingestion (~156M tokens/min at peak) and live chats triggers HTTP 429 (Too Many Requests) storms that stall interactive users. Finally, putting an unbudgeted LLM query-rewrite call on every turn blows the 500 ms TTFT budget before generation even starts, and caching answers by question text alone leaks expired 24-hour data or mixes up follow-up pronouns like "What is the penalty in it?"
Let's trace a concrete 4-step lifecycle for workspace ws_704 uploading 3 representative files (msa_draft.pdf, rate_card.csv, and scanned_exhibit.pdf):
1. Direct upload & format-aware async ingestion (t = 0s .. 12s):
`:prepare` validates <= 200 files and <= 500 MB, returning 3 presigned object-storage PUT URLs.
- `msa_draft.pdf` & `rate_card.csv` finish fast on the CPU pool (`rate_card.csv` prepends its header row
to every row-batch chunk!) -> atomically publish `corpus_generation = 2` (2 ready, 1 processing).
- `scanned_exhibit.pdf` routes to the isolated OCR pool so it never blocks text files.
2. Partial-corpus query within the < 500 ms TTFT budget (t = 15s):
User asks: "What is the H1 unit rate?" with `coverage = "ready_subset"`.
- Query Service pins `corpus_generation = 2`, embeds the query on the dedicated low-latency GPU pool (25ms),
scans `ws_704`'s tiny in-RAM partition filtered to generation 2 (2ms), streams `meta: {docs_searched: 2,
docs_pending: 1}`, and flushes the first answer token at ~410 ms (< 500 ms TTFT, ~1.8 s total for 110 tokens).
3. Corpus update + context-dependent follow-up turn (t = 35s):
`scanned_exhibit.pdf` finishes -> publishes `corpus_generation = 3` (generation-2 retrieval cache auto-misses!).
User asks: "And for H2?" -> fast < 5 ms coreference check spots ellipsis, runs a compact 80 ms rewrite
("H2 unit rate") while skipping the 50 ms reranker, and semantic cache refuses to reuse the H1 answer
because both `corpus_generation` (3 != 2) and extracted half-year entity (`H2` != `H1`) changed.
4. Strict 24-hour expiration (t = 24h 00m 00s):
Read checks (`now < expires_at`) immediately block `ws_704` queries (`410 SESSION_EXPIRED`) and any cached
entries at the exact second, while the expiry worker drops `ws_704`'s cache prefix, RAM vector shard, and blobs.
Key trade-offs
- Answering on
ready_subsetvs. blocking forrequire_all: Answering immediately over ready documents makes the session feel responsive seconds after upload, at the risk of missing facts still inPARSINGorEMBEDDING. Exposing explicitmetacoverage counts (164 of 200 ready) alongside an opt-inrequire_allmode gives both speed and completeness without ever silently returning partial results. - Transactional
corpus_generationsnapshots vs. reading raw index writes live: Incrementingcorpus_generationonce per finished document adds one lightweight row-locked DB update per file, in exchange for preventing half-embedded PDFs from skewing rankings and giving retrieval/answer caches an exact, self-invalidating version key. - Per-session in-RAM exact search vs. one global approximate (ANN) index: Because 200 documents (~10,000 chunks) occupy at most ~41 MB of float32 vectors (~6 MB for an average 30-doc session), scanning one session's contiguous partition in RAM takes ~0.5–2 ms with 100% recall and O(1) partition deletion at 24 hours, trading modest per-session metadata overhead to avoid global filtered-HNSW recall drops and expensive per-vector deletes.
- Self-hosted split GPU pools for embeddings vs. shared provider API: Running ~12–18 A100-class GPUs for batch ingestion plus a small dedicated pool of the exact same model version for 25 ms query embeddings requires GPU ops, but completely insulates interactive LLM quotas from 200-document upload spikes.
- Conditional query rewrite + bounded
max_tokensvs. unconstrained multi-call chains: Skipping LLM query rewriting on standalone questions (via a< 5 msclassifier) and capping default answers around ~200 tokens (with an explicit "Expand" button) keeps< 500 msTTFT and< 3 stotal latency physically achievable, trading multi-page prose by default for snappy interactive turns. - Six-part cache identity vs. naive semantic cache hit rate: Binding cache keys to
(tenant, authz, session_id, corpus_generation, conversation_hash, entities)yields far fewer semantic cache hits than matching raw question vectors globally, which is essential because a wrong-turn, stale-generation, or cross-session answer is a severe correctness and privacy bug—making provider KV prompt-prefix caching and retrieval caching higher-ROI wins. - Reserved interactive quota floor (e.g., 70% TPM) + visible
429/degradedflags vs. deep hidden queues: Holding a reserved floor leaves small idle headroom during lulls (mitigated by letting background tasks borrow in tiny 1-batch slices), and returning fast429 Retry-Afterordegraded: truelooks harsher than silent queueing—but prevents retry avalanches and keeps latency dashboards honest.
Common mistakes
- Streaming or parsing uploads inside the API gateway: A few concurrent 300 MB PDF/DOCX uploads blow out gateway heap memory and starve SSE chat sockets; always use size-bounded presigned object-storage URLs and async workers.
- Equating "100,000 active sessions" with "100,000 simultaneous LLM requests": Confuses 24-hour session state with in-flight request concurrency (
arrival_rate x latency), leading to wildly wrong server and quota math. - Slicing CSV files into raw character chunks without headers: Leaves chunks 2..N as meaningless comma-separated numbers without column names and splits rows mid-line.
- Non-deterministic chunk IDs on worker retries: Generating random UUIDs per embedding attempt inserts duplicate chunks after a worker crash and corrupts top-k retrieval diversity.
- Claiming
< 500 msTTFT and< 3 stotal without stage, percentile, or token bounds: Counting a dummy"thinking..."SSE packet as TTFT, quoting averages instead of p95, adding an unbudgeted 200 ms LLM query-rewrite hop, or promising< 3 son 800-token outputs that take 10 seconds to decode. - Keying semantic caches only by question embedding: Serves incomplete generation-1 answers after generation-200 finishes, confuses pronouns across conversation turns, conflates
"H1"with"H2", or leaks answers across sessions. - Relying solely on cloud object-storage lifecycle policies or lazy cache TTLs for 24-hour expiry: S3/GCS lifecycle sweeps run asynchronously once a day, and lazy cache eviction can serve expired items unless read paths explicitly check
now < expires_atalongside active 24h purges. - Hiding load-shed (
429) or degraded responses when reporting latency SLAs: Dropping half of user traffic makes p95 latency look fast on paper while users experience errors.
Follow-up questions
- How do you guarantee cached retrieval results or responses stop serving the moment a session's 24-hour file window closes? Every cached retrieval or answer entry must become unreadable the exact instant its underlying documents cross the 24-hour cutoff. At write time, each cache record sets
expires_at = min(earliest expires_at among documents in its corpus_generation, created_at + 1h)so its TTL never outlives any contributing file, and at read time the Query Service explicitly checksnow < entry.expires_atandnow < session.expires_atso lazy eviction never serves a stale hit even 10 milliseconds past hour 24. Behind that read gate, an active expiration job deletes the session's entire cache prefix, drops its in-memory vector/BM25 partition, and batch-deletes its raw object-storage prefix on schedule instead of waiting on delayed storage lifecycle sweeps. - Why might two nearly identical user prompts inside the same session demand completely different answers on later turns? Surface phrasing alone does not determine intent: in Turn 2 while discussing
msa_draft.pdf, "What is the termination notice period?" targets that agreement, whereas in Turn 6 after pivoting to an addendum, the identical words refer to the addendum! Even standalone questions change answers within one session once background workers finish indexing additional uploads (advancingcorpus_generationfrom 50 to 200 files), when user permissions change, or when two close embeddings differ in a crucial date or period ("H1 rate" vs. "H2 rate"). Safe caching must therefore bindsession_id,corpus_generation,conversation_context_hash(unless verified standalone), and exact extracted entities/dates/numbers rather than relying on vector similarity alone. - How do you prevent a sudden wave of 200-file uploads from starving live chat traffic of embedding and LLM capacity? Separate the two workloads across dedicated capacity pools instead of mixing them in one priority queue: run batch document embeddings on a throughput-oriented GPU pool and interactive query embeddings on a dedicated, low-utilization GPU pool running the exact same embedding model version (
< 25 ms), keeping upload spikes completely off interactive LLM quotas and query latency paths. Where traffic must share an upstream provider account, the Quota Manager enforces a hard interactive floor (such as 70% of TPM/RPM), allows background jobs to borrow idle tokens only in tiny single-batch leases that yield within seconds when live chat load climbs, and applies per-session fair queuing plus AIMD backoff on429s so large uploads simply wait inEMBEDDINGwhile live chats stay fast.
Follow-up questions
- How do you guarantee cached retrieval results or responses stop serving the moment a session's 24-hour file window closes?
- Why might two nearly identical user prompts inside the same session demand completely different answers on later turns?
- How do you prevent a sudden wave of 200-file uploads from starving live chat traffic of embedding and LLM capacity?
Similar questions
- Quota-Aware LLM Pipeline Dispatch and Checkpoint Recovery
- Million-Service Internal Notification Platform
- Multi-Tenant and Session Isolation for Tool-Using RAG Agents
- Lifecycle Design for 24-Hour RAG Erasure, 7-Day Chats, and Audits
- Crash Recovery for DAG Workflows with Side Effects and Multi-Day Waits
- Architecting Multi-Tenant Workflows Across Fast I/O and Slow LLM Tasks
More Qualified Health interview questions
- Quota-Aware LLM Pipeline Dispatch and Checkpoint Recovery Hard
- Multi-Tenant and Session Isolation for Tool-Using RAG Agents Hard
- Lifecycle Design for 24-Hour RAG Erasure, 7-Day Chats, and Audits Hard Pro
- Crash Recovery for DAG Workflows with Side Effects and Multi-Day Waits Hard Pro
- Architecting Multi-Tenant Workflows Across Fast I/O and Slow LLM Tasks Hard Pro
- Decoupling Live LLM Token Streams from Validated DAG Commits Hard Pro
- Safe Cancellation and Crash Recovery for Streaming Tool-Using Agents Hard Pro
- Cycle Validation and Durable Runtime Bounds for Editable Workflow DAGs Hard Pro
- Million-Service Internal Notification Platform Medium Pro