Slides · Production: cost, serving and observability
Production deployment of RAG
1 / 30
Production deployment of RAG
The knowledge base still held yesterday’s delivery cut-off. Who was supposed to tell it? This lesson is about the system around the model that answers that question.
Concept
A prototype answers; a service stays right
- A prototype is four steps: embed, retrieve, prompt, answer.
- A production system adds what keeps those steps correct, fast, affordable, secure and changeable while users and documents keep moving.
- Many failures here are not model failures: a stale index, a changed embedder, a creeping latency, a doubled bill.
- One experience report on three RAG case studies lists seven failure points and concludes that validation is only really possible while the system runs, and that robustness is something that develops as the system runs, not something fully fixed at design time.
- So in an interview, say the trade-off at every box on the whiteboard.
Numbers in this deck are illustrative unless a source is cited. State your assumptions out loud.
Source[1] Seven Failure Points When Engineering a Retrieval Augmented Generation System
Diagram
Two rooms that share one index
- Read path: needs speed and access control.
- Write path: needs correctness, freshness and versioning.
Diagram
Reference architecture, part 1: the front door
Tracing, metrics and logs watch every box. The orchestrator is stateless, so it scales on request rate.
Diagram
Reference architecture, part 2: retrieve and answer
Compare
Every box has a typical failure
| Component | Typical failure | Trade-off to say aloud |
|---|---|---|
| API gateway | Rate limit set wrongly, so valid users are refused | Protection against abuse versus refused traffic |
| Input guardrails | Add latency, or block valid input | Safety versus speed and false blocks |
| Cache | Serves a stale or another tenant’s answer | Cost and latency saved versus correctness risk |
| Retriever | Misses the right chunk, or leaks a restricted one | Recall versus access control and speed |
| Reranker | Slow, or reorders badly | Ordering quality versus latency and GPU cost |
| LLM gateway | Provider times out | Fallback quality versus availability |
| Output guardrails | Conflict with streaming | Safety versus time to first token |
Compare
You cannot stream text you have not checked
Tokens appear on screen as they are generated, so a check that finishes later cannot stop them. Three designs:
| Design | First token | Risk | Fits when |
|---|---|---|---|
| Check first, then show | Late: the whole answer is generated first | None shown unchecked | High-stakes answers, short outputs |
| Stream first, check after | Early | Unchecked text is already visible | Low-stakes chat |
| Check in chunks | Early for the first chunk | A small window of unchecked text | Middle ground with a chunk-level checker |
The right choice depends on the cost of showing one bad sentence.
Check yourself
Check: which box is failing?
Name the most likely component for each symptom.
- At peak hour users get “too many requests” while the LLM provider’s usage dashboard is low.
- First-token time is fine, except for queries that bring back about 200 candidates before the final context is built.
- An answer quotes a policy page that the asking user cannot open.
Answer
- The API gateway: its rate limit is set below what real traffic needs, and the provider is not the bottleneck.
- The reranker: its work grows with the number of candidates, so cutting candidates or using a smaller reranker are the levers.
- The retriever’s access filter (or stale permission metadata in the index): permissions must be enforced where chunks are fetched, not by the prompt.
Diagram
The write path, part 1: from change to chunks
Diagram
The write path, part 2: from chunks to a live index
Compare
Four properties the pipeline must have
| Property | How | What breaks without it |
|---|---|---|
| Idempotent | Chunk ids come from content hashes, so a retry produces the same ids | Retries duplicate chunks |
| Incremental | Only changed documents are reprocessed | Cost and lag grow with corpus size |
| Delete-aware | Removed or revoked documents leave the index, and a tombstone with the source version stops a late, older event from bringing them back | Withdrawn text keeps being retrieved |
| Versioned | Embedding model and chunker version are stored on every chunk, and each document keeps the source version of the last event applied | You cannot tell which chunks need rebuilding, and a replayed old event overwrites newer content or permissions |
Change detection matters too: a periodic full crawl by itself adds staleness equal to its interval, and it only notices disappearances if it compares the crawl listing with what the index holds.
Code
Deterministic ids, source versions and tombstones
Python
def chunk_ids(doc_id, paragraphs, chunker_v, embed_model):
seen, out = {}, []
for text in paragraphs:
n = seen.get(text, 0) # n-th copy of identical text in this doc
seen[text] = n + 1
blob = json.dumps([doc_id, chunker_v, embed_model, n, text],
separators=(",", ":")) # unambiguous field boundaries
out.append((hashlib.sha256(blob.encode()).hexdigest()[:32], text))
return out
def upsert(index, doc_id, version, paragraphs, acl):
state = index.docs.get(doc_id) # {"version": int, "deleted": bool}
if state and version <= state["version"]:
return "ignored" # replayed or out-of-order event
wanted = chunk_ids(doc_id, paragraphs, CHUNKER_V, index.embed_model)
for cid, text in wanted:
if cid not in index.chunks: # unchanged chunks are not re-embedded
index.embed_and_store(cid, doc_id, text, acl)
else:
index.chunks[cid]["acl"] = set(acl)
index.drop_chunks_of(doc_id, except_ids={c for c, _ in wanted})
index.docs[doc_id] = {"version": version, "deleted": False} # recorded last
def delete(index, doc_id, version):
state = index.docs.get(doc_id)
if state and version <= state["version"]:
return "ignored"
index.drop_chunks_of(doc_id, except_ids=set())
index.docs[doc_id] = {"version": version, "deleted": True} # the tombstoneThis is a condensed view: embed_and_store and drop_chunks_of stand for a few lines each. The source version is a per-document number that only grows, such as a revision number or event timestamp. These tests run against an in-memory stand-in for an index (not a real vector database):
| Test | Result |
|---|---|
| 1. Replay of the same event: ignored, same ids, no re-embedding | pass |
| 2. Edit at v2: one new embedding, old text gone | pass |
| 3. Late v1 event after v2: ignored, old text does not return | pass |
| 4. Revoke at v3: the old group loses access | pass |
| 5. Late replay of the earlier grant (v2): access stays revoked | pass |
| 6. Delete at v4: nothing retrievable, tombstone kept | pass |
| 7. Late upsert (v3) after the delete: document stays deleted | pass |
| 8. Late duplicate delete: ignored | pass |
| 9. Newer upsert (v5) after the delete: document is re-created | pass |
| 10. Crash mid-way, retry: same final state as a clean run | pass |
| 11. Two identical paragraphs in one document keep separate ids | pass |
| 12. New embedding model gives disjoint ids | pass |
| 13. Fields containing separator-like characters cannot collide | pass |
With the version check removed, 5 of the 13 tests fail (numbers 1, 3, 5, 7 and 8), so these tests do catch the bug. Because the id includes the text, any edit re-embeds that chunk, and an inserted paragraph does not shift the other ids. Ids are 128 bits of the hash: a 64-bit id would have a collision chance of about 7 in 100,000 across 50 million chunks (birthday estimate). These tests check sequential event order only; they do not show safety under concurrency. The version check is read-then-write, so in a real pipeline send all events for one document through one partition or worker (key the queue by document id), or write the version with compare-and-set. Ordering across different documents does not matter here. A crash in the middle of an edit leaves old and new chunks visible together until the retry completes.
Check yourself
Check: a worker dies halfway
A worker has embedded and stored 600 of a document’s 1,000 chunks when its machine is preempted. The job is retried from the start.
- What must be true of the chunk ids for the retry to be safe?
- How many chunks are embedded on the retry, and how many does the document have afterwards?
Answer
- The ids must be deterministic (derived from the content, chunker version and embedding model), so a chunk that is already stored is recognised as the same chunk.
- 400 embeddings happen on the retry, and the document ends with 1,000 chunks, the same as a clean run. With random ids the retry embeds all 1,000 again and, unless a reconciliation step removes the old ones, leaves duplicates.
Worked example
Worked example: a burst breaks the freshness promise
Promise: new documents are searchable within 10 minutes. Illustrative assumptions: normal arrivals 10 documents per minute; a 30-minute burst of 50 per minute; workers process 30 per minute; first in, first out.
| Step | Arithmetic | Result |
|---|---|---|
| Backlog growth during the burst | 50−30 | 20 documents per minute |
| Backlog at the end of the burst | 20×30 | 600 documents |
| Lag of the newest document at the end | 30600 | 20 minutes |
| When lag passes 10 minutes | 3020t=10 | t=15 minutes into the burst |
| Draining after the burst | 30−10=20 net per minute; 20600 | 30 minutes to empty |
| Lag back under 10 minutes | backlog must fall from 600 to 300: 20600−300 | 15 minutes after the burst ends |
The promise is broken from minute 15 to minute 45, which is 30 minutes. To keep the promise through this burst, workers need w with w(50−w)×30≤10, so w≥37.5 per minute (check: at 37.5 the backlog is 375 and the lag 10 minutes; at 40 it is 300 and 7.5 minutes). If arrivals stayed above worker capacity indefinitely, the backlog would grow without limit. Autoscale ingestion workers on queue depth, and alert on ingestion lag against the promise.
Diagram
Re-embedding with zero downtime
Documents and queries must share one embedding model, so the query side reads its embedding model from whichever version the alias points to, and moves with it.
Code
What the swap looks like
Elasticsearch shows one concrete form of this pattern (index names here are made up):
JSON
POST _aliases
{
"actions": [
{ "remove": { "index": "kb-v1", "alias": "kb-live" } },
{ "add": { "index": "kb-v2", "alias": "kb-live" } }
]
}- Elastic’s aliases page says several actions can run in a single atomic operation, and its own swap example (between two data streams) states that the alias never points to both at once.
- The update-aliases API accepts an index or a data stream in
addandremove. - Atomic is not the same as safe against a typo: the docs warn that when some actions in the list succeed and others fail, the outcome may not be what you want, and suggest setting
must_existso that one failing action fails the whole list. - Rollback is the same request with the names swapped.
- Other vector databases have their own alias or collection-swap feature; read yours before relying on atomicity.
Sources[2] Aliases[3] Create or update aliases (Elasticsearch API reference)
Compare
Spend a latency budget per stage
Illustrative target: p95 of about 3 s to first token, with streaming.
| Stage | Budget (s) | Main lever |
|---|---|---|
| Guardrails and query transform | 0.40 | Skip when unneeded, use a small model |
| Retrieval (dense and keyword in parallel) | 0.15 | Index tuning, regional replicas |
| Rerank | 0.35 | Smaller reranker, fewer candidates, GPU batching |
| Context building | 0.05 | Efficient dedupe and trimming |
| LLM time to first token | 1.60 | Faster model, shorter prompt, prompt caching |
| Network and queueing slack | 0.45 | Regional deployment, connection reuse |
| Total | 3.00 |
0.40+0.15+0.35+0.05+1.60+0.45=3.00. Treat the table as a plan, then measure the real end-to-end p95.
Worked example
Worked example: stage percentiles do not add up
Monitoring guidance agrees that percentile values are not safe to average: Prometheus says averaging precomputed quantiles gives statistically meaningless numbers, and aggregates buckets instead. That page is about aggregating across instances; applying the same reasoning to summing per-stage p95s is this course’s inference. A simulation (illustrative; 200,000 simulated requests, fixed seed) with six stages whose p95 values are 0.30, 0.20, 0.50, 0.10, 1.20 and 0.20 s, summing to 2.50 s:
| Assumption about the stages | p95 of the whole request | Compared with the 2.50 s sum |
|---|---|---|
| Independent, each with a typical long-tailed shape | about 1.91 s | Sum is too pessimistic |
| All slow together (one shared cause, e.g. load) | about 2.50 s | Sum is about right |
| Two stages, each 0.1 s but 1.0 s on a different 4 percent of requests | 1.1 s | Sum of p95s is 0.2 s, far too optimistic |
In the last row each stage has p95 0.1 s, because only 4 percent of its requests are slow, yet 8 percent of all requests hit one slow stage. Real systems fall anywhere in this range, so the sum neither proves nor disproves a target. Measure the end-to-end p95 and use the table to find where to spend effort.
Check yourself
Check: parallel retrieval in the budget
Dense search has a p95 of 0.30 s and keyword search a p95 of 0.12 s. Both run in parallel and the results are merged.
- What retrieval line would you put in the budget, and what would it be if they ran one after the other?
- Why is “the larger p95, so 0.30 s” still not guaranteed?
Answer
- About 0.30 s plus a small merge step in parallel, against a planning line (not the true p95) of 0.12+0.30=0.42 s in sequence, so parallelism saves about 0.12 s.
- A request finishes with the slower of the two, and the p95 of a maximum is at least the larger p95 (the two can be slow on different requests). It can be higher than 0.30 s, so measure the combined stage.
Worked example
Worked example: cost per query, and what a cache changes
Illustrative prices from the lessons: 2 dollars per million input tokens, 10 per million output. One request has a 4,096-token static prefix (system prompt, format rules, examples), 1,800 tokens of retrieved chunks, a 40-token question and a 250-token answer.
| Item | Arithmetic | Cost |
|---|---|---|
| Input without caching | 1,000,000(4,096+1,800+40)×2 with 4,096+1,800+40=5,936 tokens | $0.01187 |
| Output | 1,000,000250×10 | $0.00250 |
| Total | $0.01437 |
Prompt caching reuses an identical prefix. The Anthropic docs list cache reads at 0.1x the base input price for most models (some differ) and a 5-minute cache write at 1.25x. Assuming every request hits the cache:
- Prefix counts as 4,096×0.1=409.6 token-equivalents, so input is 409.6+1,840=2,249.6 token-equivalents = $0.00450.
- Total $0.00450 + $0.00250 = $0.00700, about 51 percent less. At 100,000 queries a day: $1,437 against $700.
- The chunks change per request, so they sit after the cached prefix and are billed normally.
- Break-even: the first request pays 1.25x for the prefix, so a single request costs more. Two requests inside the window cost 1.25+0.1=1.35 prefix-units against 2.00 without the cache, so it pays off from the second request.
Each model has a minimum cacheable length, and shorter prompts are processed without caching and without an error. The page lists minimums from 512 to 4,096 tokens, so a 4,096-token prefix is cacheable on every model it lists. A shorter prefix would not be on some. Anything that changes before the cache breakpoint, such as a timestamp, makes every request miss.
Source[5] Prompt caching
Concept
Four caches, four different risks
- Embedding cache: same text, same vector. Safe while the embedding model is fixed.
- Retrieval-result cache: same query and filters, same chunks. Must track document versions.
- Semantic cache: near-duplicate questions share an answer. Highest saving, highest risk.
- Provider prompt cache: reuses the static prompt prefix and does not change the output; the Anthropic docs say responses are the same with or without it.
A semantic cache must be partitioned by tenant and permissions, and each stored entry validated against document versions on every hit, or it can return a stale or wrong-user answer. The next lesson shows how to build and test that key.
Source[5] Prompt caching
Math
Sizing the vector layer: the arithmetic
raw bytes=Nvec×d×bHNSW bytes per vector=d×4+M×2×4(Faiss HNSW over float32 vectors)shards=⌈usable bytes per nodetotal bytes⌉replicas=⌈QPS per shard replicapeak QPS⌉| Symbol | Meaning |
|---|---|
| Nvec | Number of chunks embedded |
| d | Length of each embedding |
| b | 4 for float32, 1 for an 8-bit format |
| M | Links per vector in the HNSW graph |
| usable bytes per node | RAM you are willing to fill on one node (leave headroom) |
| QPS per shard replica | Queries per second one copy of one shard handles (measure it) |
The Faiss guidelines give the per-vector HNSW formula and note that a higher M is more accurate but uses more RAM. The first line is raw storage only; graph links, metadata and replicas come on top.
Worked example
Worked example: 50 million chunks
Illustrative inputs: 50,000,000 vectors, 384 dimensions, float32, M = 32, 32 GB usable RAM per node, peak 600 queries per second, 250 per second per shard replica.
| Quantity | Arithmetic | Result |
|---|---|---|
| Raw float32 | 50,000,000×384×4 | 76.8 GB |
| Raw at 1 byte per value | 50,000,000×384×1 | 19.2 GB |
| HNSW bytes per vector | 384×4+32×2×4=1,536+256 | 1,792 B |
| HNSW total | 50,000,000×1,792 | 89.6 GB |
| Shards (size only) | 3289.6=2.8, rounded up | 3, at about 29.9 GB each, 93 percent of usable RAM |
| Shards with headroom | 489.6 | 4, at 22.4 GB each, 70 percent of usable RAM |
| Replicas per shard | 250600=2.4, rounded up | 3 |
| Nodes | 4×3 (shards by replicas) | 12 |
When shards simply split one corpus by size, every query visits every shard, so each shard’s replicas must carry the whole query rate. Three shards would fit on paper but leave almost no room for metadata, growth or a rebuild, so plan four. Shard for size, replicate for query rate and availability. The 1-byte row shows why quantization is tempting; whether recall survives is an evaluation question.
Check yourself
Check: will it fit?
A team plans 25 million vectors of 1,536 dimensions in float32, on nodes with 64 GB usable RAM, using Faiss HNSW with M = 32.
- What is the raw size, and the size with the HNSW graph?
- How many shards, and how full is each?
Answer
- Raw: 25,000,000×1,536×4=153.6 GB. HNSW per vector: 1,536×4+32×2×4=6,144+256=6,400 bytes, so 160 GB in total.
- 64160=2.5, so 3 shards at about 53.3 GB each, about 83 percent of the RAM. That is tight once metadata and growth are added, so plan a fourth shard or compress.
Compare
Index choices trade memory, speed and recall
| Aspect | HNSW | IVF with product quantization |
|---|---|---|
| Memory | (d×4+M×2×4) bytes per vector, so RAM-hungry | Much smaller codes |
| Speed and recall knob | efSearch | nprobe, plus a rerank factor |
| Recall and speed | The Faiss guide calls it very fast and accurate when RAM is plentiful | Compression costs recall (see the data point below); the guide pairs it with a re-ranking stage |
| Fits | Plenty of RAM, or a small dataset | Memory-limited, very large corpora |
- Pinecone’s Faiss tutorial reports, on one dataset (Sift1M), about 98 percent less memory for plain PQ but roughly 50 percent recall against 100 percent for a flat index. Treat that as one data point, not a rule.
- Tune the recall target against latency with the knob, then re-check recall on your queries.
Sources[6] Guidelines to choose an index (Faiss wiki)[7] Product Quantization: Compressing high-dimensional vectors by 97%
Compare
Multi-tenancy: one index per tenant or one shared index
| Aspect | Separate collection or namespace per tenant | Shared index with a tenant filter |
|---|---|---|
| Isolation | Strongest | Depends on the filter being applied everywhere |
| Overhead | Each collection carries its own resource cost | Efficient for many small tenants |
| Operations | Larger footprint to run | One thing to run and tune |
| Typical risk | Cost and sprawl | Noisy neighbours, a filter bug leaking data |
- Qdrant’s guide says a separate collection per tenant is rarely the most efficient approach, since each collection carries its own overhead (and Qdrant Cloud caps collections per cluster). It offers a shared collection with a tenant field (payload partitioning) as one of several single-collection options, described as efficient for many small, similarly sized tenants, and reserves multiple collections for a limited number of tenants that need strict isolation.
- It also warns that requests without the tenant filter are slower, because they must scan across groups.
- The noisy-neighbour and filter-bug risks are design trade-offs from the lesson, not claims of that page.
Source[8] Multitenancy (Qdrant documentation, guide on multiple partitions)
Compare
Where it runs
| Topology | Fastest to | Main cost |
|---|---|---|
| Managed (hosted vector DB and LLM API) | Ship | Vendor lock-in, data-governance review |
| Self-hosted (Kubernetes, own GPUs) | Control, lower unit cost at scale | Operations burden |
| Hybrid or VPC | Meet data-sensitivity rules with hosted models | Private networking and extra setup |
- Autoscale the stateless orchestrator on request rate, and GPU workers on queue depth.
- Run ingestion workers on their own pool: batch embedding on the serving pool causes latency spikes for users.
Summary
Recap
- Two paths: read (fast, access-controlled) and write (correct, fresh, versioned).
- Name each box’s failure and say its trade-off aloud.
- Ingestion is idempotent, incremental, delete-aware and versioned. Re-embed into a new index and swap an alias.
- Budget latency per stage but measure the end-to-end p95; percentiles do not add.
- Tokens often dominate cost; caches help but each has a key to get right.
- Size the vector layer with arithmetic, shard for size, replicate for query rate.
Next: permissions, failure handling and safe release.
References
References & Sources (1 of 2)
Seven Failure Points When Engineering a Retrieval Augmented Generation System (opens in a new tab)
Scott Barnett, Stefanus Kurniawan, Srikanth Thudumu, Zach Brannelly, et al.2024CAIN 2024 (co-located with ICSE 2024)Paper
DOI 10.1145/3644815.3644945 (opens in a new tab)arXiv 2401.05856 (opens in a new tab)https://arxiv.org/abs/2401.05856
Used for An experience report on three RAG case studies that lists seven failure points and reports that validation is only feasible during operation and that robustness evolves over time.
Elastic2026Documentation
https://www.elastic.co/docs/manage-data/data-store/aliases
Used for An aliases API call can run several actions in one atomic operation, and the swap example keeps the alias from pointing at both targets at once.
Create or update aliases (Elasticsearch API reference) (opens in a new tab)
Elastic2026Documentation
https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-indices-update-aliases
Used for The update-aliases API accepts an index or a data stream in its add and remove actions.
Histograms and summaries (opens in a new tab)
Prometheus2026Documentation
https://prometheus.io/docs/practices/histograms/
Used for Averaging precomputed quantiles gives statistically meaningless values, so aggregate histogram buckets instead.
Prompt caching (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/prompt-caching
Used for Prompt caching reuses an identical prefix, with cache reads at 0.1x and 5-minute writes at 1.25x of base input price for most models, model-specific minimum lengths, and invalidation by earlier changes.
References
References & Sources (2 of 2)
Guidelines to choose an index (Faiss wiki) (opens in a new tab)
Meta Research (Faiss project)2026Documentation
https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index
Used for The HNSW memory formula (d x 4 + M x 2 x 4 bytes per vector), the M versus RAM trade-off, efSearch and nprobe as tuning knobs, and the re-ranking stage with IVF plus PQ.
Product Quantization: Compressing high-dimensional vectors by 97% (opens in a new tab)
Pinecone2026Article
https://www.pinecone.io/learn/series/faiss/product-quantization/
Used for One tutorial data point (Sift1M): large memory savings from product quantization with a clear recall drop against a flat index.
Multitenancy (Qdrant documentation, guide on multiple partitions) (opens in a new tab)
Qdrant2026Documentation
https://qdrant.tech/documentation/guides/multiple-partitions/
Used for A collection per tenant is rarely the most efficient approach and carries per-collection overhead; payload partitioning suits many small, similarly sized tenants; multiple collections are for a limited number of tenants needing strict isolation; requests without the tenant filter are slower.
Keys: ← → move, Home End first and last, F full screen.