8.1 Azure Managed Redis: Caching, Expiration & Invalidation
Key Takeaways
- Azure Managed Redis stores string and binary values addressed by keys; SET writes a value and GET reads it for low-latency AI path lookups
- TTL and EXPIRE attach a lifetime to a key so cache entries self-delete and force a refresh from the system of record
- Cache-aside loads data into Redis on a miss; write-through updates Redis whenever the application writes to the primary store
- Invalidate or overwrite Redis keys when source data changes so embeddings, prompts, and tool results never serve stale facts
- LLM response caching stores full completions by prompt hash; semantic caching matches similar embeddings to reuse near-duplicate answers
Azure Managed Redis is Microsoft’s fully managed Redis service for Azure AI workloads. In AI-200 terms, you integrate it as a low-latency store for session state, retrieval results, feature values, and model-call artifacts—not as a replacement for your system of record. The exam expects you to implement data operations that keep AI paths fast while remaining correct when source data or prompts change.
Why Redis appears in AI solutions
Large language model (LLM) calls, vector searches against cold storage, and multi-step agent tool chains are expensive in latency and tokens. Azure Managed Redis sits next to those components so that hot keys—user session context, recently retrieved chunks, cached completions—are available in memory. Typical AI uses include:
- Session and conversation state — short-lived chat history or tool outputs keyed by conversation ID
- Feature and lookup caches — product, policy, or catalog facts that ground prompts
- Retrieval caches — results of expensive searches reused across similar requests
- Model-call caches — full responses or semantic matches so identical or near-identical prompts do not re-hit the model
Managed Redis gives you Redis protocol compatibility, Azure networking and identity integration, and operational concerns (patching, scaling, high availability) handled by the platform. Your application code still owns cache keys, lifetimes, and invalidation rules.
Core data operations: SET and GET
At the command level, the fundamental write is SET and the fundamental read is GET. SET stores a string (or binary) value under a key. GET returns the value if the key exists, or a null/nil result if it does not. In AI pipelines you almost always design an explicit key schema so every cache entry is addressable and deletable.
Example key patterns:
| Key pattern | Example | Typical value |
|---|---|---|
session:{id} | session:conv-9f2a | JSON chat turns or summary |
doc:{id}:meta | doc:policy-441:meta | Title, version, last modified |
rag:{hash} | rag:a1b2c3… | Serialized retrieved chunk IDs |
llm:resp:{hash} | llm:resp:e9d1… | Cached completion text |
SET may optionally set a lifetime in the same call (for example SET with EX seconds), which is often preferred over a separate expire step so the write and TTL are atomic. GET after expiry behaves like a miss: the application must load from the primary store or recompute, then SET again.
For structured payloads, applications usually serialize JSON (or MessagePack) into the Redis string value. Keep values bounded; Redis is for hot, compact data. Large embeddings collections belong in dedicated vector indexes (covered in the next section) or in blob/search stores, with Redis holding pointers or small result sets.
Idempotent writes and overwrite semantics
SET replaces any existing value for that key. That overwrite behavior is what makes cache refresh simple: when you recompute a completion or reload a document snippet, SET the same key with the new payload. If you need “set only if absent” (first writer wins), Redis offers conditional forms such as SET NX; AI caches more often want unconditional SET so the newest computation wins.
Expiration: TTL and EXPIRE
Without expiration, cache keys live until deleted or until memory pressure eviction (depending on the maxmemory policy). AI caches almost always attach a time-to-live (TTL) so stale grounding data cannot linger indefinitely.
- EXPIRE key seconds — sets a TTL on an existing key
- TTL key — returns remaining seconds (−2 if missing, −1 if no expire)
- SET … EX seconds — creates the key already timed
Choose TTL by how fast the underlying truth changes and how costly a miss is:
| Cache content | Suggested TTL mindset | Rationale |
|---|---|---|
| Static FAQ grounding | Hours to days | Rarely changes; miss cost is a DB read |
| Product price / inventory | Minutes | Business data changes often |
| LLM response for identical prompt | Minutes to hours | Saves tokens; still risk of policy updates |
| Semantic cache for near-duplicate prompts | Short–medium | Similarity match can over-reuse answers |
| Agent tool result (weather, stock) | Seconds to minutes | Source is inherently time-sensitive |
When a key expires, the next GET is a miss. That miss is the signal to re-fetch from Azure AI Search, Cosmos DB, SQL, Blob Storage, or to call the model again. Do not treat expiry as invalidation of related keys: each key expires independently unless you design hierarchical deletes.
Cache-aside versus write-through
Two write policies dominate AI-200 scenarios.
Cache-aside (lazy loading)
- Application GETs the key.
- On hit, use the cached value.
- On miss, load from the system of record (or call the model), then SET into Redis with a TTL.
- Return the value to the caller.
Cache-aside is the default for read-heavy AI paths: RAG chunk lists, prompt templates, and response caches. The cache is never the authority; the database or model is. The downside is a stampede risk when many requests miss the same key simultaneously—mitigate with locks, single-flight patterns, or slightly staggered TTLs.
Write-through
- Application writes to the primary store.
- In the same logical operation, SET the new value into Redis (often with TTL).
- Readers can GET without waiting for a miss to warm the cache.
Write-through fits when updates are infrequent and readers must see fresh data immediately after a write—for example, updating a policy document’s summary that agents always read from Redis. The cost is that every write pays Redis latency, and failed Redis writes must be handled so the primary and cache do not diverge silently.
| Pattern | When to use | Failure mode to watch |
|---|---|---|
| Cache-aside | Read-heavy, expensive misses OK occasionally | Thundering herd on popular misses |
| Write-through | Writers control freshness; hot keys always primed | Partial failure leaving cache behind primary |
| Write-behind (less common on exam) | Buffer writes asynchronously | Durability delay if Redis is lost before flush |
For AI solutions, cache-aside is the pattern you will implement most often around LLM and retrieval calls; write-through appears when your app owns the mutation path for grounding content.
Invalidation on data change
TTL alone is not enough when a document, product record, or safety policy changes before the TTL ends. Invalidation means removing or overwriting cache entries so the next read cannot return the old value.
Practical invalidation tactics:
- Delete by key — when document
policy-441updates, DELdoc:policy-441:meta,rag:…keys derived from it, and anyllm:resp:…entries that embedded that content. - Versioned keys — include a content version or etag in the key (
doc:policy-441:v12). Publishing v13 makes old keys unreachable; they expire harmlessly. - Namespace flush (careful) — delete by prefix/pattern only for bounded namespaces; never flush the entire cache in production as a routine fix.
- Event-driven invalidation — on Cosmos DB change feed or Event Grid notifications, a worker deletes or refreshes related Redis keys.
Invalidation must cover derived AI artifacts. If you cached an LLM answer that quoted yesterday’s refund policy, deleting only the policy blob cache is insufficient—you must also invalidate response and semantic-cache entries that depended on that text.
Response caching and semantic caching for LLM calls
Response caching (exact match)
Build a deterministic hash of the normalized prompt (model name, temperature, system instructions, user message, and relevant tool context). Use that hash in a key such as llm:resp:{hash}. Flow:
- GET
llm:resp:{hash}. - Hit → return cached completion (no model call).
- Miss → call Azure OpenAI / Foundry model → SET result with TTL → return.
Exact-match caching is safe when inputs are identical. It fails to help when users paraphrase (“What’s the return window?” vs “How many days to return?”).
Semantic caching
Semantic caching stores an embedding of the prompt (or of a canonical question) alongside the response. On a new request:
- Embed the incoming prompt.
- Run a similarity search against cached prompt vectors in Redis (vector index; next section).
- If similarity exceeds a threshold, reuse the stored completion.
- Otherwise call the model and insert a new vector + response pair with TTL.
Semantic caching amplifies savings but introduces wrong-answer risk if the threshold is too low or if grounding data changed. Pair it with short TTLs and aggressive invalidation when knowledge bases update.
| Technique | Match type | Best for | Main risk |
|---|---|---|---|
| Response cache | Exact hash | Repeated API/batch identical prompts | No hit on paraphrases |
| Semantic cache | Vector similarity | Chat UIs with rephrased questions | Serving a near-miss answer |
| No cache | Always call model | High-stakes, rapidly changing facts | Cost and latency |
Implementation checklist for AI-200
When a question asks you to implement Azure Managed Redis caching for an AI solution, map the scenario to operations:
- Use SET/GET for the data path and a clear key schema.
- Attach TTL/EXPIRE so entries leave memory predictably.
- Prefer cache-aside for model and retrieval results; use write-through when your service writes grounding data.
- On source change, invalidate keys and any LLM response/semantic entries derived from that source.
- Choose exact response caching for identical prompts and semantic caching only when similarity reuse is acceptable.
These operations—not the portal blades alone—are what the exam tests when it says “implement caching, expiration, and invalidation” with Azure Managed Redis.
An AI chat API uses Azure Managed Redis. On each request it hashes the full prompt, calls GET on llm:resp:{hash}, and only on a miss calls Azure OpenAI then SET with a 30-minute TTL. Which caching pattern is this?
A product catalog used for RAG grounding is updated in Azure SQL. Agents still answer with yesterday’s prices for up to six hours. Redis keys for catalog snippets use a six-hour TTL and were not deleted on the SQL update. What should you implement so answers refresh immediately after catalog changes?
You need every successful write of a grounding policy summary to update both Azure Cosmos DB and Azure Managed Redis in the same application operation so readers rarely see a cold miss. Which pattern fits?