When a course tutor answers from a folder of PDFs, caching is a retrieval decision, not a database afterthought. Cache the expensive, stable work (parsed pages, normalized chunks, and embeddings), then keep the final answer cache short and tied to document versions. That gives students fast responses without quietly serving yesterday's syllabus.
How should caching shape retrieval for an online course tutor?
Short answer: use versioned retrieval caches and a small semantic-answer cache; invalidate by document fingerprint, and measure hit rate alongside citation freshness. A cache that cannot explain why an item is still valid is an incident waiting to happen.
The page usually arrives late. A student reports, "The tutor still says chapter 4 is required," while the course team has already replaced that PDF. The on-call sees normal request latency and a healthy vector index. The signal that should have fired earlier is a rising age of cached chunks for the active course version.
I would trace that alert backwards: record the PDF fingerprint at ingest, attach it to every chunk and embedding, and emit retrieval_cache_age_seconds with the fingerprint in structured logs. A cache hit should carry the same metadata into the answer trace. If the citation fingerprint differs from the current course manifest, bypass the answer cache and retrieve again. This is mundane instrumentation. It prevents a polished, fast, wrong answer.
The threshold has a cost in both directions. An age limit that is too low increases parsing and embedding work; one that is too high creates stale teaching material. Start with the course's publishing SLA, then test the boundary with a fixture that changes one page. I am not sure a single global TTL will survive every subject area; lab manuals and semester-long history PDFs have very different change patterns.
I first assumed the parser version was a deployment detail. It isn't. When parser v3 changed how headings were joined, old chunks and new embeddings looked valid but produced different citations. The fix was to put parser_version in the key and in the trace, then replay the same 120-question fixture before warming a new manifest. That replay caught a page-boundary change that a hit-rate dashboard never showed.
Small detail. Big impact.
The cache layers and their contracts
Treat each layer as a contract with a key, a value, and an invalidation rule. Raw PDF bytes can use an object-store validator such as an ETag. Parsed pages should key on (document_fingerprint, parser_version). Chunks add the chunking policy, and embeddings add the embedding model identifier. The answer cache uses the normalized question, course scope, retrieval policy, and the set of source fingerprints.
| Layer | Good cache value | Invalidate when | Main risk |
|---|---|---|---|
| Bytes | PDF content and ETag | ETag or checksum changes | stale download |
| Parse/chunk | page text and chunk boundaries | parser or policy changes | index churn |
| Embedding | vector for a chunk | model or chunk text changes | mixed vector spaces |
| Retrieval | ranked chunk IDs and scores | index or filter changes | wrong scope |
| Answer | response plus citations | any cited fingerprint changes | stale guidance |
The retrieval cache is often the safest latency win because it avoids repeated vector and metadata work while still allowing answer generation to see current source text. Keep answer entries small and observable. Include a creation timestamp, expiry, and citation fingerprints; do not hide those fields in an opaque blob.
What does a cache-aware request path look like?
The request path should fail closed on identity, not on availability. If a course manifest cannot be resolved, do not reuse an answer from another course or an unversioned key. A miss can be slower; cross-course leakage is a security incident.
Here is a deliberately small Go sketch. The interface is generic so the same policy can sit over Redis, an in-process cache, or a self-hosted store.
package retrieval
import (
"context"
"crypto/sha256"
"encoding/hex"
"strings"
)
type Store interface {
Get(context.Context, string) ([]byte, bool, error)
Put(context.Context, string, []byte) error
}
func answerKey(course, question, policy string, fingerprints []string) string {
parts := append([]string{course, strings.TrimSpace(strings.ToLower(question)), policy}, fingerprints...)
sum := sha256.Sum256([]byte(strings.Join(parts, "\x1f")))
return "answer:" + hex.EncodeToString(sum[:])
}
func GetAnswer(ctx context.Context, cache Store, course, question, policy string, fingerprints []string) ([]byte, bool, error) {
key := answerKey(course, question, policy, fingerprints)
value, hit, err := cache.Get(ctx, key)
if err != nil {
return nil, false, err
}
return value, hit, nil
}
In production, the writer of an answer also stores its expiry and source fingerprints, and the reader checks both before returning it. Use request coalescing on a miss so thirty students asking the same question do not trigger thirty embedding or generation jobs. The operation still needs an idempotency key: retries after a queue timeout must not publish duplicate cache entries with different metadata.
Where caching fails in real classrooms
The first failure mode is key drift. One service lowercases and strips punctuation; another preserves Unicode whitespace. Hit rates look fine until equivalent questions split across keys. Define normalization once, test it with table-driven cases, and log a short hash rather than the student's raw question.
The second is partial invalidation. Deleting vectors while leaving parsed chunks creates misses that silently fall back to old retrieval results. Publish a new manifest atomically, then warm the next version in the background. Never mutate a live version in place.
The third is stampede behavior at office hours. A lock with a bounded lease, jittered expiry, and a per-key queue keeps pressure predictable. Watch queue depth, cache-hit latency, stale-bypass count, and citation-age percentiles. A green p95 with a growing stale-bypass count is not green. During a launch rehearsal, I would deliberately expire one popular answer key and watch whether one worker refreshes it or every classroom request does; the distinction is visible in queue depth within seconds and is much cheaper to learn before term starts.
Choosing the trade-off and proving it
Run a replay set of real course questions labeled with the expected supporting pages. Compare retrieval recall, citation freshness, and tail latency for three policies: no answer cache, versioned answer cache, and retrieval-only cache. Keep the corpus and question set fixed while changing TTLs. I keep the report boring on purpose: for each question, it records the expected page, returned page, cache layer, fingerprint, and elapsed milliseconds. Then I sample misses by hand, because a recall percentage cannot tell me that a citation points to an appendix with a nearly identical paragraph. The result should be a decision rule, not a favorite product. If a policy wins latency but loses freshness on changed-page fixtures, it is rejected before production, even when the aggregate score looks attractive.
Caching is not suitable when source documents change continuously and every response must reflect the latest byte; use retrieval-only caching or skip caching for that path. Stick with a longer-lived embedding cache when PDFs are immutable and embedding is the dominant cost. For regulated courses, prefer explicit version pinning and an auditable purge over aggressive TTL guesses.
After rollout, page on stale citations and cross-scope key mismatches, not just latency. A cache hit is successful only when it is fast, correctly scoped, and still defensible to the instructor who owns the PDF.
References
- https://arxiv.org/abs/2005.11401
- https://www.rfc-editor.org/rfc/rfc9111
- https://www.rfc-editor.org/rfc/rfc7232
Top comments (0)