Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 18 of 28
❮Prev Next❯

Azure Managed Redis: Caching, Expiration and Invalidation

Module 2: Data for AI ⏱ 11 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    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.

    Simulate it » No Azure account needed

    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.

    Azure portal: Create Azure Managed Redis and try commands Create Azure Managed Redis and try commands in the console.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    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
    1. Open Azure Managed Redis and select + Create.
    2. Pick a performance tier and size. Then go straight to Advanced: some choices there can’t change later.
    3. For vector search tick RediSearch and use the Enterprise clustering policy. OSS clustering doesn’t support it.
    4. Review and Create.
    5. Managed Redis listens on port 10000 over TLS. Open a terminal and connect with redis-cli.
    6. Cache-aside: miss → read the database → SET with a TTL → next read is a hit. When the product changes, DEL the key.
    7. 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.

    😟 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
    🛠️ Solved with: Azure Managed Redis

    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.

    ▶ Explainer video See it in motion 7 steps · 1 min 26 sec

    An animation of the cache-aside pattern. A product API checks Azure Managed Redis for product:42, misses, reads PostgreSQL and stores the row with SET EX 300. The next request hits Redis in about a millisecond. The TTL counts down and the key expires, then a price update writes the database and deletes the key so the next read loads the new price. Timings are examples.
    Read the video script
    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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.
    6. 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.
    7. 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:

    TierMemory to vCPUGood for
    Memory Optimized8:1Lots of data, lower throughput, dev and test
    Balanced4:1Most workloads
    Compute Optimized2:1The highest throughput
    Flash OptimizedRAM plus NVMeVery 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. 1 Miss

      GET returns nothing, so the app reads the database and SETs the value with EX 300.

    2. 2 Hit

      The next GET returns from memory in about a millisecond.

    3. 3 Write

      The price changes in the database.

    4. 4 Invalidate

      DEL removes the key, so the next read loads the new price.

    Cache-aside: miss, hit, invalidate

    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

    PolicyWhat Redis removes when memory is full
    volatile-lruLeast recently used keys that have a TTL
    allkeys-lruLeast recently used keys, TTL or not
    volatile-lfu / allkeys-lfuLeast frequently used keys
    volatile-ttlKeys with the shortest time left
    noevictionNothing. 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

    E-commerce

    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.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    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.

    Question 1

    Question 1 of 5

    An application reads product details from Azure Database for PostgreSQL. You need to add Azure Managed Redis so that data is loaded into the cache only when it is first requested. Which pattern should you implement?

    Question 2

    Question 2 of 5

    A cached exchange rate must be removed automatically 300 seconds after it is written to Azure Managed Redis. Which command should the application use to write the value?

    Question 3

    Question 3 of 5

    An application caches product prices in Azure Managed Redis with a 10-minute TTL. After a price is updated in the database, customers continue to see the previous price for several minutes. You need customers to see the new price on the next request. What should you do?

    Question 4

    Question 4 of 5 · Select 2

    A Python application must connect to Azure Managed Redis by using its managed identity instead of an access key. Which TWO actions are required?

    Question 5

    Question 5 of 5

    An Azure Managed Redis cache is used only as a cache. When memory is full, write commands fail with out-of-memory errors. Most keys do not have a TTL. You need Redis to remove the least recently used keys so that writes succeed. Which eviction policy should you configure?

    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. 1.Which port does Azure Managed Redis use?Show

      10000

    2. 2.What scope does the Entra token use?Show

      https://redis.azure.com/.default

    3. 3.What does TTL return for a key with no expiry?Show

      -1

    4. 4.Which command removes a key?Show

      DEL

    5. 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

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.