Skip to content
Blogs

Cache Invalidation for Personalized AI UIs

· 20 min read

Personalized AI UIs cache embeddings, completions, and UI fragments for speed—then serve the wrong tenant the wrong answer when keys ignore identity, entitlements, or prompt revision. Staff engineers treat invalidation as authorization: namespace every layer, bust on authz events, and prove isolation with canaries—not TTL hope.

TTL is not a security model

Generic page caches expire on time. Personalized AI surfaces expire when the user, role, plan, feature flags, retrieved documents, or prompt version change—even if the clock says the entry is fresh. A sixty-second TTL keyed only on route can still leak another tenant's completion or show revoked entitlements for one request cycle.

Name what you cache at each layer: raw model output, rendered markdown, embedding vectors for the sidebar, edge HTML shells, or service-worker payloads. Each artifact needs its own key grammar and bust strategy. Mixing layers under one key guarantees either over-invalidation or silent cross-tenant hits.

Staff engineers document cache classes in the same design doc as RLS and API scopes. When product asks for "just cache the answer," the review question is whether the answer is a function of identity and authorization—not only of the visible question text.

Stale-while-revalidate can hide entitlement revocation for one hop. For billing, medical, legal, or account-recovery surfaces, prefer explicit revalidation before render or disable edge caching entirely on those routes. Speed matters, but correct personalization is the product.

Run a pre-launch review that lists every HTTP cache header, CDN rule, and in-memory LRU in the assistant path. Teams often forget an edge rule added for marketing A/B tests that also matches authenticated API routes. If marketing and product share a hostname, split cache policies by path prefix before enabling semantic reuse.

Design keys that encode authority

Include tenant id, user or session scope, entitlement hash, and content or prompt revision in cache keys. Prefer opaque hashes over concatenating PII. For semantic caches, require a tenant-scoped namespace so similar questions never hit across organizations.

On permission or plan changes, broadcast invalidation for the affected identity—not a global flush that thrashes the fleet. Document whether soft-deleted users can still hit warm entries during grace periods and how long break-glass admin sessions remain in shared indexes.

| Layer | Typical key inputs | Bust triggers | | --- | --- | --- | | Completion cache | tenant, user scope, prompt rev, tool policy rev | plan change, role change, prompt deploy | | Embedding index | tenant namespace, corpus revision | document ingest, ACL change on source | | Rendered UI fragment | locale, entitlement hash, feature flags | flag flip, entitlement hash change | | CDN HTML shell | auth cookie session version | logout-all, password reset |

Semantic similarity caches are the highest-risk layer: two tenants asking "reset my password" must not share a vector bucket. Partition indexes per tenant or per trust zone, and cap cross-user similarity within a tenant when answers include account-specific facts.

Alert on cross-tenant key collisions and unexpected hit-rate cliffs after permission-system deploys. Cache bugs in AI UIs are privacy incidents, not UX glitches.

Streaming and partials complicate busts

AI UIs often stream tokens into a client that also hydrates from a CDN or service worker. Decide whether partial streams are cacheable at all. If you cache completed answers only, document how mid-stream cancels, tool-call revisions, and regenerated segments avoid storing half-truths.

Never key a partial stream only on conversation id without binding to the latest tool results hash. Agents that revise plans mid-turn can leave warm entries that contradict the final authorized action. Prefer completing the turn server-side, then caching the finalized artifact with a turn-level revision id.

Mobile clients on Expo amplify the problem: backgrounding aborts streams while service workers may still write cache entries. Tag client abort reasons separately from server completion when logging, and disable offline persistence for in-flight assistant turns unless merge semantics are explicit.

For high-throughput copilots, separate hot read caches from write-through invalidation queues. Bursty invalidation during bulk entitlement imports should not block user-facing latency—queue bust messages and measure lag as an SLO beside hit rate.

Document which surfaces allow any edge cache at all. Marketing pages and signed-out demos can stay TTL-driven; signed-in copilots should default to no cache until keys and probes exist. That split prevents teams from copying CDN settings from the landing page into the authenticated assistant.

Drive invalidation from events, not clocks

Wire cache busts to the same events that update authorization: Stripe webhooks for plan changes, Supabase RLS policy deploys, feature-flag updates, and prompt-registry publishes. If your identity provider rotates sessions globally, include session version in keys or purge by session family.

Use version stamps on prompt templates and retrieval corpora. A prompt deploy without a cache key bump is indistinguishable from a model quality regression in support tickets. Treat prompt version like schema migration: announce, bump, measure hit rate, roll back if isolation probes fail.

Avoid "flush everything" buttons except during verified incidents. Global purges teach teams to widen TTL when costs spike, which reintroduces leakage. Scoped purge APIs should accept tenant id lists, tag filters, and revision ranges—mirroring how you scope database migrations.

Document cache behavior in runbooks next to kill switches and rollout gates. When you disable an AI feature, caches may still serve old answers unless bust rules include feature-flag dimensions.

Schedule entitlement bulk imports during low-traffic windows and pre-warm invalidation workers. A import that updates fifty thousand rows without a matching bust plan is indistinguishable from an incident in support volume the next morning.

Implementation sketch

