CloudBrum
CloudBrum · Cloud decision-support platform
Azure Databases

Azure Cache for Redis and Azure Managed RedisLast reviewedReading time~12 minLevelBeginner to advanced

Microsoft Azure · Databases · Managed Redis for caching, sessions and fast data

Azure has two managed Redis services, and the older one is being retired. Azure Cache for Redis, with its Basic, Standard, Premium and two Enterprise tiers, has announced end-of-life dates, and Microsoft points everyone to Azure Managed Redis, which runs on the Redis Enterprise engine and is sold in four memory-to-CPU shapes. This page covers both, because existing systems still run the first and every new design should start with the second. Whichever you use, the job is the same: keep hot data in memory next to your application, and be clear about what happens when the cache is empty.

On this page (17 sections)

    Mind map: Azure Cache for Redis at a glance

    Azure Cache for Redis mind map Azure Cache for Redis at a glance: Two products: Azure Managed Redis, Azure Cache for Redis, Retirement dates; Tiers: Memory Optimized, Balanced, Compute and Flash Optimized; Data features: Search and JSON modules, Persistence, Eviction policies; Availability: High availability, Zone redundancy, Active geo-replication; Clients: Clustering policy, TLS on port 10000, Retries and reconnects; Security: Microsoft Entra ID, Private endpoint, Customer-managed key; Operations: Azure Monitor metrics, Scaling up, Maintenance windows; Pricing: Hourly price by size, High availability cost, Reservations. Azure Cache for Redis and Managed Redis at a glance In-memory caching on Azure: the main building blocks and decisions CloudBrum Cloud decision-support platform CloudBrum Azure Managed Redis Azure Cache for Redis Retirement dates Two products Memory Optimized Balanced Compute and Flash Optimized Tiers Search and JSON modules Persistence Eviction policies Data features High availability Zone redundancy Active geo-replication Availability Clustering policy TLS on port 10000 Retries and reconnects Clients Microsoft Entra ID Private endpoint Customer-managed key Security Azure Monitor metrics Scaling up Maintenance windows Operations Hourly price by size High availability cost Reservations Pricing Azure Redis17-point analysis CloudBrum· 17-point cloud service analysis cloudbrum.com
    CloudBrum Azure Redis at a glance · 17-point analysis Two products Azure Managed Redis Azure Cache for Redis Retirement dates Tiers Memory Optimized Balanced Compute and Flash Optimized Data features Search and JSON modules Persistence Eviction policies Availability High availability Zone redundancy Active geo-replication Clients Clustering policy TLS on port 10000 Retries and reconnects Security Microsoft Entra ID Private endpoint Customer-managed key Operations Azure Monitor metrics Scaling up Maintenance windows Pricing Hourly price by size High availability cost Reservations CloudBrum · cloudbrum.com

    Free to share. The downloaded image includes the CloudBrum link.

    Key features (summary)

    • Two services, one successorAzure Cache for Redis is the long-standing service with Basic, Standard, Premium, Enterprise and Enterprise Flash tiers. Azure Managed Redis replaces it, and Microsoft has published retirement dates for the old one, so new work belongs on the new one.
    • Four shapes of memory and CPUAzure Managed Redis tiers differ in how much memory each virtual CPU gets: Memory Optimized has the most, Balanced is in the middle, Compute Optimized gives the most processing for the memory, and Flash Optimized puts most of the data on NVMe flash (it was still in preview in the documentation I read).
    • High availability and zonesHigh availability is on by default and keeps a replica of the data. In Regions with Availability Zones the nodes are spread over them. Turning it off lowers the price and removes the replica.
    • Active geo-replicationLinked caches in different Regions accept writes and replicate to each other, which suits users in several places and a Region-level outage. A group holds up to five caches, the smallest Balanced sizes and Flash Optimized caches can’t join, and persistence can’t be combined with it.
    • Modules includedSearch, JSON, probabilistic structures such as Bloom filters, and time series are available as modules, so a cache can also serve as a small search or vector index.
    • Entra ID and private networkingClients can sign in with Microsoft Entra ID instead of a shared key, reach the cache through a private endpoint, and use a customer-managed key for encryption at rest.
    • Clustering policyThe OSS policy exposes shards to cluster-aware clients. The Enterprise policy presents one endpoint, so ordinary clients work and multi-key commands are easier.
    • Scale up in placeChange the size of an Azure Managed Redis cache without recreating it. Moving down a size has limits, and Azure may require a new cache for it.

    Basic concepts

    Azure Managed Redis
    The current first-party managed Redis service, built on Redis Enterprise software. In Azure Resource Manager it is a Microsoft.Cache/redisEnterprise cluster with a database inside.
    Azure Cache for Redis
    The older service, with Basic, Standard, Premium, Enterprise and Enterprise Flash tiers. Microsoft has announced its retirement and asks customers to move.
    Tier (Azure Managed Redis)
    The family of cache sizes: Memory Optimized, Balanced, Compute Optimized or Flash Optimized. The name of a size carries the family, as in Balanced_B5.
    Cluster and database
    A cluster is the set of nodes you pay for. The database inside it is what clients connect to, with its own port, eviction policy and clustering policy.
    Clustering policy
    Enterprise gives one endpoint and hides the shards. OSS publishes the shard layout to clients that follow Redis Cluster rules. Non-clustered keeps everything in one shard.
    High availability
    A standby copy of each node that takes over when the primary fails or is patched. Turn it off and those events mean downtime, and maybe lost data.
    Eviction policy
    What gets deleted once memory fills up. The default drops the least recently used keys that carry an expiry.
    Persistence
    Optional saving of data to disk, either as snapshots (RDB) every hour or so, or as an append-only file written every second.
    Active geo-replication
    A group of caches in different Regions that replicate to each other, with conflicts resolved by the engine.
    Data access policy
    The rule that says which Entra identity may do what in a database.
    Private endpoint
    A private address for the cache in your virtual network, resolved through a private DNS zone.
    Access keys
    Shared secrets that give full access. They are off by default for new Azure Managed Redis databases.
    Time to live (TTL)
    A countdown in seconds after which the key deletes itself. Keys without one stay until memory runs out.
    Cache-aside
    Check the cache, and on a miss ask the database and keep the answer for a while. When the row is updated, delete the cached copy.

    How to create & configure it

    Create a private Azure Managed Redis cache with the Azure CLI

    1. Decide which service you are onA new design should use Azure Managed Redis. If you already run Azure Cache for Redis, put its retirement date in the plan and start a migration while there is time.
    2. Choose the tier and sizeStart with Balanced for general caching. Take Memory Optimized for large data sets with modest traffic, Compute Optimized for heavy command rates on small data, and Flash Optimized for big, mostly cold data sets.
    3. Choose the clustering policyTake the Enterprise policy if your clients are not cluster-aware or you use multi-key commands a lot. Take OSS if your client library handles Redis Cluster and you want it to talk to shards directly.
    4. Create the cache with safe settingsLeave high availability on, disable public network access, require TLS 1.2, and keep access keys off so that clients use Microsoft Entra ID.
    5. Add the private endpointCreate a private endpoint in the application’s virtual network and link the private DNS zone, then check from a machine in that network that the cache name resolves to a private address.
    6. Give the application an identityUse a managed identity for the application and assign it a data access policy on the database. Don’t hand out keys.
    7. Connect with retriesUse TLS on port 10000, a token provider that renews tokens, short timeouts and automatic reconnects.
    8. Add expiries and alertsPut an expiry on each key. In Azure Monitor, alert on server load, memory, evictions and connected clients.
    9. Rehearse failuresTrigger a failover or restart the application under load, then empty the cache in a test and watch what the database does.

    Tip: search the web for Redis on Azure and you will find years of articles, scripts and videos for Azure Cache for Redis, with different names, ports (6380 for TLS) and commands. Check which product a guide covers before you copy from it. See the code references for the same setup as Terraform.

    Common issues after configuration

    SymptomLikely causeWhat to check / fix
    A guide or script doesn’t work on a new cacheIt was written for Azure Cache for Redis, which uses different resource types, host names and the TLS port 6380Use the Azure Managed Redis documentation, connect on port 10000, and use the az redisenterprise commands or the azurerm_managed_redis resource.
    The host name resolves to a public address or not at allThe private endpoint exists but the private DNS zone isn’t linked to the virtual network, or the client uses another DNS serverLink privatelink.redis.azure.net to the network, make sure the client uses Azure DNS or forwards to it, and test with a lookup from the client.
    Sign-in fails with an authentication errorThe identity has no data access policy, the token is for the wrong scope, or access keys are off while the client sends a keyAssign a data access policy to the identity, request a token for https://redis.azure.com/.default, and use the object ID as the user name.
    A cluster error such as MOVED appearsThe OSS clustering policy is on and the client isn’t cluster-awareSwitch to a cluster-aware client, or create the database again with the Enterprise policy. Changing the policy in place isn’t really an option.
    Keys disappear before their TTLThe cache reached its memory limit and evicted keys, or a failover happened with high availability offWatch evictions and memory, add size, set TTLs, and keep high availability on where loss would hurt.
    Timeouts under loadServer load is high, a big value or slow command blocks the engine, or the client has too few or too many connectionsLook at server load, find large keys, use pipelining and a bounded connection pool, and move to a Compute Optimized size if CPU is the limit.
    Connections drop at certain timesMaintenance or a scaling operation restarted nodesPick a maintenance window that suits you, leave high availability on, and set the client to retry and reconnect.
    The cache can’t be scaled downThe target size has less memory than the data, or Azure restricts that changeDelete data first, or create a new cache of the smaller size and migrate.
    Can’t enable persistenceThe database belongs to an active geo-replication groupPersistence works only on databases that aren’t geo-replicated. Choose one or the other.
    Data is gone after a restartPersistence was off and high availability didn’t cover the failureTurn persistence on if the cache holds anything you can’t rebuild, or treat the data as disposable and rebuild from the database.
    The bill is higher than plannedA larger size than the working set needs, a second Region in a geo-replication group, or caches left running in developmentCompare used memory with size, drop unused caches, and turn high availability off only where a loss is harmless.

    Use cases: when and where to use it

    Good fit

    • Web and API back ends that read the same data again and again from a slower database
    • Session storage for web sites running on several servers or App Service instances
    • Rankings, counters and throttling rules that must update atomically and quickly
    • Caching answers from AI models by meaning, and vector search beside the application
    • Real-time data shared between services, such as presence or short-lived state
    • Offloading hot reads from Azure SQL Database or Cosmos DB before buying more capacity

    Consider something else

    Pros: why consider it?

    Why teams choose it

    • Managed: Microsoft patches, monitors and replaces nodes
    • Four tiers fit memory-heavy, balanced, CPU-heavy and big-but-cold data
    • Entra ID sign-in removes shared keys
    • Modules add search, JSON and time series without another service
    • Zone redundancy and active geo-replication are available
    • Integrates with private endpoints, Key Vault keys and Azure Monitor

    Trade-offs to weigh

    • Two products with similar names make documentation and old guides confusing
    • Azure Cache for Redis has retirement dates, so staying on it means a later migration
    • Sizes come in steps, and scaling down has limits
    • The clustering policy is fixed when the database is created
    • Active geo-replication and persistence exclude each other
    • Not every Azure Region offers every tier, so check availability before you plan

    Common threats, vulnerabilities & risks

    RiskSeverityWhy it mattersMitigation
    Running new systems on the retiring serviceHighAzure Cache for Redis has announced end-of-life dates, and a forced migration under a deadline is riskier than a planned one.Build new work on Azure Managed Redis, and put a migration date for old caches on the roadmap.
    Public network access left onHighA cache reachable from the internet is a target for scans and brute force, even with a key.Disable public network access and use a private endpoint.
    Shared access keys everywhereHighA key gives full control, ends up in config files and cannot be tied to a person or a service.Turn access keys off and use Microsoft Entra ID with data access policies.
    Old data treated as currentMediumA cached discount or role can outlive the change that replaced it.Delete the cached copy whenever the source changes, give moving data a short expiry, and read from the database when the answer must be exact.
    An empty cache after a restartMediumRight after a failover or restart, every read goes to the database together.Put a lock around refills so that only one caller rebuilds a key, vary the expiry times, and test the database against an empty cache.
    High availability off in productionMediumA node failure or maintenance event means downtime and can lose recent data.Leave it on in production and practise a failover.
    Wrong clustering policyMediumThe policy is effectively fixed at creation, and a mismatch with the client causes errors or forces a rebuild.Decide with the client library in hand, and test before production.
    Dangerous commands open to the applicationLow–MedFLUSHALL or KEYS from a bug or a script can wipe or stall the cache.Use data access policies that limit commands and keys where the service allows.
    Forgotten cachesLow–MedA development cache or an old geo-replication member keeps billing every hour.Name an owner in a tag and look through the list monthly.

    Performance optimisation

    • Pick the tier for the bottleneck: Memory Optimized for big data, Compute Optimized when command rate is the limit.
    • Store small values. Big blobs belong in storage, with only a pointer in the cache.
    • Share a limited pool of connections and leave them open, because each new TLS handshake adds delay.
    • Use the OSS clustering policy with a cluster-aware client when you want to spread work across shards, and the Enterprise policy for simplicity.
    • Batch with pipelining to cut round trips.
    • Run the application and the cache in the same Region, in the same zone if you can.
    • Replace KEYS with SCAN, and look for large keys when latency spikes.
    • Add random spread to expiries so that keys stored together don’t vanish together.

    Reduce monthly cost

    FinOps is the habit of managing cloud spend together with engineering. These are the FinOps checks that matter most for Azure Cache for Redis.

    • Start on Azure Managed Redis. Staying on the old tiers only delays a migration you will have to pay for later.
    • Choose the smallest size that holds the working set with headroom, and check used memory against it.
    • Use Flash Optimized for large data sets with a small hot set, where its price per gigabyte helps.
    • Turn high availability off only for caches that hold nothing you can’t rebuild, such as development and test.
    • Delete unused caches and extra geo-replication members, since each bills hourly.
    • Check the pricing page for reservations if usage is steady.
    • Cut value sizes and key counts before buying memory.
    • Avoid cross-Region traffic for chatty clients by placing the cache in the client’s Region.
    • Don’t run persistence where a rebuild from the database is cheap and quick.
    • Tag each cache with its team, and set a budget alert on the resource group.

    I left prices out: Azure rates change by Region and size, and the guides I found didn't agree. What is said here about relative cost comes from Microsoft's documentation, read in October 2026. Use the live page (see Pricing).

    Security optimisation

    • Disable public network access and use a private endpoint with the private DNS zone linked to the network.
    • Turn access keys off and sign in with Microsoft Entra ID, using managed identities for applications.
    • Give each identity a data access policy that limits commands and keys to what it needs.
    • Require TLS 1.2 or higher and refuse plain text.
    • Encrypt with a key you own in Key Vault where your rules demand that.
    • Keep secrets and needless personal data out of the cache, and give what remains a short expiry.
    • Send diagnostic logs and metrics to a Log Analytics workspace, and alert on unusual connection counts.
    • Restrict who can change the network, keys and policies with Azure role-based access control.
    • Use resource locks on production caches to stop accidental deletion.
    • Review Microsoft Defender for Cloud recommendations for the cache.

    Governance & compliance

    Guardrails

    • An Azure Policy initiative that denies caches with public network access or access keys enabled
    • A shared Bicep or Terraform module that sets TLS, a private endpoint, tags and a resource lock
    • Written rules per application for key names, expiries and what may be cached
    • A sign-off before any cache is allowed to hold personal data

    Continuous checks (Azure Policy, Defender for Cloud and your own scripts)

    • A scheduled script that lists caches that still use the retiring tiers, allow public access or have keys on
    • Azure Policy compliance reports and Defender for Cloud recommendations for Redis
    • Alerts on server load, memory use and evictions
    • An activity log alert for changes to networking, keys and access policies
    • A monthly list of caches that sit mostly empty or idle

    The Azure Activity Log records who changed a cache, Azure Policy enforces its settings, Microsoft Defender for Cloud rates them, and the Service Trust Portal keeps the compliance reports. Microsoft operates the hosts and the engine. Your part is the data: what is cached, for how long, who can read it, and whether the application still works when the cache is empty.

    Reduce carbon footprint

    • Match the size to the data you actually read, and revisit it when traffic shifts.
    • Delete development caches when a project ends, and turn off replicas where loss is harmless.
    • Use Flash Optimized for large cold data sets instead of holding all of it in memory.
    • A cache that answers most reads saves the database a great deal of work.
    • When rules and latency allow, place the cache in a Region with a cleaner power grid.
    • Microsoft’s sustainability tools report by subscription and service group, so quote no Redis figure.

    Pricing

    Purchase options

    Azure Managed Redis Hourly, by tier and size

    Billed for every hour by the tier and size you pick. The size name carries the family, as in Balanced_B5. Prices differ by Region.

    High availability Replica adds to the price

    Leaving high availability on keeps a replica, and the price reflects that. Turning it off lowers the price and removes the protection.

    Active geo-replication Each linked cache is billed

    Every member of a geo-replication group is a cache of its own, so cost grows with the number of Regions, plus cross-Region data transfer.

    Azure Cache for Redis Hourly, by older tier and size

    The older Basic, Standard, Premium and Enterprise tiers are billed hourly by size. They carry retirement dates, so budget for a migration.

    What you actually pay for

    • Every hour that a cache exists, by tier and size
    • The replica when high availability is on
    • Every member of an active geo-replication group
    • Traffic that leaves a Region or goes out to the internet
    • Private endpoints, log storage in Log Analytics and any customer-managed key vault

    Microsoft lists the hourly prices, the Regions that offer each size and any reserved capacity on its pricing page. See the official Azure Managed Redis pricing page and the Azure pricing calculator.

    Important code references

    A private Azure Managed Redis cache: a Balanced B5 size with high availability, public access off, TLS 1.2, access keys off, the Enterprise clustering policy, a private endpoint with its private DNS zone, and a data access policy for the application’s identity. The CLI tab builds it and tests the sign-in; Terraform describes the same resources. The Python tab signs in with Microsoft Entra ID and keeps web sessions with a sliding expiry and a leaderboard, and the C# tab reads through the cache with a lock so that one caller rebuilds a missing value. Replace the names and the identity with your own.

    # Placeholders: replace the names, and the object ID of the identity your application runs as. Check that your Region offers Azure Managed Redis first.
    RG=cache-demo
    NAME=orders-cache
    LOCATION=centralindia
    VNET=app-vnet
    SUBNET=cache-subnet
    APP_OBJECT_ID=00000000-0000-0000-0000-000000000000
    
    az group create --name $RG --location $LOCATION
    
    # 1. The cache. Balanced B5 has a 4:1 memory to vCPU ratio. High availability keeps a replica, nothing is reachable from the internet,
    #    TLS 1.2 is the minimum, and access keys stay off so that clients sign in with Microsoft Entra ID.
    az redisenterprise create --resource-group $RG --name $NAME --location $LOCATION --sku Balanced_B5 \
      --high-availability Enabled --public-network-access Disabled --minimum-tls-version 1.2 \
      --client-protocol Encrypted --clustering-policy EnterpriseCluster --eviction-policy VolatileLRU --access-keys-auth Disabled
    
    # 2. A private endpoint in the virtual network, with the private DNS zone that Azure Managed Redis uses.
    CACHE_ID=$(az redisenterprise show --resource-group $RG --name $NAME --query id --output tsv)
    az network private-endpoint create --resource-group $RG --name $NAME-pe --vnet-name $VNET --subnet $SUBNET \
      --private-connection-resource-id $CACHE_ID --group-id redisEnterprise --connection-name $NAME-link
    az network private-dns zone create --resource-group $RG --name privatelink.redis.azure.net
    az network private-dns link vnet create --resource-group $RG --zone-name privatelink.redis.azure.net --name cache-dns-link \
      --virtual-network $VNET --registration-enabled false
    az network private-endpoint dns-zone-group create --resource-group $RG --endpoint-name $NAME-pe --name default \
      --private-dns-zone privatelink.redis.azure.net --zone-name redis
    
    # 3. Let the application's identity use the database. The "default" policy gives full data access; scope it down where you can.
    az redisenterprise database access-policy-assignment create --resource-group $RG --cluster-name $NAME --database-name default \
      --name app --access-policy-name default --object-id $APP_OBJECT_ID
    
    # 4. Where do clients connect? The host name ends in redis.azure.net and the port is 10000.
    az redisenterprise show --resource-group $RG --name $NAME --query "{host:hostName,state:provisioningState,sku:sku.name,ha:highAvailability}"
    az redisenterprise database show --resource-group $RG --cluster-name $NAME --query "{port:port,tls:clientProtocol,policy:clusteringPolicy,eviction:evictionPolicy}"
    
    # 5. Check the sign-in from a machine that can reach the private endpoint.
    az redisenterprise test-connection --resource-group $RG --cluster-name $NAME --auth entra
    
    # 6. Move up a size when memory or CPU stays high, or turn on Flash Optimized later if the extension offers it for your Region.
    az redisenterprise update --resource-group $RG --name $NAME --sku Balanced_B10
    
    # 7. Keep the bill honest: tag the cache and set a budget alert for the resource group.
    az tag update --resource-id $CACHE_ID --operation merge --tags owner=orders-team cost-center=1234
    # Placeholders: replace the names and point the data sources at your own virtual network and subnet. Check that your Region offers Azure Managed Redis first.
    variable "location" {
      type    = string
      default = "centralindia"
    }
    
    variable "vnet_name" {
      type    = string
      default = "app-vnet"
    }
    
    variable "subnet_name" {
      type    = string
      default = "cache-subnet"
    }
    
    provider "azurerm" {
      features {}
    }
    
    resource "azurerm_resource_group" "cache" {
      name     = "cache-demo"
      location = var.location
    }
    
    data "azurerm_virtual_network" "app" {
      name                = var.vnet_name
      resource_group_name = azurerm_resource_group.cache.name
    }
    
    data "azurerm_subnet" "cache" {
      name                 = var.subnet_name
      virtual_network_name = var.vnet_name
      resource_group_name  = azurerm_resource_group.cache.name
    }
    
    # Balanced B5 has a 4:1 memory to vCPU ratio. High availability keeps a replica, nothing is reachable from the internet,
    # and access keys stay off so that clients sign in with Microsoft Entra ID.
    resource "azurerm_managed_redis" "orders" {
      name                      = "orders-cache"
      resource_group_name       = azurerm_resource_group.cache.name
      location                  = azurerm_resource_group.cache.location
      sku_name                  = "Balanced_B5"
      high_availability_enabled = true
      public_network_access     = "Disabled"
    
      default_database {
        access_keys_authentication_enabled = false
        client_protocol                    = "Encrypted"
        clustering_policy                  = "EnterpriseCluster"
        eviction_policy                    = "VolatileLRU"
      }
    
      tags = {
        owner = "orders-team"
      }
    }
    
    # A private endpoint in the virtual network, with the private DNS zone that Azure Managed Redis uses.
    resource "azurerm_private_dns_zone" "redis" {
      name                = "privatelink.redis.azure.net"
      resource_group_name = azurerm_resource_group.cache.name
    }
    
    resource "azurerm_private_dns_zone_virtual_network_link" "redis" {
      name                  = "cache-dns-link"
      resource_group_name   = azurerm_resource_group.cache.name
      private_dns_zone_name = azurerm_private_dns_zone.redis.name
      virtual_network_id    = data.azurerm_virtual_network.app.id
    }
    
    resource "azurerm_private_endpoint" "orders" {
      name                = "orders-cache-pe"
      location            = azurerm_resource_group.cache.location
      resource_group_name = azurerm_resource_group.cache.name
      subnet_id           = data.azurerm_subnet.cache.id
    
      private_service_connection {
        name                           = "orders-cache-link"
        private_connection_resource_id = azurerm_managed_redis.orders.id
        subresource_names              = ["redisEnterprise"]
        is_manual_connection           = false
      }
    
      private_dns_zone_group {
        name                 = "default"
        private_dns_zone_ids = [azurerm_private_dns_zone.redis.id]
      }
    }
    
    output "host_name" {
      value = azurerm_managed_redis.orders.hostname
    }
    # pip install "redis>=5" redis-entraid azure-identity
    # Signs in to Azure Managed Redis with Microsoft Entra ID (no access key), then keeps web sessions with a sliding expiry and a leaderboard in a sorted set.
    import json
    import secrets
    
    import redis
    from redis_entraid.cred_provider import create_from_default_azure_credential
    
    HOST = "orders-cache.centralindia.redis.azure.net"
    SESSION_TTL = 1800
    
    
    def connect(host=HOST):
        """The credential provider gets a token with DefaultAzureCredential (a managed identity in Azure, your sign-in on a laptop) and renews it before it expires.
        The EnterpriseCluster policy shows one endpoint, so the plain client works. With the OSSCluster policy use redis.RedisCluster instead."""
        provider = create_from_default_azure_credential(("https://redis.azure.com/.default",))
        return redis.Redis(host=host, port=10000, ssl=True, decode_responses=True, credential_provider=provider,
                           socket_timeout=1.0, socket_connect_timeout=2.0, health_check_interval=30)
    
    
    def create_session(r, user_id, data=None):
        """Stores the session and returns its random id. Only the id goes to the browser."""
        session_id = secrets.token_urlsafe(24)
        r.set(f"session:{session_id}", json.dumps({"user": user_id, **(data or {})}), ex=SESSION_TTL)
        return session_id
    
    
    def get_session(r, session_id):
        """Reads the session and pushes its expiry forward in one command, so an active user stays signed in and an idle one drops out."""
        raw = r.getex(f"session:{session_id}", ex=SESSION_TTL)
        return json.loads(raw) if raw else None
    
    
    def end_session(r, session_id):
        r.delete(f"session:{session_id}")
    
    
    def add_points(r, board, player, points):
        """Sorted sets keep members ordered by score, so a ranking needs no sorting in the application."""
        return r.zincrby(f"board:{board}", points, player)
    
    
    def top(r, board, count=10):
        return r.zrevrange(f"board:{board}", 0, count - 1, withscores=True)
    
    
    if __name__ == "__main__":
        cache = connect()
        sid = create_session(cache, "user-7", {"cart": 2})
        print(get_session(cache, sid), "| ttl:", cache.ttl(f"session:{sid}"))
        add_points(cache, "weekly", "asha", 40)
        print(top(cache, "weekly", 3))
    // dotnet add package StackExchange.Redis
    // dotnet add package Microsoft.Azure.StackExchangeRedis
    // dotnet add package Azure.Identity
    // Signs in to Azure Managed Redis with Microsoft Entra ID (no access key), then reads through the cache: one caller rebuilds a missing value and the others wait for it.
    using System.Text.Json;
    using Azure.Identity;
    using Microsoft.Azure.StackExchangeRedis;
    using StackExchange.Redis;
    
    string host = Environment.GetEnvironmentVariable("CACHE_HOST") ?? "orders-cache.centralindia.redis.azure.net";
    
    // DefaultAzureCredential finds a managed identity in Azure and your own sign-in on a laptop. The extension renews the token before it expires.
    ConfigurationOptions options = ConfigurationOptions.Parse($"{host}:10000");
    options.Ssl = true;
    options.AbortOnConnectFail = false;
    options.ConnectTimeout = 2000;
    options.SyncTimeout = 1000;
    await options.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
    
    await using ConnectionMultiplexer mux = await ConnectionMultiplexer.ConnectAsync(options);
    IDatabase db = mux.GetDatabase();
    
    Product? product = await Cache.GetOrLoadAsync(db, "product:42", () => LoadFromDatabaseAsync(42), TimeSpan.FromMinutes(5));
    Console.WriteLine(product);
    
    static Task<Product?> LoadFromDatabaseAsync(int id) => Task.FromResult<Product?>(new Product(id, "Notebook"));
    
    record Product(int Id, string Name);
    
    static class Cache
    {
        private static readonly RedisValue Missing = "__missing__";
    
        public static async Task<T?> GetOrLoadAsync<T>(IDatabase db, string key, Func<Task<T?>> load, TimeSpan ttl) where T : class
        {
            RedisValue hit = await db.StringGetAsync(key);
            if (hit.HasValue) return Decode<T>(hit);
    
            string lockKey = "lock:" + key;
            string owner = Guid.NewGuid().ToString("N");
            if (await db.LockTakeAsync(lockKey, owner, TimeSpan.FromSeconds(10)))
            {
                try
                {
                    T? value = await load();
                    if (value is null)
                        await db.StringSetAsync(key, Missing, TimeSpan.FromSeconds(30)); // remember "not found" briefly
                    else
                        await db.StringSetAsync(key, JsonSerializer.Serialize(value), Jitter(ttl));
                    return value;
                }
                finally
                {
                    await db.LockReleaseAsync(lockKey, owner);
                }
            }
    
            for (int i = 0; i < 20; i++) // another caller is loading: wait up to about a second
            {
                await Task.Delay(50);
                hit = await db.StringGetAsync(key);
                if (hit.HasValue) return Decode<T>(hit);
            }
            return await load(); // the loader was slow: go to the database directly
        }
    
        // Update the database first and then delete the cached copy; the next read reloads it.
        public static async Task SaveAsync(IDatabase db, string key, Func<Task> writeToDatabase)
        {
            await writeToDatabase();
            await db.KeyDeleteAsync(key);
        }
    
        private static T? Decode<T>(RedisValue value) where T : class => value == Missing ? null : JsonSerializer.Deserialize<T>((string)value!);
    
        // Adds random spread to the expiry so that keys written together don't all lapse at once.
        private static TimeSpan Jitter(TimeSpan ttl) => ttl + TimeSpan.FromSeconds(Random.Shared.Next(0, (int)(ttl.TotalSeconds / 10) + 1));
    }

    Best videos to explore

    Videos picked for this service. Each one is labelled with its source, opens on YouTube if you prefer, and loads only when you press play.

    Introducing Azure Managed Redis - Cost Effective Caching for Your AI AppsOfficial · Microsoft · Beginner · Watch on YouTube
    Introduction to Azure RedisOfficial · Microsoft · Beginner · Watch on YouTube
    Azure Managed Redis: Fully Managed Redis for the Hyperscale CloudCommunity video · Intermediate · Watch on YouTube
    Azure Cache for Redis (.NET 6)Community video · Intermediate · Watch on YouTube

    Interview questions

    BasicWhat is Azure Cache for Redis, and what is Azure Managed Redis?

    Both are managed Redis services on Azure that keep data in memory for fast reads. Azure Cache for Redis is the older service, with Basic, Standard, Premium, Enterprise and Enterprise Flash tiers. Azure Managed Redis is its successor, built on Redis Enterprise software, and it is where Microsoft wants new work to go.

    BasicIs Azure Cache for Redis being retired?

    Yes. The Enterprise tiers retire on 31 March 2027, and creating new Enterprise caches has been blocked since April 2026. Basic, Standard and Premium come later, in September 2028 according to the one notice I could find. Check Microsoft’s retirement FAQ for the current dates, and plan a move to Azure Managed Redis.

    BasicWhat are the Azure Managed Redis tiers?

    Memory Optimized has the most memory for each virtual CPU, Balanced sits in the middle, Compute Optimized gives the most processing for the memory, and Flash Optimized stores most of the data on NVMe flash so that very large data sets cost less. Sizes are named by family and number, such as Balanced_B5.

    IntermediateWhat is the difference between the Enterprise and OSS clustering policies?

    With the Enterprise policy clients see one endpoint and the service handles sharding, so ordinary clients and multi-key commands work. With the OSS policy the shard layout is published and the client must follow Redis Cluster rules, which can spread load across shards. The policy is chosen when the database is created, and apart from one narrow case the only way to change it is to create a new database.

    IntermediateHow do you sign in without access keys?

    Turn access keys off, give the application a managed identity and assign it a data access policy on the database. The client asks Microsoft Entra ID for a token for the Redis scope and presents it as the password, with the identity’s object ID as the user name. A credential provider in the client library renews the token before it expires.

    IntermediateWhat does high availability do, and what happens if you turn it off?

    It keeps a replica of the data and takes over when the primary fails or during maintenance, and in Regions with zones the nodes are spread across them. With it off, the price is lower, but a failure or update means downtime and recent writes can be lost. It suits development caches, not production.

    AdvancedHow would you migrate from Azure Cache for Redis to Azure Managed Redis?

    Pick the target tier and clustering policy to match the old cache’s memory and client behaviour, create the new cache with a private endpoint and Entra sign-in, then move the data. For a pure cache you can start empty and let it warm, with a cold-start plan for the database. Where the data matters, use Microsoft’s migration tooling (in preview for Basic, Standard and Premium when I read it) or an export and import, and switch clients by changing the host name, port and credentials.

    AdvancedHow do you design a cache that survives a Regional failure?

    Create an active geo-replication group with a cache in each of two Regions so that writes replicate in both directions, and have the application use the nearest one. Remember that persistence can’t be used on those databases, that conflicts are resolved by the engine, and that the application must still work with an empty cache as a last resort.

    AdvancedWhat is a cache stampede, and how do you stop one?

    A popular key expires and many requests miss at the same moment, all landing on the database. Have one caller rebuild the value under a short lock while the rest wait, stagger expiry times, refresh hot keys before they lapse, and test with an empty cache to see whether the database holds.

    AdvancedHow would you choose between Azure Managed Redis and Azure Cosmos DB for fast reads?

    Ask whether the data is the source of truth. Cosmos DB is a durable, globally distributed database with guaranteed consistency levels, and it is the place to keep the real data. Azure Managed Redis is faster for hot data and rich in-memory structures, but is best treated as a rebuildable copy, or as shared fast state, in front of a database.

    Similar or alternative services on other clouds

    CapabilityAWSAzureGoogle Cloud
    ServiceAmazon ElastiCacheAzure Cache for Redis and Azure Managed RedisMemorystore
    EnginesValkey, Redis OSS, MemcachedRedis, on the Redis Enterprise engine for Managed RedisValkey, Redis, Memcached
    Hands-off modeElastiCache ServerlessSized tiers, no serverless modeSized by node type and shard count
    Scaling outShards and replicas, onlineLarger sizes and clustering policyShards and replicas, online
    Private accessVPC subnets and security groupsPrivate endpointPrivate Service Connect or private services access
    Sign-inIAM authentication and user groupsMicrosoft Entra ID or access keysIAM authentication or token
    Across RegionsGlobal DatastoreActive geo-replicationCross-instance replication
    BackupsSnapshots to S3Persistence and exportManaged backups and persistence
    How you are billedGigabyte-hours and compute units, or node-hoursHourly price by tier and sizeNode-hours by node type

    Typical clients are Azure Virtual Machines, Azure App Service, Azure Kubernetes Service pods and Azure Functions, with Azure SQL Database or Azure Cosmos DB behind the cache. Metrics and alerts live in Azure Monitor.

    Did you find this article helpful?

    Your answer helps us improve this page for the next reader.

    Sources and further reading

    CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.