Skip to content

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.

Exact cachenormalised textSemantic cachesim + entity checkEmbedding cachequery → vectorRetrievalhybrid + re-rankModelprompt caching onKey scopetenant + user groupsTTLby content typeInvalidateon document updateCheapest check firstKeep it correctdrop entries citing changed docs
A cache that serves a stale or another user’s answer is a bug, not an optimisation. Scope keys and invalidate on change.

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.

Semantic cache: hits versus wrong answers16 questions arrive. If one is close enough to a cached question, the cached answer is returned without calling the model.

Cache hits 11 of 16 (69%) · wrong answers served 3 · cost per million questions ≈ ₹2.5 lakh (₹8 lakh with no cache)

IncomingNearest cachedSimilarityResult
What is the refund window?What is the refund window?1.00hit
what is the refund windowWhat is the refund window?1.00hit
How do I reset 2FA?How do I reset 2FA?1.00hit
How long do I have to ask for a refund?What is the refund window?0.93hit
Refund period for my order?What is the refund window?0.90hit
I can't log in, how do I reset two-factor?How do I reset 2FA?0.91hit
Where do I download my GST invoice?How do I get a GST invoice?0.94hit
What does the Pro plan cost per month?What does the Pro plan cost monthly?0.98hit
What does the Team plan cost per month?What does the Pro plan cost monthly?0.96hit: WRONG answer
Refund window for annual plans?Refund window for monthly plans?0.95hit: WRONG answer
Is there a limit of 100 API calls a minute?Is there a limit of 1,000 API calls a minute?0.97hit: WRONG answer
How do I cancel my order?How do I cancel my subscription?0.84miss
How can I export all my data?How do I export my data?0.89miss
Change billing emailHow do I update my billing email?0.86miss
Do you support SSO with Okta?Do you support SSO?0.82miss
What are your office hours in Bengaluru?What are your support hours?0.78miss
Guided experiments
  1. Start with exact matching. How many hits? Why is the exact cache still worth having even with a semantic one?
  2. 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?
  3. Turn on the entity check. Find the lowest threshold with no wrong answers. How does its hit rate compare with exact matching?
  4. 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.

In production: Store effective dates on policy chunks and filter out superseded versions at query time. Deleting an old version is good; never retrieving it by accident is better.

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.

Tip: Measure “answered” separately from “asked”. A cheaper system that says “not found” twice as often hasn’t saved money.

Hands-on: coding window

The coding window and the full VS Code lab are available after you sign in.

Sign in to code

Labs

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

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

1. Which stage usually dominates RAG latency and cost?
2. A semantic cache served the monthly-plan answer to an annual-plan question. Fix?
3. What must be part of every cache key?
4. Why delete stale chunks during re-indexing?
5. Replicas mainly give you…

Interview questions

  1. Walk me through the latency budget of a RAG request. Where would you optimise first?
  2. How do you design a semantic cache that never serves a wrong or private answer?
  3. How do you keep a RAG index fresh when 5% of documents change daily?
  4. How would you scale a RAG system from 100 to 2,000 queries per second?
  5. 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).