Short answer: cache ranked content IDs against an explicit catalog revision, not the tutor's generated answer, and spend indexing work only when the searchable course content changes. For a gaming course catalog, that makes index cost visible without letting an old lesson survive behind a fast cache hit.
I care about the revenue-per-hour trade here. A solo SaaS can spend a week tuning an elaborate cache hierarchy, or ship a small boundary that makes stale data impossible to confuse with current data. I would ship the boundary first.
The concrete system is an online tutor that searches product content for gaming courses: lesson summaries, mechanics glossaries, exercises, and course metadata. Students may phrase the same intent as "animation cancel lesson," "canceling an attack animation," or "where is the animation-cancel module?" Semantic retrieval helps connect those phrasings to stored passages. The original retrieval-augmented generation paper describes the useful split: generated output can be conditioned on retrieved, non-parametric memory rather than relying only on model parameters. Caching belongs inside that split, where its invalidation rules can follow the searchable corpus.
How should an online course tutor cache retrieval without stale lessons?
Use three different lifetimes because three different things change. Cache normalized query embeddings by embedding-policy version. Cache ranked passage IDs by catalog revision and retrieval-policy version. Keep the final generated answer out of the durable retrieval cache unless the application can also bind it to every prompt, model, authorization, and content dependency that shaped it.
That distinction matters more than the cache engine. If lesson 42 is unpublished, a cached answer may still quote it even after the search index is correct. A cached list of passage IDs is narrower: the read path can resolve those IDs against the current content store, apply access checks again, and drop anything no longer visible. This is a design rule, not a promise that every stale state disappears automatically. Every mutable dependency included in a response still needs either a version in the key or a fresh check after the hit.
One revision for the whole catalog is the smallest safe starting point. Publishing any searchable change increments catalogRevision; old keys then become unreachable and expire naturally. It is intentionally coarse. A popular game-design course can invalidate cached retrieval for unrelated courses, so broad revisions trade hit rate for a short implementation and an audit trail I can understand on a Friday afternoon. Ship weekly. Refine only after measurements show that invalidation churn, rather than embedding or generation, is the actual constraint.
The cache layers have different failure costs:
| Cached value | Key must include | Hit behavior | Main trade-off |
|---|---|---|---|
| Query embedding | normalized query, embedding policy | reuse the vector | avoids repeated query work, but normalization can merge distinct intent |
| Ranked passage IDs | query identity, scope, catalog revision, retrieval policy | rehydrate and reauthorize passages | protects freshness, but a coarse revision lowers hit rate |
| Generated answer | all retrieval and generation dependencies | return prose directly | fastest read path, but the invalidation surface is much larger |
The catch is simple: revision-keyed result caching is not suitable when edits must become invisible before the revision update can commit. In that workflow, keep authorization and publication status as fresh post-cache filters, or skip result caching for restricted material. It is also a poor fit for per-student retrieval whose ranking depends on rapidly changing progress; stick with only the query-embedding cache there, then rank against current learner state.
The smallest cache boundary I would ship
The implementation needs boring inputs. The caller supplies a trusted scope and catalog revision; the retrieval service owns query normalization, key construction, and post-hit hydration. No vendor SDK is required by this interface. The cache and index sit behind four methods, so either can move without leaking storage details into tutor code.
import { createHash } from "node:crypto"; type SearchScope = { tenantId: string; courseId: string; catalogRevision: number; }; type RankedId = { passageId: string; score: number }; type Passage = { id: string; courseId: string; published: boolean; text: string; }; interface Cache { get<T>(key: string): Promise<T | null>; set<T>(key: string, value: T, ttlSeconds: number): Promise<void>; } interface SemanticIndex { search(query: string, courseId: string, limit: number): Promise<RankedId[]>; } interface ContentStore { getMany(ids: string[]): Promise<Passage[]>; } const RETRIEVAL_POLICY = "semantic-v3"; const RESULT_TTL_SECONDS = 900; function normalizeQuery(query: string): string { return query.trim().replace(/\s+/g, " ").toLocaleLowerCase("en-US"); } function digest(value: string): string { return createHash("sha256").update(value).digest("hex"); } function resultKey(query: string, scope: SearchScope): string { const identity = JSON.stringify({ tenantId: scope.tenantId, courseId: scope.courseId, catalogRevision: scope.catalogRevision, retrievalPolicy: RETRIEVAL_POLICY, query: normalizeQuery(query) }); return `retrieval:${digest(identity)}`; } async function retrieveForTutor( query: string, scope: SearchScope, cache: Cache, index: SemanticIndex, content: ContentStore ): Promise<Passage[]> { const key = resultKey(query, scope); let ranked = await cache.get<RankedId[]>(key); if (!ranked) { ranked = await index.search(normalizeQuery(query), scope.courseId, 8); await cache.set(key, ranked, RESULT_TTL_SECONDS); } const passages = await content.getMany(ranked.map(item => item.passageId)); const byId = new Map(passages.map(passage => [passage.id, passage])); return ranked .map(item => byId.get(item.passageId)) .filter((passage): passage is Passage => Boolean(passage?.published && passage.courseId === scope.courseId) ); } Two details are doing the real work. First, the key includes tenant and course scope; the same words must not reuse results across catalogs. Second, hydration happens on every hit, so deletion and publication checks use current records. The cached score preserves rank, while the map restores that order after a batch read.
Don't cache a miss for the same duration without thinking. A student may search for a newly announced combat-design module before the publishing transaction updates the index. A long-lived empty result would hide the module after it becomes searchable. I would either give misses a shorter policy or decline to cache them until request volume proves they matter. The exact duration is workload-dependent, and I'm not sure there is a useful universal value; hit rate, edit frequency, and the acceptable freshness window would resolve it.
There is another quiet edge: query normalization is semantic policy. Lowercasing and collapsing whitespace are conservative for this English catalog, but stripping punctuation, numbers, or game-specific symbols can merge distinct searches. 2D, 3D, C++, and C# are not decoration. Keep normalization versioned when its behavior changes, even if the index itself does not.
Measure index cost instead of guessing
Cache hit rate alone can lie. A high hit rate may come from returning old popular material while new lessons never enter the candidate set. For each request, record the cache outcome, catalog revision, retrieval-policy version, candidate count, hydrated count, and total latency. Record content-to-index lag on the publishing side. Do not log raw student queries by default; derive a stable, scoped query digest when request correlation is enough.
Index cost also needs a denominator. Track searchable passages processed per catalog revision, changed passages versus unchanged passages, and index writes caused by each publishing event. Those are application counters, not universal benchmarks. Their purpose is to answer a practical question: is the system paying to re-index content that did not change? If yes, content-addressed passage fingerprints or per-course revisions may be worth the added state. If no, the coarse design is still earning its keep. Test freshness as a sequence, not as isolated functions. Publish revision 17, search for "animation cancel," and capture the ranked IDs. Change the matching lesson, publish revision 18, then repeat the same query. The test should assert that revision 18 uses a different key and that hydration never returns an unpublished passage, including when an old revision-17 cache entry remains stored. Add a tenant-scope test with identical query text. Add a retrieval-policy test so a ranking change cannot reuse prior results.
Fast isn't enough. Correct scope is the product.
For error handling, treat cache access as an optimization boundary: the retrieval path can proceed to the index when a cache read is unavailable, while index or content-store failures should follow the tutor's normal error policy rather than being disguised as an empty answer. The code sample shows the success path because retry and timeout policy depends on the runtime, but production metrics should distinguish a true miss from an unavailable cache. That distinction keeps an operational incident from looking like sudden student curiosity.
What I would change when the catalog grows
I would first split the global revision into course revisions. That reduces unrelated invalidation while keeping the same proof: a result belongs to one explicit snapshot of searchable course content. If a query intentionally spans the full catalog, its key can carry a catalog-level revision or a deterministic set of course revisions, though the latter can become too large to be a sensible cache key.
Next comes incremental indexing. Fingerprint the canonical searchable fields of each passage, enqueue work only when that fingerprint changes, and keep metadata-only changes out of the embedding pipeline when they cannot affect retrieval. This is where the gaming catalog's shape matters. Editing a price display or thumbnail may change a product page without changing the lesson text a tutor searches; combining every field into one document revision would pay index cost for irrelevant edits. The searchable projection should be explicit and tested.
I would not add finer partitions merely because the catalog has a large row count. More revisions mean more invalidation state, harder multi-course queries, and more ways for a publishing transaction to update content without its matching revision. The decision comes from observed churn: if one frequently edited course evicts useful cached results for many quiet courses, course-level keys buy something. If most courses publish together, they add bookkeeping without preserving many hits.
Generated-answer caching stays last. It can be appropriate for public, stable FAQ-style prompts where the full prompt template, model policy, retrieval snapshot, and visibility rules are versioned together. It is not suitable for personalized tutoring feedback, learner progress, or access-controlled lessons. In those cases, reuse the expensive deterministic pieces and regenerate the learner-facing response from current context. That keeps the tutor responsive without pretending a sentence has the same lifecycle as a passage ID.
The weekly shipping decision
Start with a revisioned cache of ranked IDs, current-state hydration, and coarse invalidation. This design is small enough to inspect and specific enough to test. It also isolates the two bills of engineering time: publishing pays for changed searchable content, while repeated student intent can reuse retrieval work inside a known revision.
Move to per-course revisions only after metrics show unrelated invalidation. Move to passage fingerprints when index writes reveal avoidable work. Skip result caching when authorization or learner state changes faster than the content snapshot can represent. Those limits are features of the decision, not footnotes.
The revenue-per-hour rule is blunt: outsource undifferentiated cache storage if that saves operational attention, but keep revision ownership and cache-key policy in application code. Those rules encode what "current" means for the course business. Shipping them behind a small TypeScript interface leaves room to change infrastructure later without rewriting the tutor.
References
- Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks: https://arxiv.org/abs/2005.11401