Short answer: cache the normalized page snapshot and the retrieval result separately, then invalidate by content hash and course version rather than by a timer alone. For an online course tutor that watches e-commerce pages and alerts on diffs, this keeps answers fresh without turning every student question into a full crawl and vector search. The accounting rule is the same one I use for a ledger: every answer needs an observable source version, an idempotent refresh, and an audit trail.
1. Start with the bill: what actually consumes the budget?
The expensive term is usually repeated work, not the bytes in a cache. A question can trigger a page fetch, HTML parsing, chunking, embedding, vector lookup, and answer generation. If a product page changes its delivery note by one sentence, recomputing every chunk for every course session is wasteful; retaining an old answer indefinitely is worse because the tutor may quote a policy that has already changed.
Model the path as two ledgers. The first ledger records source versions: URL, retrieval timestamp, ETag or Last-Modified value when available, canonicalized content hash, and parser version. The second records answer dependencies: query hash, chunk IDs, model identifier, and the source version used. A cache hit is valid only when both ledgers agree.
I keep raw HTML for a short, explicit retention window and keep normalized text and hashes longer. That is a trade-off, not a universal rule. Raw pages can contain personal data or licensed material; keeping less reduces exposure, but it also removes the evidence needed to reconstruct a disputed answer. Define the retention decision with compliance and legal owners, and record the decision in the data inventory.
The first check is arithmetic: measure the share of work caused by unchanged pages. If 92 of 100 checks produce the same canonical hash, the useful optimization is conditional re-chunking, not a faster vector database. Your mileage may vary because page templates and crawl policies differ.
2. How should an online course tutor cache retrieval and freshness?
Use three keys with different lifetimes. A source key identifies the canonical page and parser version. A retrieval key identifies a query, course scope, and source version. An alert key identifies a source hash pair, so the same diff cannot send duplicate notifications. TTL is a backstop for missed invalidation, not the definition of freshness.
The normalization step must be deterministic. Remove navigation and volatile timestamps, resolve relative links, preserve headings, and normalize whitespace before hashing. Store the hash beside the normalized document, not only in a vector record. When a page changes, compare hashes first; only then split into chunks and update embeddings. The tutor can answer from the previous index while the new index is built, provided the response is labeled with its source version and the freshness policy allows that grace period.
Here is a small Go interface that makes the boundaries testable. It uses generic names and a standard HTTP client so the policy is not tied to a hosted search product.
package retrieval import ( "context" "crypto/sha256" "encoding/hex" "net/http" "strings" ) type Snapshot struct { URL string Hash string Version string Text string FetchedAt int64 } type Store interface { GetSnapshot(ctx context.Context, key string) (Snapshot, bool, error) PutSnapshot(ctx context.Context, key string, value Snapshot) error PutAlertOnce(ctx context.Context, key string) (bool, error) } func canonicalHash(body string) string { clean := strings.Join(strings.Fields(body), " ") sum := sha256.Sum256([]byte(clean)) return hex.EncodeToString(sum[:]) } func fetch(ctx context.Context, client *http.Client, url string) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err } resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, &httpError{code: resp.StatusCode} } return readBody(resp.Body) } The omitted storage implementation is deliberate: the invariant is more important than a vendor SDK. PutAlertOnce should be backed by a unique constraint or an equivalent atomic operation. A retry after a timeout must not create a second alert, and a refresh job must be safe to run twice.
3. Detect diffs before you re-index
A diff is a semantic event for a tutor, not merely a byte comparison. A price, enrollment deadline, or return condition deserves a high-priority alert; a changed tracking pixel does not. Keep both a content hash and a field-level diff. The hash answers “did anything change?” while the diff classifier answers “does this change affect an answer?”
Chunk boundaries should follow headings and list items where possible, with a maximum token budget chosen from the model context limit. Preserve a stable chunk ID derived from document hash, section path, and ordinal. When only section three changes, sections one and two retain their IDs and embeddings. This reduces index churn and makes audit queries intelligible.
Consider a concrete race. Worker A fetches a product page at 10:00:00 and starts embedding the new return policy. Worker B, delayed by a queue retry, still has the 09:59:58 snapshot and receives a student question at 10:00:04. If B writes its older retrieval result after A has committed, the index appears healthy while the tutor silently regresses. The fix is a compare-and-swap on the source version: each write carries the hash it read, and the store accepts it only if the current version is unchanged. A rejected write is not an incident; it is a normal concurrency outcome that gets re-read and evaluated. The answer path then checks the committed version against the freshness policy, attaches that version to its evidence, and records the decision. This sequence also makes recovery deterministic after a process crash, because replaying the event either observes the same version or becomes a no-op. In a financial ledger I would call this an idempotent posting rule; for a tutor, it is the difference between a traceable stale answer and an unexplained one.
Race conditions leave fingerprints.
The freshness policy belongs in the answer contract. For example, a tutor may serve a cached explanation for 15 minutes for low-risk product descriptions, but it should fetch a current snapshot before answering a return-policy question. The policy must be explicit in code and telemetry; an unspoken “probably fresh” assumption is not an operational guarantee.
One sentence can be the whole section.
That is intentional: a change detector that cannot explain its source version is not ready to drive student-facing answers.
4. Test failure modes, not just cache hits
Happy-path hit rates do not expose correctness failures. Test a parser-version change, an origin returning a new ETag with identical normalized text, two workers refreshing the same URL, a notification retry, and a query arriving during re-indexing. Assert the resulting source version, chunk IDs, and alert idempotency key. Also test clock skew; timer-based invalidation becomes unpredictable when workers disagree about time.
For observability, emit one structured event per stage: fetch, normalize, hash, chunk, embed, retrieve, answer, and notify. Include correlation ID, source URL hash, document version, query hash, cache outcome, and policy decision. Do not log the raw student question or page body by default. Payment and education systems both have reasons to minimize sensitive data, and auditability does not require indiscriminate retention.
A useful dashboard has four distributions rather than one average: age of served source versions, time from source change to indexed chunk, duplicate-alert rate, and percentage of answers whose evidence failed the freshness policy. Tail latency matters because a 99th-percentile refresh can dominate a tutor session even when the mean looks healthy.
5. Choose what not to cache
Caching everything feels safe until retention, deletion, and access-control requirements arrive. Do not cache a personalized page under a public URL key. Do not reuse a retrieval result across course entitlements. Do not retain raw snapshots after the documented evidence window merely because storage is inexpensive. The cost of an incident includes proving what was shown, not only paying for another fetch.
The catch is that this design is not suitable when answers must reflect a live, transactional state on every request, or when the source forbids storing copies. In those cases, use a direct fetch with strict timeouts and a smaller evidence record, and accept the latency. Stick with a simple TTL cache when the content is low risk, changes rarely, and no alert or audit obligation exists; adding hashes, diff classification, and versioned chunks there would be needless machinery.
I also would not select a vector index as the source of truth. It is an acceleration layer. The canonical snapshot, parser version, and immutable event log are the records used for reconciliation. If an embedding model changes, rebuild from those records rather than trying to infer the original text from vectors.
The result is a deliberately boring loop: fetch, normalize, hash, compare, re-index changed sections, and record the answer dependency. Boring is valuable here. It gives a course tutor fresh explanations, gives an e-commerce operator a precise diff alert, and gives an auditor a path from answer back to source.