Azure Managed Redis: Caching, Expiration and Invalidation
30-second answer
Azure Managed Redis is an in-memory store based on Redis Enterprise. With cache-aside, your app checks Redis first; on a miss it reads the database (or calls the model), then saves the result with a TTL using SET key value EX 300. When the source data changes, you invalidate by deleting the key so the next read loads fresh data. In Python you connect with redis-py on port 10000 over TLS, using Microsoft Entra ID through redis-entraid (or an access key if enabled), and an eviction policy decides what goes when memory fills.
Exam objective: 2.3.1 Implement Azure Managed Redis data operations, including caching, expiration, and invalidation. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Open <strong>Azure Managed Redis</strong> and select <strong>+ Create</strong>.
👆 Click the glowing item in the portal to continue
Read the steps as text
- Open Azure Managed Redis and select + Create.
- Pick a performance tier and size. Then go straight to Advanced: some choices there can’t change later.
- For vector search tick RediSearch and use the Enterprise clustering policy. OSS clustering doesn’t support it.
- Review and Create.
- Managed Redis listens on port 10000 over TLS. Open a terminal and connect with redis-cli.
- Cache-aside: miss → read the database → SET with a TTL → next read is a hit. When the product changes, DEL the key.
- Hit rate climbs as the cache warms up. Every hit is a database read, or an LLM call, you didn’t pay for.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
Azure Managed Redis
Azure Managed Redis keeps hot data in memory. Cache-aside: check Redis, and on a miss read the database and store the result with a TTL. When data changes, invalidate the key. Redis can also hold a vector index for fast similarity search, for example a semantic cache of answers.
🤔 What happens if…
Read this tour as text
- Text becomes a vector. An embedding model turns text into a list of numbers, a vector (1,536 numbers for
text-embedding-3-small). Texts that mean similar things get vectors that sit close together, so "refund" lands near "money back". - Cosmos DB: items, partitions, RUs. In Azure Cosmos DB for NoSQL, JSON items live in containers, spread across logical partitions by the partition key. Every operation costs Request Units (RUs). A point read by id and partition key costs about 1 RU. A query that scans every partition costs far more.
- Indexing and consistency. By default Cosmos DB indexes every property, so writes cost more RUs. An indexing policy can exclude paths you never filter on, such as the big
embeddingarray. Consistency levels trade freshness for speed and cost: Strong, Bounded staleness, Session (default), Consistent prefix, Eventual. - Vector search in Cosmos DB. A vector embedding policy tells Cosmos DB where the vectors are, their dimensions and distance function. A vector index makes search fast:
diskANNorquantizedFlatfor large sets, orflatfor exact search on small vectors (up to 505 dimensions). ThenORDER BY VectorDistance(c.embedding, @q)returns the closest items. - Change feed. The change feed is an ordered log of inserts and updates in a container (deletes only show up in the *all versions and deletes* mode). A change feed processor reads it with a lease container that remembers how far each worker got, so a new product can be embedded the moment it’s saved.
- PostgreSQL with pgvector. In Azure Database for PostgreSQL, the pgvector extension adds a
vector(1536)column type. Without an index, every search compares against every row (a sequential scan). An HNSW or IVFFlat index finds near neighbours fast, trading a little recall for a lot of speed. - RAG with a metadata filter. Retrieval-augmented generation (RAG): embed the question, fetch the closest chunks (
ORDER BY embedding <=> $1 LIMIT 5), filter by metadata such astenant_idorlang, then send those chunks to the model as context. The answer is grounded in your own data. - Azure Managed Redis. Azure Managed Redis keeps hot data in memory. Cache-aside: check Redis, and on a miss read the database and store the result with a TTL. When data changes, invalidate the key. Redis can also hold a vector index for fast similarity search, for example a semantic cache of answers.
Make a slow product lookup fast with the cache-aside pattern, watch keys expire, then turn the same cache into a vector store for support articles with RediSearch.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
The same product page hits the database 5,000 times a minute.
😊 THE SOLUTION
Cache-aside with Redis, a TTL and invalidation on change.
- Slow repeated reads✓ In-memory cache
- Stale data forever✓ TTL expiry
- Price changed✓ Delete the key on update
Start with a question
If 2,000 people ask the same question in an hour, should your app look up the answer 2,000 times?
Think of a busy chai stall near an office. The owner doesn’t brew each cup from scratch. He keeps a big pot ready, pours from it for the next twenty customers, and makes a fresh pot every half hour or as soon as the milk runs out.
Azure Managed Redis is that pot. Your app keeps hot results in memory, serves repeats in under a millisecond, and throws the pot out on a timer (TTL) or the moment the recipe changes (invalidation). The database, or the expensive model call, only gets the first request.
Explain it like I’m 10
Visual: cache-aside in motion
Watch one product key go through a miss, a hit, an expiry and an invalidation.
Read the video script
- Check the cache firstA request for product 42 comes in. Before touching the database, the app asks Redis. Nothing's there. That's a miss.
- Miss, so read the databaseOn a miss, the app reads the database. That works, but it's the slow path. Call it forty milliseconds here, just as an example.
- Save it with a TTLThen it saves the result in Redis with a time to live. SET, the key, the value, then EX 300. That copy lives for five minutes.
- The next request hitsThe next person asks for the same product. This time Redis has it, so the answer comes straight from memory in about a millisecond. The database isn't touched at all.
- The TTL runs outMeanwhile the TTL counts down. At zero Redis drops the key, and the next read misses and reloads it. A little random jitter stops thousands of keys expiring together.
- Price changes? Delete the keyNow the price changes. The app writes the database first, then deletes the key. Skip that and people see the old price until the TTL runs out. Delete after the commit, not before.
- Fresh on the next readThe next request misses, loads the new price and caches it again. That's cache-aside: check Redis, fall back to the database, set a TTL, and delete the key on every write.
The technical explanation
What Azure Managed Redis is
Azure Managed Redis is built on Redis Enterprise and runs your data in memory. Four tiers:
| Tier | Memory to vCPU | Good for |
|---|---|---|
| Memory Optimized | 8:1 | Lots of data, lower throughput, dev and test |
| Balanced | 4:1 | Most workloads |
| Compute Optimized | 2:1 | The highest throughput |
| Flash Optimized | RAM plus NVMe | Very large datasets where cold keys can live on disk |
Clients connect on port 10000 over TLS (the older Azure Cache for Redis used 6380). New caches have access keys disabled by default, and Microsoft recommends Microsoft Entra ID with a managed identity.
Connecting from Python
# pip install redis redis-entraid azure-identity
import redis
from redis_entraid.cred_provider import create_from_default_azure_credential
credential_provider = create_from_default_azure_credential(
("https://redis.azure.com/.default",),
)
r = redis.Redis(
host="contoso-cache.westeurope.redis.azure.net",
port=10000,
ssl=True,
decode_responses=True,
credential_provider=credential_provider, # refreshes the Entra token for you
)
r.ping()
Before this works, add your user or the app’s managed identity as a Redis user on the cache (the Authentication page in the portal). With Entra ID, the Redis user name is the identity’s object ID and the token is the password; redis-entraid handles both and re-authenticates before the token expires. If you’ve enabled access keys instead, pass password=<key> and keep that key in Key Vault.
The core commands
SET product:42 "{...json...}" EX 300 # store for 300 seconds
GET product:42 # read it (nil after it expires)
TTL product:42 # seconds left; -1 = no expiry, -2 = key doesn't exist
EXPIRE product:42 60 # change the TTL on an existing key
DEL product:42 # remove it now (invalidation)
Cache-aside in code
import json
def get_product(product_id: int) -> dict:
key = f"product:{product_id}"
cached = r.get(key)
if cached: # hit
return json.loads(cached)
row = db_get_product(product_id) # miss: go to PostgreSQL or Cosmos DB
r.set(key, json.dumps(row), ex=300) # cache it for 5 minutes
return row
def update_price(product_id: int, price: float) -> None:
db_update_price(product_id, price) # 1. write the source of truth
r.delete(f"product:{product_id}") # 2. invalidate, so the next read is fresh
-
1 Miss
GET returns nothing, so the app reads the database and SETs the value with EX 300.
-
2 Hit
The next GET returns from memory in about a millisecond.
-
3 Write
The price changes in the database.
-
4 Invalidate
DEL removes the key, so the next read loads the new price.
The same pattern works for AI calls: cache an embedding by a hash of its input text, or a model answer by a hash of the exact prompt. That saves tokens and latency on repeats. When “repeat” should mean “same meaning” rather than “same text”, you need a semantic cache, covered in the Redis vector search lesson.
Choosing TTLs and handling invalidation
- Delete the key after the database commit. Deleting first leaves a gap where another request can reload the old value.
- Prefer delete over writing the new value into the cache on update. The next read rebuilds it, and you avoid two writers racing.
- Add a little random jitter to TTLs (300 ± 30 seconds) so thousands of keys don’t expire in the same second and hit the database together.
- Short TTLs for prices and stock, longer ones for product descriptions and embeddings, which rarely change.
When memory fills up: eviction policies
| Policy | What Redis removes when memory is full |
|---|---|
volatile-lru | Least recently used keys that have a TTL |
allkeys-lru | Least recently used keys, TTL or not |
volatile-lfu / allkeys-lfu | Least frequently used keys |
volatile-ttl | Keys with the shortest time left |
noeviction | Nothing. Writes fail with an out-of-memory error |
For a pure cache, allkeys-lru or volatile-lru (with TTLs on everything) are the usual choices. noeviction suits data you can’t afford to lose silently. Watch the used memory and evicted keys metrics in Azure Monitor.
Architect level Clustering policy and multi-key commands
Every Azure Managed Redis instance is sharded internally. The clustering policy decides how clients see that. OSS exposes the Redis Cluster API for the best throughput, and your client must support cluster mode. Enterprise gives one endpoint that proxies to the right shard, so any client works. Non-clustered is for caches up to 25 GB. You pick the policy when you create the cache, and OSS or Enterprise can’t be changed afterwards. Multi-key commands across shards can raise CROSSSLOT errors; with Enterprise, DEL, MGET, MSET, EXISTS, UNLINK and TOUCH work across slots, and with OSS all keys must share a hash slot (use hash tags like {product:42}:price).
Real-world business scenario
Adventure Works Cycles (fictional)
- The problem
- Their product assistant called PostgreSQL and the embedding API on every chat turn. During a sale, database CPU hit 100% and customers saw prices that were 10 minutes out of date because a cache had been added with long TTLs and no invalidation.
- What they used
- Azure Managed Redis (Balanced tier) with cache-aside for product rows and embeddings, Entra ID through redis-entraid, a 5-minute TTL with jitter, and DEL on every price update.
- Why that choice
- Repeat reads now come from memory, and deleting the key on write means price changes show up on the next request instead of after the TTL.
- The result
- Database load during the next sale stayed under half of the previous peak, and price complaints stopped.
When to use it and when not to
✓ Use it when…
- The same data or model result is read far more often than it changes.
- You need sub-millisecond reads for sessions, rate limits or hot product data.
- You want to cut repeated embedding or model calls for identical inputs.
✕ Think twice when…
- As the only copy of data you can't lose. Treat the cache as disposable unless you configure persistence and plan for it.
- Data that must be exactly current on every read, such as an account balance during a payment.
↔ Alternatives to consider
- Azure Cosmos DB integrated cache when the data already lives in Cosmos DB and you want caching without new code.
- Azure API Management semantic caching to cache LLM responses at the gateway.
Test yourself with exercises
5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner What is cache-aside?
Model answer
The app asks Redis first. If the key is there, that's a hit and we return it straight away. If not, that's a miss, so we read from the database, store the result in Redis with a TTL, and return it. The cache only fills with what people actually ask for.
Interviewer follows up
Why always set a TTL?
You
So nothing stays stale forever if an invalidation is missed, and so memory gets freed for keys nobody reads any more.
Intermediate How do you connect redis-py to Azure Managed Redis without an access key?
Model answer
I install redis-entraid, create a credential provider with create_from_default_azure_credential for the scope https://redis.azure.com/.default, and pass it to redis.Redis with the host, port 10000 and ssl=True. The identity has to be added as a Redis user on the cache first. The provider refreshes the token before it expires.
Experienced developer A product price changed in the database but customers still see the old one for five minutes. How do you fix it?
Model answer
That's the TTL doing its job without invalidation. In the code path that writes the new price, I commit the database change and then delete the cache key for that product. The next read is a miss and loads the new price. I keep the TTL as a safety net. If several services write prices, I'd publish an event on each change and have one subscriber do the deletes.
Scenario Your cache is full and new SET commands fail with an out of memory error. What happened?
Model answer
The eviction policy is probably noeviction, or it's a volatile policy and most keys have no TTL, so Redis has nothing it's allowed to remove. I'd set TTLs on cached keys and pick a policy like volatile-lru or allkeys-lru, or scale the cache up if the data really needs that memory.
Quick revision
Key points
- Azure Managed Redis is based on Redis Enterprise; tiers are Memory Optimized, Balanced, Compute Optimized and Flash Optimized.
- Connect on port 10000 with TLS. Entra ID via redis-entraid is preferred; access keys are disabled by default on new caches.
- Cache-aside: GET, on a miss load from the source, then SET with EX seconds.
- TTL commands: SET ... EX, EXPIRE, TTL (-1 means no expiry, -2 means gone).
- Invalidate on write by deleting the key after the database commit.
- The eviction policy decides what Redis removes when memory is full.
Important terminology
- Azure Managed Redis
- Microsoft's managed Redis service built on Redis Enterprise, with Memory Optimized, Balanced, Compute Optimized and Flash Optimized tiers.
- Cache-aside
- A pattern where the app reads from the cache, loads from the data store on a miss and writes the result into the cache.
- TTL (time to live)
- How long a key lives before Redis removes it. Set with SET ... EX seconds or EXPIRE, and read with TTL.
- Invalidation
- Removing or updating a cached value when the source data changes, so readers don't get stale data.
- Eviction policy
- The rule Redis uses to remove keys when memory is full, such as volatile-lru, allkeys-lru or noeviction.
- redis-entraid
- The Python package that plugs Microsoft Entra ID tokens into redis-py and refreshes them automatically.
Common mistakes
- Caching without a TTL, so stale data and memory use grow forever.
- Updating the database but not deleting the cached key.
- Using port 6380 (Azure Cache for Redis) instead of 10000 for Azure Managed Redis.
Exam tips
- "Load into the cache only when requested" = cache-aside.
- "Expire a cached value after 5 minutes" = SET key value EX 300 (or EXPIRE key 300).
- "Users see stale data after an update" = invalidate (DEL) on write.
Five quick revision questions
-
1.Which port does Azure Managed Redis use?Show
10000
-
2.What scope does the Entra token use?Show
https://redis.azure.com/.default
-
3.What does TTL return for a key with no expiry?Show
-1
-
4.Which command removes a key?Show
DEL
-
5.Which Azure Managed Redis tier moves cold data to NVMe storage?Show
Flash Optimized.
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: Vector Search with Azure Managed Redis
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.