Azure Cache for Redis: The Complete Advanced Guide
A book-style walk through how a managed in-memory cache is built, how Redis works inside, how to secure, size, monitor, and protect it, and how to move forward as Microsoft shifts the service toward Azure Managed Redis.
Imagine a busy library. Every time a student asks a question, the librarian walks to a huge basement archive, finds the right folder, and walks back. That works, but when a thousand students ask the same popular question, the librarian spends the whole day walking stairs. Now imagine the librarian keeps the twenty most requested folders on the desk. Most questions are answered in seconds, the basement is visited far less often, and everybody goes home happier. That desk is a cache, and Azure Cache for Redis is a very fast, very smart desk that Microsoft builds, repairs, and guards for you.
In this guide we will go far beyond the product brochure. We will learn what Redis is, why it is so quick, how Azure wraps it into a managed service, which tiers exist, how data moves in and out, how to keep it safe, how it survives failures, and how to avoid the mistakes that make caches slow, expensive, or dangerous. We will also deal honestly with an important piece of news: Microsoft has announced a retirement timeline for Azure Cache for Redis and recommends Azure Managed Redis as the path forward. A good architect needs to understand both the service that exists in many systems today and the service they will be moving to.
1What Azure Cache for Redis Really Is
Before settings and diagrams, we need a clear picture of the technology and the problem it solves.
The short definition
Redis is an open-source software that stores data in the main memory of a computer, which is the same fast memory your programs use while they run. Because memory is thousands of times faster than a disk, Redis can answer requests in well under a millisecond. It stores data as keys and values, where a key is a unique name and a value is the information behind that name. Azure Cache for Redis is a managed service that runs Redis for you on Azure. Microsoft creates the machines, installs the software, keeps copies for safety, applies updates, and offers tools to watch and scale it.
People use it for many jobs, but the most common one is caching: keeping a copy of data that is expensive to fetch so that the next request can be served instantly. It is also widely used as a session store, a counter, a leaderboard, a queue, and a lightweight message channel.
Think of a chef in a restaurant. Fresh ingredients live in a cold store at the back, which is slow to reach. Salt, oil, and chopped onions stay in small bowls right next to the stove. Redis is that row of small bowls. It does not replace the cold store, but it keeps the things used all the time within arm’s reach.
Why a cache is needed at all
Databases are built to be correct and durable, not to be the fastest possible. Every question may involve reading from disk, checking permissions, joining tables, and waiting in line behind other users. When many users ask the same thing, a database does the same work again and again. A cache removes that repeated work. The result is faster pages, lower cost on the database, and a system that stays calm when traffic suddenly jumps.
An important note about the product line
Microsoft now offers a newer service called Azure Managed Redis, built on the Redis Enterprise software, and has announced a retirement timeline for Azure Cache for Redis. According to the official retirement notice, the Basic, Standard, and Premium tiers are scheduled to retire on 30 September 2028, with existing instances disabled from 1 October 2028. The Enterprise and Enterprise Flash tiers are scheduled to retire earlier, on 31 March 2027, with existing instances disabled from 1 April 2027. Microsoft recommends moving to Azure Managed Redis well before those dates.
Everything in this guide about how Redis works, how caching patterns behave, and how to secure and monitor a cache stays useful in the new service. But if you run an Enterprise tier cache today, your deadline is close, so treat migration as a project with a date, not a someday idea. Always confirm dates on the official retirement page, because they are Microsoft’s to change.
| Offering | Based on | Status in this guide |
|---|---|---|
| Azure Cache for Redis: Basic, Standard, Premium | Open-source Redis | Widely deployed today, retirement scheduled for 30 September 2028 |
| Azure Cache for Redis: Enterprise and Enterprise Flash | Redis Enterprise software | Retirement scheduled for 31 March 2027 |
| Azure Managed Redis | Redis Enterprise software | The recommended successor |
2Core Concepts and Vocabulary
A few words appear again and again. Learn them once and the rest of the guide will read smoothly.
Key and value
A key is a unique name, like a label on a drawer. The value is what is inside the drawer. You ask for a key and Redis hands back its value.
Cache hit and miss
A hit means the data was found in the cache. A miss means it was not, so the application must fetch it from the original source.
Time to live
A countdown attached to a key. When it reaches zero the key is removed automatically, which keeps old data from living forever.
Eviction
When memory is full, Redis removes some keys to make room, following a rule called an eviction policy.
Shard
One slice of the data. A clustered cache splits keys across several shards so that no single machine holds everything.
Replica
A live copy of a primary node, kept ready to take over if the primary fails.
Persistence
Saving the in-memory data to disk so it can be reloaded after a restart. Not every use needs it.
Throughput and latency
Throughput is how many operations are completed per second. Latency is how long one operation takes. Good design watches both.
More words you will meet
Two more ideas deserve a plain explanation. The first is the control plane versus the data plane. The control plane is where you create a cache, change its size, or change its settings, usually through the Azure portal or automation. The data plane is where your application reads and writes keys. A long scaling operation on the control plane does not mean individual reads are slow; they are separate worlds that touch only at the edges.
The second is the difference between a cache and a database. A cache holds copies, and losing a cache entry is acceptable because the original still exists elsewhere. A database holds the truth, and losing data is a disaster. Redis can be configured to act more like a database by saving data to disk, but most designs treat it as a copy that can always be rebuilt.
Some teams treat the cache as the only place where certain data lives, such as a shopping basket, and are shocked when a failover or eviction removes it. If the data matters, either keep the truth elsewhere or design deliberately for durability.
A cache is a whiteboard in a meeting room, and a database is the filing cabinet. You write the current numbers on the whiteboard because everyone needs them fast. If someone wipes the board, you copy the numbers again from the cabinet. Nobody would put the only copy of the contract on the whiteboard.
3Architecture and Components
Now we look at the building blocks of a managed cache and how a request travels through them.
The big picture
A managed cache is not a single program on a single machine. In the standard and premium offerings it is a primary node and a replica node, each running the Redis software on its own virtual machine, placed apart so that one hardware failure does not take out both. Around them sit a management service that creates and repairs the machines, a monitoring pipeline that collects numbers, and a network layer that decides who is allowed to connect. In clustered setups several such pairs exist, one for each shard.
flowchart TD
A[Application] --> B[Endpoint name and port]
B --> C[Primary node]
C -- asynchronous copy --> D[Replica node]
E[Management service] -.-> C
E -.-> D
F[Monitoring and metrics] -.-> C
G[Optional persistence storage] -.-> C
The endpoint
Your application never needs to know which machine is the primary. It connects to a host name and a port, and the platform makes sure that name always leads to the node currently serving requests. After a failover the name leads to the new primary, and well-written clients simply reconnect.
The primary and replica nodes
The primary accepts reads and writes. The replica receives a continuous stream of changes from the primary and keeps its own copy in memory. If the primary fails, the replica is promoted. Because the copying is asynchronous, the replica can be a tiny moment behind, so a few very recent writes may be lost in an unlucky failover. This is a trade-off that Redis makes in return for speed.
Shards in a clustered cache
A single machine has limits in memory and in processing power. Clustering solves this by splitting the data across several shards. Every key is mapped to one of many fixed slots, and each shard owns a share of the slots. A client that understands clustering looks at the key, works out the slot, and talks straight to the right shard. This allows the cache to grow beyond one machine and to handle far more traffic.
The management layer
Behind the scenes a management service performs the jobs you would otherwise do by hand: building machines, applying updates, replacing failed nodes, and carrying out your scale requests. You never log in to it. You feel its work when you press scale in the portal and wait, or when a maintenance event briefly restarts a node.
Endpoint
The stable name and port that clients use, which follows the active primary.
Primary node
Handles reads and writes and streams changes to its replica.
Replica node
Holds a live copy and takes over when the primary fails.
Shards
Slices of the data in a clustered cache, each with its own primary and replica.
Management service
Creates, updates, scales, and repairs caches without your help.
Telemetry
Collects health numbers that you can chart and alert on.
Picture a pizza shop with two ovens. One oven is baking orders, and the other is kept warm with the same recipe in case the first breaks. A shop with many ovens and a clear rule about which oven handles which street is like a clustered cache. The customer only dials one phone number and never needs to know which oven is working.
Because the platform may restart or replace nodes, treat every connection as temporary. Applications should reconnect automatically and retry briefly.
4Tiers, Sizing, and the Move to Azure Managed Redis
The tier you choose decides features, resilience, and price. Today that choice has two layers: the classic tiers you may already run, and the newer service you are likely to move to.
The classic tiers
Azure Cache for Redis has offered several tiers, each aimed at a different level of need. They share the same basic idea, but they differ in how many copies exist, which features are available, and what promises Microsoft makes about availability.
| Tier | Nodes | Typical use | Notable points |
|---|---|---|---|
| Basic | A single node | Development, testing, and non-critical caching | No replica, so no protection if the node fails, and no availability promise |
| Standard | Primary plus replica | Production caching where a short failover is acceptable | Two nodes with an availability promise |
| Premium | Primary plus replica, optionally many shards | Larger or busier production workloads | Adds clustering, persistence, private network injection, and geo-replication options |
| Enterprise | Redis Enterprise software | Advanced needs such as modules and active geo-replication | Retirement scheduled for 31 March 2027 |
| Enterprise Flash | Redis Enterprise with disk-backed storage | Very large datasets at lower cost per gigabyte | Retirement scheduled for 31 March 2027 |
Sizes, shard counts, bandwidth, and connection limits differ by tier and change over time. Confirm the exact numbers on the official pages before you finalise a design or write a business case.
Azure Managed Redis in plain words
Azure Managed Redis is the newer service, built on Redis Enterprise software and running on current Redis versions. It is meant to replace both the open-source-based tiers and the Enterprise tiers. Instead of choosing between Basic, Standard, and Premium, you choose a family of instance types based on how much memory you need compared with processing power.
Memory Optimized
The most memory for each unit of compute, at an eight to one ratio. Suited to memory-heavy workloads that do not need the very highest throughput, and a lower-cost choice for development and testing.
Balanced
A four to one ratio of memory to compute, for standard workloads that need a sensible mix of both.
Compute Optimized
A two to one ratio, giving more processing power per gigabyte, for workloads that need the highest throughput.
Flash Optimized
Keeps hot data in memory and moves less used data to fast disk storage. This lowers the cost of very large datasets in exchange for some performance.
flowchart LR
A[Basic Standard Premium] --> M[Azure Managed Redis]
B[Enterprise and Enterprise Flash] --> M
M --> M1[Memory Optimized]
M --> M2[Balanced]
M --> M3[Compute Optimized]
M --> M4[Flash Optimized]
Azure Managed Redis also brings a richer feature set. It supports Redis modules such as JSON, search including vector search, probabilistic structures, and time series on the in-memory families. It supports active geo-replication across regions on the in-memory families, high availability across availability zones where regions allow it, data persistence, import and export, scaling, private networking, and sign-in through Microsoft Entra ID. Some of these features are not available on the Flash Optimized family, so check the matrix before choosing it.
Choosing a family is like choosing a vehicle. Memory Optimized is a large cargo van: lots of space, moderate speed. Compute Optimized is a sports car: less space, very fast. Balanced is a family estate car. Flash Optimized is a van with a trailer behind it: it carries enormous loads, but the trailer is slower to unload.
Sizing a cache
Sizing starts with a few honest questions. How much data will you keep, and how big is each item on average? How many requests per second do you expect at the busiest moment? How long can items live? What fraction of your data is actually hot? Add headroom, because Redis needs spare memory for internal bookkeeping, for copying during persistence, and for sudden growth. A cache sized exactly to today’s data will struggle tomorrow.
Estimate the hot data
Measure how many distinct items users request and how large each is. The hot set is usually far smaller than the whole database.
Estimate peak traffic
Find the busiest second of the busiest day, not the daily average. Caches fail at peaks.
Choose the family or tier
Pick the one whose memory and compute ratio matches the shape of the workload, and confirm needed features such as modules or geo-replication.
Load test
Replay realistic traffic and watch memory, processor load, and latency. Adjust before launch, not after.
Review after launch
Real users always differ from tests. Revisit sizing after the first month.
Azure Managed Redis is clustered by default, with a non-clustered option available for smaller caches. Make sure your client library understands clustering and that your commands do not touch keys in different slots at once.
5Caching Patterns That Work
A cache is only as good as the pattern used to fill and refresh it. These are the proven approaches and when each one fits.
Cache-aside
This is the most common pattern. The application first asks the cache. If the data is there, it is used at once. If not, the application reads from the database, saves a copy in the cache with a time to live, and returns the answer. The application is in charge, which makes the pattern simple and tolerant of cache failures: if the cache is down, the application can still read from the database, only more slowly.
sequenceDiagram
participant App as Application
participant Cache as Redis cache
participant DB as Database
App->>Cache: Ask for item
alt Found in cache
Cache-->>App: Return item quickly
else Not found
Cache-->>App: Miss
App->>DB: Read item
DB-->>App: Item
App->>Cache: Store item with time to live
App-->>App: Return item
end
The other patterns
Read-through
The cache itself fetches missing data from the source. The application only talks to the cache. It needs extra components that Redis alone does not provide.
Write-through
Every write goes to the cache and the database together. Reads are always fresh, but writes are slower because two places must be updated.
Write-behind
Writes land in the cache first and are saved to the database later in batches. Very fast, but risky because data not yet saved can be lost.
Refresh-ahead
Popular items are reloaded just before they expire, so users never wait for a miss on the most important data.
Deciding how long data lives
The time to live is a promise about staleness. A short value keeps data fresh but causes more misses. A long value saves work but risks showing old information. Choose it from the business meaning of the data: a product description can live for hours, a stock level for seconds, a user profile for minutes, and a security decision for as little as it takes to stay safe. When data changes in the database, you can also delete or update the cache entry directly, which keeps freshness high without very short lifetimes.
Three famous problems
Cache stampede
A popular item expires, and thousands of requests miss at the same moment, all hitting the database together. Defences include letting only one request rebuild the item while others wait, adding small random differences to lifetimes, and refreshing popular items before they expire.
Cache penetration
Requests keep asking for items that do not exist anywhere, so every request misses and reaches the database. Defences include caching the fact that something does not exist for a short time, and validating requests before they reach the cache.
Cache avalanche
Many items expire at the same moment, or the whole cache restarts, and the database is suddenly flooded. Defences include spreading expiry times, warming the cache before traffic returns, and protecting the database with limits.
Problem
Every cached item is given the same lifetime, set when the application starts, such as one hour for everything.
Why It’s Harmful
Items loaded together expire together, creating waves of misses that hammer the database at regular intervals.
Correct Approach
Choose lifetimes by the meaning of each kind of data and add a small random spread so that expiry is scattered over time.
Invalidation: keeping the cache honest
There is a famous saying among engineers that the two hardest problems in computing are naming things and knowing when to throw away cached copies. Invalidation is the act of removing or updating a cached item because the original has changed. There are three common approaches. The first is to rely only on time to live, accepting that data may be slightly old until it expires. The second is to delete the cached entry whenever the application changes the source, so the next read loads a fresh copy. The third is to update the cached entry at the same moment as the source, which keeps reads fast but requires care to avoid race conditions where two writers finish in a different order than they started.
Deleting is usually safer than updating, because it avoids writing a value that may already be out of date by the time it lands. When several applications share one cache, agree on who is allowed to change each kind of item. Confusion about ownership is one of the quiet reasons caches show wrong data.
Serialisation and the shape of cached values
Values travel across the network as bytes, so the application must convert its objects into a storable form and back again. The format you choose affects size, speed, and compatibility. Compact binary formats save memory and bandwidth, while readable text formats are easier to inspect when something goes wrong. Whatever you choose, include a version marker so that when the shape of the data changes, old cached items can be recognised and ignored instead of crashing a newer application. A rolling deployment, where old and new versions of the application run side by side for a while, makes this habit especially valuable.
Adding a small version number to key names lets a new release start with a clean set of keys while the old ones expire on their own. It is a cheap way to avoid mixing incompatible formats.
6Internal Working of Redis
Here we open the hood and see why Redis is so fast, and what that speed costs.
Why memory makes it fast
A disk has to move a physical part or read through a controller, while memory can be reached in a few tens of nanoseconds. Redis keeps all its working data in memory and uses compact structures designed for quick lookup. A key is turned into a number by a hashing step, and that number leads almost directly to the place where the value sits. There is no long search through a table and no waiting for a disk to spin.
The single main thread
The open-source Redis software executes commands one after another on a single main thread. This sounds like a weakness, but it is a clever choice. With only one command running at a time, there is no need for locks, no risk of two commands changing the same value at once, and no time wasted switching between tasks. Each command is so small that millions can pass through in a second. Newer versions use extra threads for reading and writing network data, but the commands themselves still queue up in order.
The trade-off is that a slow command makes everyone behind it wait. A command that scans a huge collection, or fetches a gigantic value, blocks the line. This is why you will hear experts warn against expensive commands and oversized keys. The Redis Enterprise software behind Azure Managed Redis runs several Redis processes on each machine so that more of the available processors are put to use, but the same lesson applies to each shard: keep commands small and quick.
Picture a single very fast cashier at a shop. Each customer with a basket of three items passes through in seconds, so the line moves quickly. But if one customer arrives with a trolley holding a thousand items, everybody behind must wait. Redis is that cashier, which is why big, slow commands are the enemy of a healthy cache.
Memory, expiry, and eviction
Memory is limited, so Redis needs rules for what happens when it fills up. There are two separate ideas. Expiry removes keys whose time to live has run out. Redis checks keys when they are touched and also samples keys in the background to find expired ones, so a key may linger briefly after its time is up. Eviction removes keys that are still valid when memory is full, following the chosen policy.
| Policy idea | What it removes | Good for |
|---|---|---|
| No eviction | Nothing; new writes fail when memory is full | Cases where losing data silently is worse than failing loudly |
| Least recently used, all keys | Keys not touched for the longest time, from any key | Pure caches where everything can be rebuilt |
| Least recently used, keys with expiry | Old keys, but only those that have a time to live | Mixed use, protecting keys that have no expiry |
| Least frequently used | Keys used least often over time | Workloads with stable popular items |
| Random | Random keys | Rarely the best choice, but simple |
| Shortest time to live | Keys closest to expiring | Workloads where soon-to-expire data is least valuable |
Classic Azure caches commonly default to evicting the least recently used keys among those that have an expiry. If you store keys without expiry and fill the cache, that policy may have nothing to remove and writes will fail. Always check the policy that your cache actually uses.
Memory overhead and fragmentation
The memory shown as used is more than the raw size of your data. Every key carries bookkeeping, and the memory manager can leave small unusable gaps over time, a problem called fragmentation. Classic tiers let you reserve a slice of memory to absorb this overhead and the copying work done during saves. Ignoring this reserve is a common cause of sudden out-of-memory trouble in caches that looked half empty.
Persistence: snapshots and logs
Redis can save its data to disk in two ways. A snapshot writes the whole dataset to a file at intervals, which is compact and fast to reload but can lose changes made since the last snapshot. An append-only log records every write command as it happens, which loses very little but takes more space and effort. To take a snapshot safely, Redis makes a lightweight copy of its memory image, and changes made during the save need extra memory, so a busy, nearly full cache can run into trouble while saving.
Replication
A replica starts by copying the whole dataset from the primary, then receives a continuous stream of every change. This copying is asynchronous: the primary does not wait for the replica before answering the client. That keeps writes fast but means that a failover can lose the last few changes. For a cache that is usually acceptable, because the lost entries can be rebuilt.
Clustering and hash slots
In a cluster, the key space is divided into sixteen thousand three hundred and eighty-four slots. A formula turns each key into a slot number, and each shard owns a range of slots. Commands that touch several keys work only when all the keys live in the same slot. To keep related keys together, designers can mark part of the key name so that only that part is used to choose the slot. Forgetting this rule is the most common reason that code works on a single node and fails when moved to a cluster.
flowchart LR
K[Key name] --> H[Hash function]
H --> S[Slot number]
S --> A[Shard 1 owns slots low range]
S --> B[Shard 2 owns slots middle range]
S --> C[Shard 3 owns slots high range]
Big keys and hot keys
Two kinds of unusual keys cause most performance trouble. A big key is one whose value is very large, such as a list with millions of items. Reading, deleting, or copying it takes so long that it blocks the command line. Even deleting a big key can cause a pause, which surprises many teams. The remedy is to split big collections into smaller ones, trim them regularly, and watch for growth that nobody planned.
A hot key is one that receives a huge share of all requests, such as the front-page banner on a news site. In a cluster, all requests for that key land on one shard, so that shard works hard while others sit idle. Remedies include keeping a copy of the hottest items in the application’s own memory for a few seconds, or storing several copies under slightly different names and picking one at random for each read.
Transactions, scripts, and messages
Redis offers a few features that go beyond simple reads and writes. A transaction groups commands so that they run together without other commands slipping in between, though it does not undo earlier steps if a later one fails. A server-side script lets you send a small program that runs entirely inside Redis, which makes a multi-step action atomic and saves round trips. Both features need all their keys to live in the same slot when used in a cluster. Publish and subscribe lets one part of a system broadcast a message to anyone listening, but, as we saw earlier, it keeps no history.
Transactions
Run a group of commands together without interruption from other clients.
Server-side scripts
Run a small program inside Redis so a multi-step action is atomic and quick.
Publish and subscribe
Broadcast a message to listeners connected at that moment, with no storage.
Key expiry events
Notifications can be raised when keys expire, though they are best-effort and should not be the only trigger for important work.
7Data Flow and Lifecycle
Let us follow a single request from the application to the cache and back, and then follow the life of the cache itself.
The journey of one request
Suppose a user opens a product page. The application builds a key name for that product and sends a read command. The client library reuses an existing connection, because opening a new connection for every request is slow and wasteful. The command travels over an encrypted channel to the endpoint, reaches the primary node, and joins the queue of commands. When its turn comes, Redis looks up the key in memory and returns the value. The application decodes the value and builds the page. If the key was missing, the application takes the longer path through the database and stores the result for next time.
sequenceDiagram
participant App as Application
participant Lib as Client library
participant EP as Endpoint
participant Pri as Primary node
participant Rep as Replica node
App->>Lib: Ask for key
Lib->>EP: Send command over encrypted connection
EP->>Pri: Route to current primary
Pri->>Pri: Look up key in memory
Pri-->>Lib: Return value
Lib-->>App: Decoded result
Pri->>Rep: Stream any changes made
Reads, writes, and connections
A read is the lightest operation. A write changes memory, may update an expiry, and is added to the stream sent to the replica and, where configured, to the persistence log. Connections deserve special care. Each connection uses memory and counts toward a limit, so applications should share a small number of long-lived connections rather than opening many short ones. Many Redis clients can send several commands over one connection at the same time, which keeps latency low.
Batching and pipelining
Every round trip across the network costs time, even if Redis answers instantly. When an application needs many small results, it can send a batch of commands together and read all replies at once. This technique, called pipelining, can raise throughput dramatically. The balance is to keep batches modest so that one huge batch does not hold up the queue for other users.
Connect
The client opens a secure connection to the endpoint and signs in with a key or an identity token.
Route
The platform sends the command to the current primary, or in a cluster, the shard that owns the key’s slot.
Execute
Redis runs the command in memory, checking expiry and applying changes.
Replicate
Writes are streamed to the replica and, if enabled, recorded for persistence.
Reply
The result returns to the client, which hands it to the application.
The life of the cache itself
Create
Choose a name, region, and size. Creation takes some time while machines are prepared.
Warm up
A new cache is empty, so early traffic mostly misses. Pre-loading popular data protects the database.
Operate
Day-to-day service with monitoring, backups where configured, and automatic repair of failed parts.
Scale
Change size, add shards, or move tiers. These are management operations that take time and may cause brief connection drops.
Update
Software and operating system updates happen on a schedule, ideally inside a maintenance window you choose where the tier allows it.
Retire or migrate
Because of the announced retirement dates, every classic cache will eventually be migrated to a new service or removed.
Assuming a scale or update is invisible. Even well-run platforms can drop connections for a moment during these events. An application without automatic reconnection and retry will turn a harmless blip into an outage.
What a good client library does for you
The library between your application and the cache does a great deal of invisible work, and knowing it helps you configure it well. It keeps connections open and multiplexes many requests over each one. It notices when a connection breaks and tries to rebuild it. In a cluster it learns which shard owns which slot, follows redirections when slots move, and refreshes its map after a failover. It converts values between your objects and bytes. Every one of these behaviours has settings, and the defaults are not always right for your workload.
Timeouts
Set limits for connecting and for each command, short enough to fail fast, long enough to survive a brief slow moment.
Retries
Retry a small number of times with growing delays, and add a little random spread so that many clients do not retry in perfect step.
Reconnection
Keep automatic reconnection on, and make sure the application does not create a new client each time a call fails.
Keep-alive
Send small periodic messages so that idle connections are not silently dropped by network devices in between.
Thread capacity
Make sure the application has enough worker threads ready, because a starved application can look like a slow cache.
When timeouts appear, teams often blame the cache. Frequently the delay is on the client side: exhausted threads, a busy processor, or large replies filling the network. Measure both ends before deciding where the problem lives.
8Data Structures and Use Cases
Redis is more than a place to store text. It offers ready-made structures that solve real problems with a single command.
Strings
The simplest value: text, numbers, or small pieces of serialised data. Numbers can be increased or decreased in one step, which makes strings perfect for counters.
Hashes
A key that holds many named fields, like a small record for a user profile. You can read or change one field without touching the rest.
Lists
Ordered collections where items are added at either end. Useful for queues and recent-activity feeds.
Sets
Collections of unique items. They answer questions such as whether a user is in a group, or which items two groups share.
Sorted sets
Unique items, each with a score, always kept in score order. The classic tool for leaderboards and for ranking.
Streams
An append-only log of events that several readers can consume in groups, suited to lightweight messaging pipelines.
Bitmaps and counters of unique items
Compact structures for tracking yes or no flags per user or for estimating how many distinct visitors appeared, using very little memory.
Geospatial indexes
Store places and ask which ones are near a point, useful for store locators and delivery apps.
Use cases in plain language
Data caching
Keep results of heavy database queries or calls to other services close at hand, so repeated requests are instant.
Session storage
Store who is logged in and what they are doing, so any web server can serve any user. Sessions are small, expire naturally, and are read on almost every request, which suits Redis perfectly.
Rate limiting
Count how many requests each user or address has made in a short window and refuse extra ones. Atomic counters and expiry make this simple and reliable.
Leaderboards and rankings
Sorted sets keep scores in order automatically, so showing the top ten players is one quick request instead of a heavy database sort.
Queues and lightweight messaging
Lists and streams can hand work from one part of a system to another. For critical business events that must never be lost, a dedicated messaging service is usually the safer home.
Search and vector similarity
With the right modules, available in the newer service, Redis can search text and find items with similar meaning, which supports recommendation and retrieval features in modern applications.
The simple publish and subscribe feature delivers a message only to those listening at that moment. Anyone disconnected misses it, and nothing is stored. Use streams, or a dedicated messaging service, where delivery must be guaranteed.
Choosing key names
Good key names are short, readable, and consistent. A common habit is to build them from parts, such as the kind of object, its identity, and the field, separated by a colon. Consistent names make monitoring easier, let teams avoid collisions, and allow cleaning up related keys together. Very long names waste memory when you have millions of keys, so aim for clear but compact.
Matching structure to problem
The skill of using Redis well is largely the skill of choosing the right structure. A common beginner habit is to turn everything into one large text value and store it under a single key. This works, but it forces the application to read and rewrite the entire value for the smallest change. A hash lets you change one field. A sorted set lets you add one score. A list lets you push one item. Each of these changes is tiny and atomic, so the cache does less work, uses less network, and avoids the race conditions that appear when two users rewrite the same big value at once.
| Problem | Good structure | Why it fits |
|---|---|---|
| Page view counter | String used as a number | Increase in one atomic step |
| User profile fields | Hash | Read or change one field without touching others |
| Recent activity feed | List | Add at one end, trim the other end |
| Unique visitors today | Set or a compact counting structure | Duplicates are ignored automatically |
| Top players | Sorted set | Kept in score order at all times |
| Event pipeline with several readers | Stream | Keeps history and lets readers share work |
9Security in Depth
Because a cache often holds sessions, tokens, and customer data, it deserves the same care as a database. Security works best in layers.
Think of a bank. There is a fence around the property, a guard at the gate, a locked door to the hall, a teller who checks your identity, and a vault for the valuables. Each layer is imperfect alone, but together they make an attack very hard.
Layer 1: network isolation
The first question is who can even reach the cache. A cache can have a public endpoint protected by firewall rules that list allowed addresses, or it can be reached only through private paths. A private endpoint gives the cache a private address inside your own virtual network, so traffic never crosses the open internet. In the premium classic tier, the cache can also be placed directly into your virtual network. The safest default is to turn off public access and allow only private paths.
Layer 2: encrypted connections
Data travelling between application and cache should always be encrypted. Classic caches accept encrypted connections on one port and, if you ask, plain connections on another. The plain port is off by default and should stay off. Set a minimum protocol version so that outdated and weak versions are refused, and make sure your clients actually verify the server’s certificate.
Layer 3: authentication
Authentication answers “who are you?”. There are two main ways. The first is an access key, a long secret shared by everyone who uses it. It is simple, but anyone who holds it has full power, and it must be rotated carefully. The second is Microsoft Entra authentication, which lets applications and people sign in with their identity. Applications running in Azure can use a managed identity, so no secret is stored at all. Entra sign-in also allows access to be granted per person or per service and removed at once from one central place.
Entra authentication: benefits
- No shared secret to leak or forget to rotate
- Access can be granted and removed centrally
- Actions can be tied to named identities for auditing
- Works with managed identities for applications in Azure
- Supports least-privilege roles for data access
Entra authentication: trade-offs
- Some older client libraries may lack support
- Tokens expire, so clients must refresh them correctly
- Needs setup of roles and directory permissions
Layer 4: least privilege and data protection
Give each application only the access it needs. A service that only reads sessions should not be able to erase the whole cache. Keep access keys, if you must use them, in a secure vault rather than in configuration files, and rotate them on a schedule using the primary and secondary keys so that rotation causes no outage. Do not store highly sensitive data in the cache unless you have to, and when you do, keep lifetimes short and consider encrypting the value inside the application before storing it.
Layer 5: logging and review
Turn on diagnostic logging and send it to a place your security team watches. Review who has access regularly, remove old identities, and set alerts on unusual patterns such as a burst of failed sign-ins or a sudden jump in connections.
Close the doors
Disable public access where possible and use private endpoints.
Encrypt the traffic
Keep the plain port off, set a modern minimum protocol, and verify certificates.
Prefer identities to keys
Use Entra authentication and managed identities, and keep any remaining keys in a vault.
Limit what each caller can do
Grant narrow roles and review them regularly.
Watch and respond
Collect logs, set alerts, and make sure someone owns the response.
Problem
One access key is pasted into every application and every developer’s machine, and nobody knows who uses it.
Why It’s Harmful
A single leak gives full control of the cache, changing the key breaks every system at once, and nothing can be traced to a particular user.
Correct Approach
Give each application its own identity, prefer managed identities, store any unavoidable secrets in a vault, and rotate using the two keys in turn.
Roles, ownership, and review
Security is not only technology; it is also habit. Decide who owns each cache, who may change its settings, and who may read or write data. Management actions, such as changing the network rules or regenerating keys, should be limited to a small group, while applications receive only data access. Review these assignments on a schedule and remove anyone who has changed teams. When a person leaves, their access should end the same day.
What should never go into a cache
Because a cache is easy to use, it is tempting to put anything there. Be selective. Highly sensitive items such as full payment details, government identity numbers, and passwords should not be cached at all unless there is a strong reason and strong protections. When personal data must be cached, keep lifetimes short, store only the fields needed, and make sure your privacy rules cover the cache as much as the database. Remember that a cache is also a copy, and copies must be deleted when people ask for their data to be removed.
Label each kind of data you plan to cache as public, internal, or sensitive. The label then drives the lifetime, the network path, and who may read it.
10High Availability, Persistence, and Geo-replication
Things break. A good design says exactly what happens when a node, a building, or a whole region disappears.
Two ideas to keep apart
High availability means surviving small failures, such as one machine dying, with a short pause. Disaster recovery means surviving large failures, such as a region being unavailable, usually with a longer pause and a plan. Because a cache holds copies, the honest first question is whether you need to protect the cache contents at all. Often the best disaster recovery for a cache is a clean, empty cache in another place that warms up from the database.
High availability is a spare tyre in the boot of the car. Disaster recovery is a second car at a relative’s house in another city. For a cache, there is also a third idea: you can often simply buy a new notebook, because the old notes were copies of a book you still own.
Availability inside one region
Single node
A basic cache has one node. A failure means downtime and an empty cache after recovery. Fine for development, risky for production.
Primary and replica
Two nodes on separate machines. If the primary fails the replica is promoted, usually within a short time, and clients reconnect.
Zone redundancy
Nodes are spread across separate data centres in one region, protecting against the loss of a whole building. Availability depends on tier and region.
Clustered shards
Several shards, each with a primary and replica, so a failure affects only one slice of the data while the rest keeps serving.
Persistence in practice
Persistence lets a cache reload its data after a restart or a serious failure, instead of starting empty. It is useful when rebuilding the cache is very expensive or when the cache is used for data that is hard to recreate. It has a cost: extra disk writes, extra memory during snapshots, and some added delay. Decide using your recovery needs, not habit. Many pure caches run without any persistence and are happier for it.
Geo-replication
Geo-replication copies data between regions. In the classic premium tier, a primary cache in one region is linked to a secondary in another, and the secondary is read-only until you fail over. In the newer service and in the older enterprise tiers, active geo-replication lets several caches in different regions all accept writes and merge their changes, which allows users in different parts of the world to read and write locally. This is powerful, but it changes how you think about conflicts, because two regions might change the same item at nearly the same time.
flowchart LR
U1[Users in Region A] --> C1[Cache in Region A]
U2[Users in Region B] --> C2[Cache in Region B]
C1 C2
C1 -.-> D1[Local database A]
C2 -.-> D2[Local database B]
| Need | Common tool | What to expect |
|---|---|---|
| Survive a node failure | Replica with automatic failover | A short pause and brief connection errors |
| Survive a data centre loss | Zone redundancy where available | Short pause, handled by the platform |
| Reload after restart | Persistence | Slower recovery of data, with some risk of recent loss |
| Survive a regional outage | Geo-replication or a warm standby cache | A planned switch of region |
| Serve users in many regions locally | Active geo-replication | Local speed, with merge rules for conflicts |
Making applications failover-friendly
The platform can only do half the work. Applications must reconnect automatically, retry after a short delay that grows with each attempt, and set sensible time limits so that a failing cache does not freeze the whole system. They should also be able to run without the cache, even slowly, by falling back to the database, and they should limit how hard they hit the database during that fallback.
Use the reboot and failover test features offered by the platform, in a non-production cache first, to watch how your application behaves. Many teams discover missing retry logic only during these drills, which is exactly why they are valuable.
Warming an empty cache safely
A new, restarted, or failed-over cache may be empty. If your traffic is heavy, an empty cache sends every request to the database at once, which can overwhelm it. A warm-up plan solves this. Before switching traffic, load the most popular items using a list taken from recent usage. Then let traffic return in steps rather than all at once. Combine this with limits on how many database queries can run at the same time, so that even in the worst moment the database stays alive.
| Situation | State of the cache | Protective step |
|---|---|---|
| Brand-new cache | Completely empty | Pre-load popular items and shift traffic gradually |
| After a short failover | Mostly intact, a few recent writes missing | Rely on retries and normal misses to refill |
| After a full restart without persistence | Empty | Warm-up plan and database request limits |
| After a regional switch | Depends on geo-replication | Verify contents, warm if needed, and test before declaring recovery |
11Networking and Connectivity
How your application reaches the cache decides its speed, its safety, and how easy it is to fix when something goes wrong.
Distance is latency
Even at the speed of light, a signal needs time to travel. A cache that answers in a fraction of a millisecond is wasted if the application sits in another region and each request must cross hundreds of kilometres. Place the cache in the same region as the application, and where possible in the same availability zone or close to it. This one decision often matters more than any tuning of the cache itself.
Keeping salt in a bowl next to the stove is only useful if the stove is in the same kitchen. If the bowl is kept in a neighbouring house, the chef gains nothing, however fast the bowl itself is.
Ways to reach a cache
Public endpoint with firewall
Reachable over the internet, limited to addresses you list. Simple, but the widest exposure, so use only when private paths are not possible.
Private endpoint
Gives the cache a private address inside your virtual network. Traffic stays on the Microsoft network and can be reached from peered networks and from on-premises networks over a private link.
Virtual network injection
Offered by the classic premium tier, where the cache nodes sit directly inside a subnet you provide. It gives strong isolation but needs careful subnet and rule planning, and is not the model used by the newer service.
flowchart TD
APP[Application subnet] --> PE[Private endpoint]
OFF[On-premises network] -->|VPN or private circuit| HUB[Hub virtual network]
HUB --> PE
PE --> R[Redis cache]
DNS[Private name zone] -.-> PE
NSG[Network rules] -.-> PE
Names and ports
Applications connect by host name. With a private endpoint, the name must resolve to the private address from every network that needs access. This is the most common source of mysterious failures: a name that resolves correctly from one network and to the wrong place from another. Test name resolution from every client network before going live. Ports also matter. Classic caches use one port for encrypted traffic and another for plain traffic, and the plain one should stay off. The newer service uses a different port from the classic tiers, so firewall rules and connection settings must be updated when you migrate.
Connection hygiene
Connections are a limited resource. Each client holds memory on the server, and every tier has a ceiling on how many connections it accepts. Web applications that create a new connection for every request can exhaust that ceiling within seconds under load. Create one shared client when the application starts, reuse it for the life of the process, and let the library repair broken connections on its own. Set connection and command time limits so that a stuck call fails fast instead of piling up.
One long-lived, shared client per application process is almost always better than many short-lived ones. It is faster, gentler on the cache, and far easier to monitor.
Problem
The application opens a fresh connection, runs one command, and closes it again for every web request.
Why It’s Harmful
Each new secure connection adds delay and server work. Under load the connection limit is reached, new users are refused, and the cache looks broken when it is actually healthy.
Correct Approach
Create a single shared client at startup, reuse it everywhere, and rely on the library’s automatic reconnection.
Firewalls, on-premises users, and developers
Developers often want to connect to a cache from their own computers to look at keys or test ideas. Handing out public access for this is risky. Safer options include a shared jump machine inside the private network, a secure tunnel through the organisation’s VPN, or a dedicated non-production cache with relaxed rules. Whatever you choose, make it easy and documented, because people who find the safe path difficult will invent an unsafe one.
For users and servers in on-premises data centres, the private link into Azure must carry both the traffic and the name lookups. A common failure is that the link works but the office name servers do not know how to resolve the cache’s private name. Set up forwarding for the private zone and test from a real office computer before announcing that the cache is ready.
12Migrating to Azure Managed Redis
The announced retirement dates turn migration from an option into a plan. Here is how to approach it calmly.
Know your dates and your tier
The first step is an inventory. List every cache in every subscription, its tier, its size, its owner, and the applications that use it. Then match each cache to its deadline. Enterprise and Enterprise Flash caches come first, because their retirement is scheduled for 31 March 2027. Basic, Standard, and Premium caches follow, with retirement scheduled for 30 September 2028. Microsoft recommends not waiting for the deadline, because early moves leave time to test and to fix surprises.
flowchart TD
A[Inventory all caches] --> B[Match each cache to its retirement date]
B --> C[Review features used]
C --> D[Choose target family and size]
D --> E[Check client library and commands for cluster support]
E --> F[Create new cache and test]
F --> G[Move data or let cache warm]
G --> H[Switch application to new endpoint]
H --> I[Watch metrics then remove old cache]
What changes for your application
Host name and credentials
The new cache has its own endpoint and its own keys or identities. Applications must be updated to point to them.
Clustering by default
The new service is clustered by default, with a non-clustered option for smaller caches. Client libraries must understand clustering, and some, such as the popular .NET client, need no special setup.
Multi-key commands
Commands that touch several keys must keep those keys in the same slot. Review the code for such commands and add slot-grouping where needed.
Ports and network rules
Connection ports and private endpoint arrangements differ, so firewalls, private zones, and security rules need review.
Features and sizes
Choose the family that matches your memory and compute needs, and confirm that features you rely on, such as geo-replication, modules, or persistence, are offered in the family you picked.
Authentication
Take the chance to move from shared access keys to Entra identities, so the migration also improves security.
Moving the data, or not
The cleverest question in migration is whether you need to move the data at all. If your cache holds only copies of data from a database, you can often create the new cache, point the application at it, and let it fill naturally. Early traffic will miss more often, so plan the switch for a quiet period and protect the database from the extra load. If the cache holds data that is hard to rebuild, use the methods described in the official migration guides, which cover options for copying existing data and keeping continuity. Whichever route you take, rehearse it first on a copy of the real workload.
Assess
Inventory caches, features used, client libraries, and any commands that cannot work across slots.
Prepare
Build the new cache in a test environment, update the client libraries, and run the full test suite against it.
Rehearse
Practise the switch, time it, and write down the rollback steps.
Cut over
Switch the application to the new endpoint in a quiet period, with the old cache kept intact for a short time.
Verify and retire
Watch hit rate, latency, and errors. When all is stable, remove the old cache and update your documentation.
Some regions, sizes, and management operations were still being rolled out in the new service at the time of writing. If a feature you need is missing, Microsoft’s guidance is to contact support early. Leaving the work to the final weeks removes all your options.
Testing a migration properly
A migration test is more than checking that the application starts. Run the same load you expect in production against the new cache and compare hit rate, latency, memory use, and error counts with the old one. Include the unpleasant cases: a failover test, a burst of traffic after an empty start, and a client reconnecting after a network blip. Verify that every command your code uses behaves correctly across slots. Ask each application team to sign off with a short written note, so that there is a clear record of what was tested and by whom.
Moving is the ideal moment to remove unused keys, fix missing lifetimes, replace shared keys with identities, and move to private endpoints. A migration that only copies old habits to new hardware wastes most of its value.
13Monitoring, Logging, and Metrics
A cache that nobody watches fails in silence. Good monitoring turns “the site feels slow” into a clear, fixable fact.
A car dashboard shows speed, fuel, and engine temperature so that you can act before the engine overheats. Cache metrics are the same: memory used is the fuel gauge, server load is the temperature, and hit rate tells you whether the journey is efficient.
The numbers that matter
| Metric | What it tells you | What to do when it looks bad |
|---|---|---|
| Cache hit rate | Share of requests answered from the cache | Review lifetimes, key design, and what is being cached |
| Used memory | How full the cache is | Plan more memory, shorten lifetimes, or remove oversized keys |
| Evicted keys | How many valid keys were removed to make room | A steady rise means the cache is too small for the hot data |
| Server load or processor use | How busy the Redis process is | Find slow commands, reduce load, or scale out |
| Connected clients | How many connections are open | Check for connection leaks and share clients |
| Operations per second | Overall traffic volume | Compare with capacity and look for unusual spikes |
| Network bandwidth | Data moving in and out | Look for oversized values and consider compression |
| Latency and errors | How long requests take and how many fail | Check load, network distance, and recent changes |
Hit rate is the heartbeat
The ratio of hits to total requests is the simplest sign of a healthy cache. A high hit rate means most users are served from memory. A falling hit rate may mean that lifetimes are too short, that the cache is too small and keeps evicting useful data, or that a new feature is asking for data that was never cached. Watch it over days as well as minutes, because slow drifts reveal design problems.
Logs, alerts, and dashboards
Send platform metrics and diagnostic logs to a central workspace so that you can chart them, search them, and keep history for longer. Create alerts for memory above a sensible level, server load that stays high, a rising count of evictions, a sudden fall in hit rate, and any burst of connection errors. Give each alert an owner and a short written response guide. An alert that nobody understands will soon be ignored.
Finding the slow culprit
When load is high, the question is which commands are responsible. Redis can show a record of slow commands and can report the biggest keys in memory. Large values, huge collections, and commands that scan everything are the usual suspects. Fixing a handful of them often removes most of the pain without adding any hardware.
Notice
An alert fires or users report slowness.
Locate
Check memory, server load, connections, and network to see which resource is stressed.
Identify
Find slow commands, oversized keys, or a hot key that draws a flood of requests.
Fix
Split big values, replace expensive commands, add lifetimes, or scale out as a last step.
Confirm and record
Check that metrics returned to normal and write down what was learned.
Troubleshooting four common symptoms
Symptom 1: Timeouts during busy periods
Check server load and the slow command record first. Then look at the client side: too many connections, small thread pools, or large replies can all cause timeouts even when the server looks calm.
Symptom 2: Memory keeps rising to the limit
Look for keys without a lifetime, a growing collection that nobody trims, and oversized values. Confirm the eviction policy suits the data, and remember the reserved memory for overhead and snapshots.
Symptom 3: One shard is hot and the rest are idle
A single popular key or an uneven key naming pattern is sending most traffic to one shard. Spread the load by splitting the hot item into several copies or by changing how keys are grouped.
Symptom 4: Errors during maintenance or scaling
This points to clients that do not reconnect or retry. Test with the platform’s reboot features in a non-production cache and fix the client settings.
A rhythm for capacity planning
Capacity planning is not a single event before launch; it is a habit. Each month, look at the peak values of memory, server load, connections, and bandwidth, and compare them with the limits of your tier. Look at how they have grown over the last quarter and project a few months ahead. If the peak of any measure regularly crosses a comfortable level, such as more than about two thirds of its limit, plan to scale before the next busy season. Scaling in a hurry, during an incident, is far more stressful and more risky than scaling calmly on a quiet day.
Glance at the dashboard
Look for unusual spikes, falling hit rates, and rising evictions.
Compare to limits
Check peak memory, load, and connections against what the tier allows.
Review the design
Revisit lifetimes, key sizes, and which data is worth caching, and adjust size or family.
Review the roadmap
Check product announcements, retirement dates, and newer features that might improve the design.
14Design Patterns and Anti-patterns
A pattern is a proven solution. An anti-pattern is a tempting shortcut that usually causes pain later.
Patterns worth adopting
Cache-aside with sensible lifetimes
Let the application own the cache. Check first, load on a miss, store with a lifetime that matches how fresh the data must be, and delete or update the entry when the source changes.
Request coalescing
When many requests miss on the same item, let one of them rebuild it while the others wait for the result. This stops stampedes and protects the database.
Layered caching
Keep a tiny cache in the application’s own memory for the very hottest items, backed by the shared Redis cache, backed by the database. Each layer absorbs traffic from the one behind it.
Graceful degradation
If the cache is unavailable, the application keeps working by reading from the database with limits on how much load it sends, and may show slightly reduced features instead of failing outright.
Passwordless access
Applications sign in using managed identities, so no shared secret exists to leak, forget, or rotate in a panic.
Environment ladder
Run development, test, and production caches with the same design but smaller sizes in lower environments, so surprises appear before users see them.
flowchart LR
REQ[Request] --> L1[Local memory cache]
L1 -->|miss| L2[Shared Redis cache]
L2 -->|miss| DB[Database]
DB --> L2
L2 --> L1
Anti-patterns to avoid
Problem
Storing very large values, such as whole reports or big files, under a single key.
Why It’s Harmful
Reading or writing a huge value blocks the single command line, so every other user waits. It also strains network bandwidth and memory.
Correct Approach
Keep values small. Store large files in object storage and keep only a reference, or split large data into pieces that can be fetched separately.
Problem
Using commands that list or scan every key in a busy production cache.
Why It’s Harmful
Such commands walk through all the data while holding up everyone else. On a large cache, one careless command can freeze the system for seconds.
Correct Approach
Track the keys you need in a dedicated collection, or use the incremental scanning commands in small steps, and never run full listings on live production.
Problem
Treating the cache as the only home of important data, such as orders or payments.
Why It’s Harmful
Evictions, failovers, and restarts can remove data. With asynchronous copying, even a normal failover can lose the latest writes.
Correct Approach
Keep the truth in a durable database. Use the cache for copies and for data that you can afford to lose or rebuild.
Problem
Building a distributed lock out of a simple key and assuming it is perfectly safe.
Why It’s Harmful
Failovers, pauses, and clock differences can let two workers believe they hold the same lock, causing duplicate work or corrupted data.
Correct Approach
Use locks only for efficiency, not for correctness, and protect critical data with checks in the database itself.
Reading a design with a critical eye
When reviewing a cache design, a short list of questions often reveals the weak spots faster than reading every detail. What happens if the cache is empty right now? What happens if it answers slowly for ten minutes? What is the largest value stored, and the most popular key? Which data would be harmful if lost, and where is its durable home? Who can read the cache, and how would we know if someone should not? If the team can answer these calmly and concretely, the design is probably in good shape. If the answers are vague, the design needs more work before it meets real users.
15Best Practices and Common Mistakes
This chapter gathers the habits that separate calm operations from constant firefighting.
Best practices by area
Keep it close
Place the cache in the same region as the application, and test latency from the real application hosts.
Always set a lifetime
Give almost every key a lifetime with a small random spread, so nothing lives forever and expiry is scattered.
Share and retry
Use one long-lived client, set time limits, and retry with growing delays.
Keep them small
Avoid expensive commands and giant values, and batch small requests with care.
Private and identity-based
Use private endpoints, encrypted connections, and Entra identities, and keep secrets in a vault.
Rehearse failures
Test reboots and failovers in a safe environment and write down what happens.
Choose maintenance windows
Where the tier allows, pick update times that avoid your busiest periods.
Tag and automate
Define caches as repeatable templates with consistent names and tags for owner and cost centre.
Common mistakes and how to avoid them
The cache fills, evictions rise, and hit rate drops. Add headroom and watch the eviction metric.
Snapshots and overhead need spare memory. Running the cache at the very top of its capacity risks failures during saves.
Code that touches several keys works on a single node and fails across slots. Test against the same topology you will run in production.
Allowing unencrypted connections exposes data on the network. Keep it off and require modern encryption.
When the cache restarts empty, all traffic falls on the database at once. Warm the cache and protect the database with limits.
Retirement dates are fixed. Put migration on the plan now, starting with the earliest deadline.
A launch checklist
Network ready
Private path chosen, names resolve from every client network, plain port off.
Security ready
Identities and roles set, secrets in a vault, logging enabled.
Resilience ready
Retry logic tested, failover drill performed, fallback to the database proven.
Observability ready
Hit rate, memory, load, and connection alerts routed to owners with guides.
Cost ready
Right-sized, tagged, and reviewed against the budget.
Teaching the team
Tools do not keep a cache healthy; people do. Hold a short session for every new developer explaining what the cache is for, which patterns the team uses, and which commands are forbidden in production. Keep a one-page guide of key naming rules and lifetimes. Share what you learn from incidents in short, blame-free notes. Over time, these small habits do more for reliability than any single feature of the platform.
16Advantages, Trade-offs, and Cost Thinking
Every good design is a balance. Here we weigh what a managed cache gives you against what it asks in return, and how to keep the bill sensible.
Advantages
- Very low latency and very high throughput for hot data
- Takes load off databases, which are slower and more expensive to scale
- Fully managed machines, updates, and failover handling
- Rich data structures that solve counters, rankings, sessions, and queues
- Private networking, encryption, and identity-based sign-in
- A clear path forward through the newer service, with modules and active geo-replication
Disadvantages / Trade-offs
- Memory is expensive compared with disk, so large datasets cost more
- Data in memory can be lost on eviction, failover, or restart unless designed for
- Caching adds complexity: lifetimes, invalidation, and stampede protection
- A single slow command or giant key can hurt every user
- Clustering adds rules about multi-key commands
- The classic service is on a retirement path, so migration work is unavoidable
How the bill is made
The cost of a cache is mainly the size and type of the nodes you choose, charged for every hour they exist, whether busy or idle. More memory, more shards, more compute, and extra replicas all raise the price. Features such as geo-replication add the cost of extra caches in other regions. Data that leaves a region adds network charges. Because prices change and vary by region, always confirm numbers using the official pricing page and calculator, and avoid quoting stale figures in a business case.
Ways to spend less without hurting users
Right-size from metrics
Compare used memory and server load with what you pay for. A cache that never goes above a third of its memory can often be smaller.
Cache only what pays off
Items that are rarely repeated, or cheap to fetch, waste memory. Focus on expensive and popular data.
Choose the right family
In the newer service, pick the ratio of memory to compute that fits your workload instead of paying for compute you do not use. Large datasets with a small hot set may suit the flash-backed family.
Use cheaper options for development
Non-production caches rarely need replicas or large sizes. Use the lowest-cost options that still let you test the real behaviour.
Compress and trim values
Smaller values mean more items per gigabyte and less network traffic.
Consider reservations for steady use
A committed term for steady workloads can lower the price compared with paying by the hour. Check reservation terms against the retirement dates before committing.
Tag every cache with its owner and project, set a budget alert, and review hit rate and memory use each quarter. A cache with a poor hit rate may be costing money while saving nothing.
A worked cost-thinking example
Imagine a company with three systems that use caches: a busy shopping site, an internal reporting tool, and a development environment. A careless design gives each one the same large, replicated, geo-replicated cache. A thoughtful design asks what each one really needs. The shopping site has strict speed needs and global users, so it earns a larger cache with replicas and perhaps geo-replication. The reporting tool is used only in office hours and its results can be rebuilt, so a modest cache with no persistence is enough. The development environment needs the same features as production to test properly, but at the smallest size that still behaves correctly.
The saving does not come from clever tricks. It comes from asking, for each system, what is truly required and refusing to pay for more. Repeating the exercise every quarter keeps the bill honest as workloads grow, shrink, or retire. It also gives a natural moment to plan the move to the newer service, because choosing a family there is just the same exercise with different names.
17Real-world Scenarios
Here are four everyday situations that show how the ideas in this guide fit together. The names are illustrative, not real customers.
Scenario A: An online retailer survives a sales event
A retailer sees traffic rise many times over during a big sale. Product pages, prices, and stock counts are served from the cache, with short lifetimes for stock and long ones for descriptions. They spread expiry times, pre-load the most popular products before the sale starts, and protect the database with limits. Because the cache is in the same region as the application and clients share a few long-lived connections, latency stays low even at peak.
Scenario B: A software company stores sessions for millions of users
A web application keeps session data in the cache so that any server can serve any user. Sessions have a lifetime that matches the login period, are small, and are read on nearly every request. The team uses a replicated, zone-redundant setup and accepts that a rare failover may sign a handful of users out, because the benefit of speed is worth that small cost.
Scenario C: A game company runs live leaderboards
A mobile game uses sorted sets to rank players. Scores are updated in real time, and the top ranks are fetched in one quick request. The company uses active geo-replication in the newer service so that players in Europe and Asia both read and write to a nearby cache, and they decide in advance how to resolve the rare case when two regions update the same player at once.
Scenario D: A bank prepares for the retirement deadline
A bank discovers that several teams run Enterprise tier caches, which retire first. It builds an inventory, ranks caches by deadline and importance, updates its client libraries to be cluster-aware, rehearses migration in a test environment, and moves caches one team at a time. It also takes the chance to replace shared access keys with managed identities and to move to private endpoints.
flowchart TD
U[Shoppers] --> W[Web tier]
W --> R[Managed Redis cache]
R -->|miss| API[Product service]
API --> DB[Database]
API --> R
W --> S[Session data in cache]
When another service may be a better fit
A cache is not the answer to everything. If you need rich queries across many fields, relationships between records, or strong guarantees that data is never lost, a database is the right home. If you must deliver business events reliably to many consumers, a dedicated messaging service is safer than simple publish and subscribe. If your dataset is huge and rarely re-read, caching it all wastes money. Choosing the right tool for each job is a core part of good architecture.
18Frequently Asked Questions
Short answers to the questions teams ask most often.
Microsoft has announced a retirement timeline. Basic, Standard, and Premium are scheduled to retire on 30 September 2028, and Enterprise and Enterprise Flash on 31 March 2027. Microsoft recommends moving to Azure Managed Redis. Always confirm the dates on the official retirement page.
A cache keeps fast copies of data that can be rebuilt, and a database keeps the durable truth. Redis can persist data to disk, but most designs still treat it as a copy.
It keeps data in memory, uses compact structures, and runs commands one after another without locks, so each small command finishes in a tiny fraction of a millisecond.
Yes. Keys can expire or be evicted, and asynchronous copying means a failover can lose the very latest writes. Design so that lost data can be rebuilt from the source.
The replica becomes the primary, the endpoint name leads to it, and connections drop briefly. Applications with automatic reconnection and retry usually recover in seconds.
For a pure cache where everything can be rebuilt, evicting least recently used keys is a sensible choice. If you store keys without lifetimes alongside cached ones, think carefully so important keys are not removed or writes do not fail.
You need it when one machine cannot hold your data or handle your traffic. The newer service is clustered by default, with a non-clustered option for smaller caches, so plan for cluster rules in your code.
Prefer Microsoft Entra authentication with managed identities, so no shared secret exists. If you must use access keys, keep them in a vault and rotate them using the primary and secondary keys in turn.
Usually not. A private endpoint with encrypted connections is the safer default, and the plain unencrypted port should stay off.
At least the host name and credentials, plus a review of client library cluster support, multi-key commands, ports, and network rules. Choose the family that fits your memory and compute needs and test thoroughly before switching.
It depends on the workload, but the trend matters most. A steady high rate means the cache is working. A falling rate signals problems with lifetimes, sizing, or what is being cached.
Test connectivity and name resolution from every client network, behaviour under realistic load, a reboot or failover, the fallback to the database when the cache is empty, and your alerts.
19Summary and Key Takeaways
Azure Cache for Redis brings the speed of in-memory data to your applications while Microsoft handles the machines, updates, and repair. It works best when you treat it as a fast copy of data that lives safely elsewhere, fill it with proven patterns such as cache-aside, give every key a sensible lifetime, keep commands and values small, and let applications reconnect and retry. It must be secured in layers, watched through a few key metrics, and protected with the level of resilience your business really needs. Finally, because Microsoft has announced retirement dates for the classic service and recommends Azure Managed Redis, every team should plan its migration now, starting with the earliest deadline.
Key Takeaways
- A cache holds copies, not the truth — design so that any cached item can be rebuilt from a durable source, and expect expiry, eviction, and the occasional lost write.
- Redis is fast because it is simple — it runs small commands in memory one after another, so oversized values and expensive commands hurt everyone.
- Pattern and lifetime decide success — use cache-aside, choose lifetimes by the meaning of the data, add random spread, and defend against stampedes, penetration, and avalanches.
- Secure in layers — private endpoints, encrypted connections, Entra identities, least privilege, and logging work together, with no shared keys pasted everywhere.
- Plan for failure at every size — replicas, zone redundancy, and geo-replication answer different risks, and applications must reconnect, retry, and fall back gracefully.
- Watch hit rate, memory, load, and evictions — a few well-chosen metrics with owned alerts catch most problems early.
- Migrate before the deadline — Enterprise tiers are scheduled to retire on 31 March 2027, and Basic, Standard, and Premium on 30 September 2028, so inventory, test, and move to Azure Managed Redis in good time.