```typescript type CacheKeyParts = { tenantId: string; subjectScope: string; // hashed user or session scope entitlementHash: string; promptRevision: string; corpusRevision: string; };

export function completionCacheKey(parts: CacheKeyParts, questionFingerprint: string): string { const payload = [ parts.tenantId, parts.subjectScope, parts.entitlementHash, parts.promptRevision, parts.corpusRevision, questionFingerprint, ].join(":"); return `llm:v1:${hashSha256(payload)}`; }

// On authz change — publish to invalidation bus (not TTL hope) export async function onEntitlementChanged(tenantId: string, subjectScope: string) { await bustQueue.enqueue({ tenantId, subjectScope, layers: ["completion", "ui-fragment"] }); } ```

Keep key derivation in one module reviewed by security. Duplicated key logic between edge workers and API servers is how teams accidentally omit entitlement hash on one path.

For Supabase-backed MVPs, align row-level changes with cache busts: a policy change without bust is equivalent to serving stale data from a replica with broken replication lag assumptions. You do not need perfect synchrony—you need bounded staleness documented per surface.

Expose a read-only debug endpoint in staging that expands a cache key from the caller's session—never in production without strict access control. Engineers who cannot see key material guess and ship regressions. Pair the endpoint with redacted examples in onboarding docs so new hires do not treat cache as magic.

Prove isolation in production

Add canary checks that attempt to fetch another tenant's cached completion by key guess and by similarity search. Run after every deploy that touches auth, prompts, or retrieval. Fail the pipeline when probes succeed where they must not.

Monitor hit-rate cliffs after permission deploys: a sudden spike often means keys stopped varying when they should. Pair with leakage metrics—requests that returned answers for a different subject scope than the caller.

Game days should include revoking a plan mid-session and verifying the UI cannot render cached premium answers within your documented staleness bound. Include mobile and web clients; service workers routinely outlive server bust messages.

Publish an invalidation SLO: maximum time from entitlement change to cache visibility for high-risk surfaces. Product and legal should sign that number, not only infra.

Link isolation probes to observability for streaming LLM paths: partial caches and SSE clients can desync from server bust events when disconnects retry with stale ETags.

Store probe results with deploy ids so you can correlate leakage windows with prompt or auth changes. Retention can be short; the habit of failing builds on probe regression matters more than long-term storage of every canary attempt.

Operational checklist

Inventory every cache layer in the AI UI stack before launch. Mark which layers may hold personalized text versus public snippets only.

Require cache key diagrams in design reviews for new copilot surfaces. If the diagram is missing, default answer is no edge cache until keys exist.

Pair invalidation with cost-aware routing: semantic caches save tokens until they leak—then legal and support costs dominate. Review hit rate alongside cost per successful outcome weekly.

When migrating prompts or corpora, run dual-key periods: old and new revision keys in parallel with metrics comparing quality and isolation. Cut over only when probes and eval gates pass.

Document user-visible staleness in privacy notices where regulations require accurate processing descriptions. "We may show cached assistant text for up to X minutes after permission changes" is better than silent wrong answers.

Finally, rehearse incident response: disable cache reads via feature flag before chasing model bugs when reports mention wrong-account content. The fastest mitigation is often stop serving warm entries, not redeploy the model.

Review cache design in the same cadence as permission-model changes for multi-tenant copilots: if RLS or gateway scopes shift without a matching bust contract, you have two authorization systems that disagree until users report wrong-account answers.

Train support to recognize cache-shaped incidents: wrong plan features, answers referencing another workspace name, or assistant tone from an old prompt version. A runbook entry that starts with disable cache reads saves hours before model rollback.

Measure cost saved by semantic caches only after isolation probes pass for seven consecutive days. Optimizing hit rate before keys are correct optimizes the wrong metric and hides privacy debt behind a finance dashboard. Treat that week as a launch gate, not a nice-to-have checklist item buried in a spreadsheet. Product, legal, and infra should all see the same probe dashboard before you announce cache-backed speed wins.

Frequently asked questions

When is semantic caching safe for multi-tenant AI?
Semantic caching is safe only when indexes are partitioned per tenant or trust zone, inputs exclude cross-tenant training data, and answers cannot include account-specific facts unless subject scope is in the key. Never share similarity buckets across organizations. Run canary queries after every retrieval or prompt deploy, and treat a hit-rate spike after an auth deploy as a possible isolation regression until probes prove otherwise.
Should we use stale-while-revalidate on AI answers?
Use stale-while-revalidate only for low-risk, non-personalized snippets such as public documentation summaries. For entitlements-sensitive answers, prefer short TTL plus explicit revalidation or no edge cache at all. One stale hop after a plan downgrade is enough for a support escalation or regulatory complaint, so document maximum staleness per surface and test downgrade paths in game days.
How do prompt changes interact with cache keys?
Treat prompt template version as part of the key for any cached completion derived from that template. Deploy prompts like schema migrations: bump revision, monitor hit rate and quality, roll back if probes fail. Silent prompt edits without key bumps are a common source of wrong-account narratives in support tickets because users see new policy language with old cached behavior.
What is different on Expo and React Native clients?
Service workers and AsyncStorage can persist assistant text after server busts, so mobile users may see revoked entitlements longer than web unless client caches honor bust signals. Disable offline persistence for in-flight turns unless merge rules are explicit. Tag client abort versus server complete in logs so streaming cache bugs do not look like model regressions during on-call.

Sources

Related service

Ship AI features to production: tooling, retrieval, evaluation, safety boundaries, and operable backends.

View hire details


Published on September 16, 2026 by Berktug Berke Ates.