15. Performance and Cost Optimization
Budget latency, batch embeddings, cache safely, and optimize cost without sacrificing correctness.
Latency Budgets
End-to-end latency includes query rewriting, embedding, retrieval, reranking, context assembly, model first-token time, generation, and validation. Measure p50, p95, and p99. Streaming may improve perceived responsiveness even if total completion time is similar. Instrument each stage and optimize the dominant bottleneck rather than guessing.
Total = rewrite + embed + retrieve + rerank
+ assemble context + generate + validate- Inspect the relevant pipeline stage instead of guessing.
- Preserve source provenance, versions, and access scope.
- Measure quality on representative queries.
Why measure p95 latency?
Batch Embeddings and Reuse Work
Batching can reduce network overhead during ingestion. Use bounded concurrency, persist progress, and deduplicate unchanged content before embedding. Cache vectors only when normalized content hash, embedding model, and preprocessing version match. Larger batches can increase memory and failure blast radius, so benchmark realistic workloads.
const key = hash({
contentHash: sha256(normalizedText),
modelId: embeddingModelId,
preprocessingVersion: "normalize-v3"
});- Inspect the relevant pipeline stage instead of guessing.
- Preserve source provenance, versions, and access scope.
- Measure quality on representative queries.
What belongs in an embedding cache key?
Query and Answer Caching
RAG answers depend on permissions, corpus version, prompt version, model, and current data. Cache keys should include relevant scope and versions. Re-check authorization before returning private cached content. Use TTLs and invalidation on source updates, permission changes, or reindexing. Caching retrieval results may be safer than caching final answers for dynamic data.
const key = hash({
tenantId: auth.tenantId,
userScope: auth.cacheScope,
query: normalizeQuery(query),
corpusVersion, promptVersion, modelId
});- Inspect the relevant pipeline stage instead of guessing.
- Preserve source provenance, versions, and access scope.
- Measure quality on representative queries.
Why include corpus version in a cache key?
Cost Modeling and Budgets
Costs include parsing/OCR, embeddings, storage, search, reranking, model input/output, evaluation, observability, retries, and reindexing. Estimate per-query and per-document costs, then model realistic traffic. Reduce unnecessary context, cache safely, batch work, cap outputs, and use smaller models only when evaluation supports the choice. Keep provider rates in maintained configuration and reconcile estimates with actual usage.
Per query = query embedding + search + rerank
+ model input/output + retries + observability- Inspect the relevant pipeline stage instead of guessing.
- Preserve source provenance, versions, and access scope.
- Measure quality on representative queries.
Which is a sensible optimization?