Courses / RAG Systems / Module 14
Module 14: Caching, latency, cost and scaling: semantic cache, incremental indexing, sharding
10 h · theory 3 · hands-on 4 · project 2 · revision 1
You will be able to
- Add exact and semantic caches and measure hit rates
- Index incrementally and delete stale chunks
- Shard and replicate an index
- Report cost per answered question
Capstone increment: Semantic cache, incremental re-indexing and a latency and cost dashboard.
Job-description skills: Latency, caching and scale · Lab tools: redis, locust
1. Where the time and money go
Break a request into stages and measure each: query rewrite, embedding, search, re-ranking and generation. Generation usually dominates both latency and cost, which is why streaming the answer (users see words within a second) and sending less context matter more than shaving milliseconds off vector search.
Cheapest work first: check an exact cache, then a semantic cache, then do the full pipeline with provider prompt caching for the long, stable parts of the prompt.
2. Exact and semantic caches
An exact cache keyed on normalised question text is cheap and always safe within a scope. A semantic cache reuses an answer when a new question’s embedding is close to a cached one, and its danger is near-identical questions with different answers: “annual” versus “monthly” plans, “100” versus “1,000” calls a minute. Add an entity check (numbers, plan and product names must match), tune the threshold on real query pairs, and measure wrong answers served, not just hit rate.
Scope every cache key by tenant and permission groups so one user never sees another’s answer, set a time-to-live by content type, and invalidate entries whose citations point at documents that changed.
Cache hits 11 of 16 (69%) · wrong answers served 3 · cost per million questions ≈ ₹2.5 lakh (₹8 lakh with no cache)
| Incoming | Nearest cached | Similarity | Result |
|---|---|---|---|
| What is the refund window? | What is the refund window? | 1.00 | hit |
| what is the refund window | What is the refund window? | 1.00 | hit |
| How do I reset 2FA? | How do I reset 2FA? | 1.00 | hit |
| How long do I have to ask for a refund? | What is the refund window? | 0.93 | hit |
| Refund period for my order? | What is the refund window? | 0.90 | hit |
| I can't log in, how do I reset two-factor? | How do I reset 2FA? | 0.91 | hit |
| Where do I download my GST invoice? | How do I get a GST invoice? | 0.94 | hit |
| What does the Pro plan cost per month? | What does the Pro plan cost monthly? | 0.98 | hit |
| What does the Team plan cost per month? | What does the Pro plan cost monthly? | 0.96 | hit: WRONG answer |
| Refund window for annual plans? | Refund window for monthly plans? | 0.95 | hit: WRONG answer |
| Is there a limit of 100 API calls a minute? | Is there a limit of 1,000 API calls a minute? | 0.97 | hit: WRONG answer |
| How do I cancel my order? | How do I cancel my subscription? | 0.84 | miss |
| How can I export all my data? | How do I export my data? | 0.89 | miss |
| Change billing email | How do I update my billing email? | 0.86 | miss |
| Do you support SSO with Okta? | Do you support SSO? | 0.82 | miss |
| What are your office hours in Bengaluru? | What are your support hours? | 0.78 | miss |
Guided experiments
- Start with exact matching. How many hits? Why is the exact cache still worth having even with a semantic one?
- Switch to semantic matching at 0.90, then raise the threshold to 0.97. Do the wrong answers go away? Look at the Team plan, annual plans and API limit rows: why do they score so high?
- Turn on the entity check. Find the lowest threshold with no wrong answers. How does its hit rate compare with exact matching?
- Two users ask “what is my order status?”. What must be part of the cache key so one user never sees another’s answer?
3. Incremental indexing and deletes
Re-embedding the whole corpus every night is slow and expensive. Hash each chunk’s content, re-embed only chunks whose hash changed, and delete chunks whose source disappeared or was replaced. Stale chunks are a quiet quality killer: the 2023 policy keeps outranking the 2026 one.
Make the job idempotent so it can be retried and backfilled safely, and record per run what was added, changed and deleted. Vector indexes often mark deletes rather than removing them; schedule the engine’s optimisation or vacuum step.
4. Shards, replicas and memory
Replicas serve more queries per second and survive node failures; shards split an index that no longer fits on one node. Shard by tenant or document id, and know that every query fans out to all shards unless a filter targets one. Keep quantized vectors in memory and full vectors on disk with rescoring (Module 5) to fit more per node.
Load-test before launch with Locust or k6 using a replay of realistic questions: find the queries per second at which p95 latency breaks your target, and plan for at least 50% headroom.
5. Report cost per answered question
Put four numbers on the dashboard: p50 and p95 latency per stage, cache hit rate (exact and semantic), tokens per answer, and cost per answered question. Cost per question is the number finance and product understand, and it makes every optimisation easy to justify.
Common wins in order: cache, send fewer and better chunks (re-rank to the top 3 to 5), route simple questions to a smaller model, and use prompt caching for long fixed prompts.
Hands-on: coding window
The coding window and the full VS Code lab are available after you sign in.
Sign in to codeLabs
Lab 14.1: Semantic cache
Add a RedisVL semantic cache scoped by tenant and groups with an entity check. Replay 500 logged questions and measure hit rate and wrong answers served at three thresholds.
Expected: A threshold choice with hit rate and a wrong-answer count of zero on the replay.
Lab 14.2: Incremental re-indexing
Make ingestion hash chunks, upsert only changed ones, delete removed ones and log the counts; filter superseded policy versions by effective date.
Expected: A second run on an unchanged corpus re-embeds nothing; a changed document updates only its chunks.
Lab 14.3: Load test and dashboard (capstone increment)
Load-test /ask with Locust at 2× expected peak, and add a dashboard with per-stage latency, cache hit rate and cost per answered question.
Expected: p95 at peak under your target, and a screenshot of the dashboard in the README.
Go deeper
Videos
- AI Dev 25 x NYC | Nitin Kanukolanu: Semantic Caching for LLM Applications · DeepLearningAI · ~29 min. A practitioner talk on semantic caching: thresholds, false hits and how to measure them.
- RAG at 10 Million Documents — System Design · Code with Lucian · ~15 min. A system-design walk-through of RAG at ten million documents: sharding, ingestion and latency.
- What is a semantic cache? · Redis · ~3 min. A two-minute explanation of semantic caching from Redis.
Further reading
- Docs Distributed deployment · Qdrant docs. Shards, replicas and consistency settings for a vector database cluster.
- Interactive ANN-Benchmarks · Aumüller, Bernhardsson and Faithfull. Use the curves to estimate how many queries per second an index sustains at your target recall.
- Article Building A Generative AI Platform · Chip Huyen. The components of a production GenAI system added one at a time, with the reason for each.
GitHub repositories
- redis/redis-vl-python: SemanticCache: distance thresholds, TTLs and filterable cache scopes.
- zilliztech/GPTCache: Its similarity evaluators and how it decides a cache hit, useful for designing your entity check.
- locustio/locust: Writing a user class that replays real questions and reports percentiles.
- qdrant/qdrant: The distributed deployment docs: shards, replicas and on-disk vectors.
Checkpoint quiz
Interview questions
- Walk me through the latency budget of a RAG request. Where would you optimise first?
- How do you design a semantic cache that never serves a wrong or private answer?
- How do you keep a RAG index fresh when 5% of documents change daily?
- How would you scale a RAG system from 100 to 2,000 queries per second?
- What is cost per answered question, and how would you halve it?
Ask the professor
Sign in to ask questions about this module.
Discussion
Community discussion appears here once giscus is configured (see README).