AZ-204Chapter 10 of 102Objective 4.2

Azure Cache for Redis

This chapter covers Azure Cache for Redis, a fully managed in-memory data store that provides high throughput and low-latency access to data. On the AZ-204 exam, this topic appears in approximately 10-15% of questions, primarily under objective 'Monitor and optimize performance solutions' (4.2). You will need to understand caching patterns, Redis data structures, eviction policies, and how to integrate Redis with Azure applications. Mastery of this service is crucial for building scalable, high-performance cloud solutions.

25 min read
Intermediate
Updated May 31, 2026

Warehouse with Instant Access

Imagine a large e-commerce company that operates a busy warehouse. The main inventory database is like a massive, slow filing cabinet in the basement—it stores everything but takes time to retrieve. To speed things up, the company sets up a small, fast-access shelf right next to the cash registers. When a customer asks for a product, the cashier first checks the shelf. If the product is there (a cache hit), the cashier hands it over instantly. If not (a cache miss), the cashier runs to the basement, gets the item, and also places a copy on the shelf for future requests. This shelf has limited space, so the cashier uses a rule: when the shelf is full, they remove the least recently used item to make room for new ones. This is exactly how Azure Cache for Redis works. Redis stores frequently accessed data in memory (the shelf) for sub-millisecond access, reducing load on the backend database (the basement). The cache eviction policy (like LRU) decides which data to discard when memory is full. The cache also supports expiration times (TTL) so that stale data is automatically removed. By using Redis, applications can serve data much faster and scale to handle more concurrent users without overwhelming the database.

How It Actually Works

What is Azure Cache for Redis?

Azure Cache for Redis is a fully managed, in-memory data store based on the open-source Redis (Remote Dictionary Server). It provides a high-performance cache that can handle millions of requests per second with sub-millisecond latency. It is not just a cache; it can also serve as a message broker (via Pub/Sub), a session store, and a real-time data store. The service abstracts the complexity of managing Redis servers, handling patching, updates, scaling, and high availability.

Why Use Azure Cache for Redis?

The primary reason is performance. Traditional disk-based databases (like SQL Server or Cosmos DB) have higher latency (typically 5-10 ms) and can become bottlenecks under heavy read loads. Redis stores data in RAM, achieving latencies of <1 ms. By caching frequently accessed data, you reduce load on the backend database, improve application responsiveness, and lower costs by scaling the backend less aggressively.

How Redis Works Internally

Redis is a single-threaded event loop that processes commands sequentially. This design avoids locking overhead, ensuring predictable performance. All data is stored in memory using a key-value model. Keys are binary-safe strings, and values can be one of several data structures: strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, and geospatial indexes. Redis persists data optionally via snapshotting (RDB) or append-only file (AOF), but in a cache scenario, persistence is often disabled for maximum throughput.

Key Components and Defaults

Tiers: Basic (single node, no SLA), Standard (two-node replica with SLA), Premium (higher performance, persistence, clustering, and VNet injection).

Clustering: Premium tier supports clustering, which shards data across up to 10 shards (each shard is a primary-replica pair). This allows scaling beyond a single node's memory limit (up to 120 GB per shard, up to 1.2 TB total).

Eviction Policies: When memory is full, Redis evicts keys based on the configured policy. Default is volatile-lru (evict least recently used keys among those with an expiration set). Other options: allkeys-lru, volatile-lfu, allkeys-lfu, volatile-random, allkeys-random, volatile-ttl, noeviction (returns errors on write).

Time-to-Live (TTL): Keys can be set with an expiration time in seconds or milliseconds using commands like EXPIRE or SETEX. Expired keys are lazily removed (on access) and periodically (every 100 ms).

Persistence: RDB snapshots (point-in-time snapshots, default every 60 seconds if 1000 changes) and AOF (append-only log, fsync every 1 second). Premium tier allows both.

Connection Limits: Basic/Standard: up to 250 connections (C0-C1) scaling to 1000 (C6). Premium: up to 1000 connections (P0-P4) scaling to 20000 (P5).

Data Size Limits: String values up to 512 MB. Total cache size depends on tier: from 250 MB (C0) to 1.2 TB (P5 with clustering).

Configuration and Verification Commands

To create a Redis cache in Azure CLI:

az redis create --resource-group myResourceGroup --name myCache --location eastus --sku Standard --vm-size C1

To get connection string:

az redis show --name myCache --resource-group myResourceGroup --query "hostName"

Use Redis CLI to connect:

redis-cli -h myCache.redis.cache.windows.net -p 6380 -a accessKey --tls

Common commands: - PING - test connectivity - SET key value EX 3600 - set key with 1-hour TTL - GET key - retrieve value - INFO - get server stats (memory, connections, etc.) - MONITOR - stream all commands (for debugging)

Integration with Azure Applications

Azure Cache for Redis integrates seamlessly with Azure App Service, Azure Functions, Azure Kubernetes Service (AKS), and more. The recommended client library is StackExchange.Redis for .NET, ioredis for Node.js, and redis-py for Python. Connection strings typically use TLS on port 6380. For high availability, use the connection string with ssl=true,abortConnect=false.

Caching Patterns

Cache-Aside: Application checks cache first. On miss, loads from database and stores in cache. Most common.

Read-Through: Cache automatically loads data from database on miss (requires custom provider).

Write-Through: Data written to cache and database simultaneously.

Write-Behind: Data written to cache asynchronously to database (higher performance but risk of data loss).

Monitoring and Performance

Azure provides metrics in the portal: Cache Hits, Cache Misses, Evicted Keys, Connected Clients, Server Load, and Memory Usage. You can configure alerts based on thresholds (e.g., >90% memory usage). For diagnostics, enable diagnostic settings to stream metrics to Log Analytics, Storage, or Event Hubs.

Scaling and High Availability

Standard and Premium tiers provide 99.9% SLA. Scaling can be vertical (change tier) or horizontal (enable clustering). Premium tier supports data replication with automatic failover in under 10 seconds. Geo-replication (active geo-replication for Premium) allows linking two caches across regions for disaster recovery, but data is asynchronously replicated.

Security

Redis supports authentication via access keys (primary/secondary) or Azure Active Directory (AAD) tokens (preview). Network security via Azure Firewall rules or VNet injection (Premium). TLS 1.2 is enforced by default. For advanced scenarios, use private endpoints.

Exam Relevance

On the AZ-204, expect questions on:

Selecting the appropriate tier (Basic vs Standard vs Premium).

Configuring eviction policies and understanding their impact.

Implementing caching patterns (especially cache-aside).

Handling expiration and stale data.

Using Redis for session state in ASP.NET Core.

Connection resilience (retry logic, abortConnect).

Monitoring with metrics and alerts.

Remember: Redis is in-memory, so data is lost on failure unless persistence or replication is configured. For cache-only scenarios, data loss is acceptable. For session state, use Standard or Premium tier with replication.

Walk-Through

1

Identify Cacheable Data

Analyze application data access patterns to determine which data is frequently read and rarely updated. Typically, this includes reference data (product catalogs, configuration), user session data, and results of expensive queries or computations. Data that changes frequently or is highly sensitive may not be suitable. The goal is to reduce load on the backend database and improve response times.

2

Choose Redis Tier and Size

Select the appropriate Azure Cache for Redis tier based on requirements: Basic (single node, no SLA, dev/test), Standard (two-node replica, 99.9% SLA, production), or Premium (higher performance, clustering, persistence, VNet). Estimate required memory size based on data volume and growth. Use the Azure pricing calculator to compare costs. For production, always choose Standard or Premium.

3

Configure Cache Settings

Set eviction policy (default volatile-lru), enable non-SSL port if needed (not recommended), configure firewall rules or VNet to restrict access. For Premium, enable clustering if scaling beyond 53 GB. Set up diagnostics to stream metrics to Log Analytics. Configure persistence if data durability is needed (RDB or AOF). Set appropriate maxmemory-reserved to ensure system overhead.

4

Implement Cache-Aside Pattern

In application code, check cache first using GET. If key exists (cache hit), return data. If not (cache miss), query database, store result in cache with a TTL using SET, then return data. Use StackExchange.Redis: IDatabase cache = connection.GetDatabase(); string value = cache.StringGet(key); if (value == null) { value = db.Query(key); cache.StringSet(key, value, TimeSpan.FromMinutes(10)); }

5

Handle Expiration and Stale Data

Set appropriate TTL for each cached item based on how often the underlying data changes. For session data, TTL can match session timeout (e.g., 20 minutes). For reference data, TTL may be hours or days. Use absolute expiration (EXPIRE) or sliding expiration (sliding window in Redis via custom logic). If data becomes stale, either accept eventual consistency or implement cache invalidation by deleting or updating the cache when the database changes.

6

Monitor and Scale

Use Azure Monitor to track cache metrics: Cache Hits, Cache Misses, Evicted Keys, Server Load, Memory Usage. Set alerts for high memory usage (>80%) or high eviction rate. If evictions are frequent, increase cache size or adjust eviction policy. Scale vertically by changing tier (requires downtime) or horizontally by enabling clustering (Premium tier, may require data migration). For Standard/Premium, scaling is typically online with minimal downtime.

What This Looks Like on the Job

E-Commerce Product Catalog

A large e-commerce platform uses Azure Cache for Redis to cache product details (name, price, description, images). The product catalog is read-heavy with millions of requests per day. The backend database is a SQL Server. Without caching, each product page load would query the database, causing high latency (50-100 ms) and database load. By implementing cache-aside with a 1-hour TTL, the application achieves sub-millisecond response times for cached products. The cache is a Premium P2 instance (13 GB) with clustering enabled to handle 500 GB of product data. They use allkeys-lru eviction policy because all data is equally important. They also set up geo-replication to a secondary region for disaster recovery. Misconfiguration: initially they used noeviction policy, causing write errors during traffic spikes. Switching to allkeys-lru resolved the issue.

User Session State for ASP.NET Core

A SaaS application running on Azure App Service uses Redis to store user session data. The application is stateless and scales horizontally across multiple instances. Without a centralized session store, users would lose session data on different instances. They use the Microsoft.AspNetCore.Session middleware with Redis as the distributed cache. The cache is a Standard C2 instance (2.5 GB) with volatile-lru eviction. Session timeout is 20 minutes, matching the TTL. They also use Redis for authentication token caching. Common pitfall: forgetting to install the Redis session provider NuGet package (Microsoft.Extensions.Caching.StackExchangeRedis) leads to runtime errors. Also, they set abortConnect=false to allow graceful fallback if Redis is temporarily unavailable.

Real-Time Leaderboard for Gaming

An online multiplayer game uses Redis sorted sets to maintain a real-time leaderboard. Player scores are updated frequently, and the leaderboard is displayed to thousands of concurrent players. Using Redis sorted sets with ZADD and ZRANK commands provides O(log N) performance. They use a Premium P1 instance (6 GB) with AOF persistence to avoid losing scores on restart. They also use Redis Pub/Sub to broadcast leaderboard changes to game servers. Misconfiguration: they initially used a single Basic tier instance, which caused data loss during maintenance windows. Upgrading to Standard with replication solved the problem.

How AZ-204 Actually Tests This

What AZ-204 Tests on This Topic

Under objective 4.2 (Monitor and optimize performance solutions), the exam focuses on:

Selecting the correct caching solution (Azure Cache for Redis vs. CDN vs. Azure Front Door).

Understanding Redis tiers and their features (Basic vs Standard vs Premium).

Configuring eviction policies and their impact on cache behavior.

Implementing caching patterns, especially cache-aside.

Handling expiration and stale data.

Using Redis for session state in ASP.NET Core.

Monitoring and scaling Redis caches.

Connection resilience and retry logic.

Common Wrong Answers and Why

1.

"Use Basic tier for production workloads" - Basic has no SLA and no replication. Candidates choose it because it's cheaper. The correct answer is Standard or Premium for production.

2.

"Set eviction policy to noeviction to avoid data loss" - This causes write errors when memory is full. Candidates think it's safe, but it breaks the application. The correct policy is usually volatile-lru or allkeys-lru.

3.

"Redis persists data by default" - Persistence is optional and disabled by default. Candidates assume data is always durable. In reality, data is lost on restart unless RDB or AOF is configured.

4.

"Use a single Redis instance for all regions" - Geo-replication is needed for multi-region. Candidates forget about latency and data sovereignty.

Specific Values and Terms on the Exam

Tiers: Basic (no SLA, single node), Standard (99.9% SLA, two nodes), Premium (99.9% SLA, clustering, persistence).

Eviction policies: volatile-lru (default), allkeys-lru, volatile-ttl, noeviction.

Default TTL: none; must be set explicitly.

Connection ports: 6380 (SSL), 6379 (non-SSL).

Client library for .NET: StackExchange.Redis.

Session state middleware: AddDistributedRedisCache and AddSession.

Metric thresholds: Cache Miss Rate > 10% may indicate poor hit ratio.

Edge Cases and Exceptions

Clustering limitations: Some commands (e.g., MGET with keys on different shards) are not supported. Use hash tags to ensure keys are on the same shard.

Transaction support: Redis transactions (MULTI/EXEC) are not fully ACID; they are optimistic and do not roll back on errors.

Maximum number of databases: Default 16 (configurable).

Persistence trade-offs: RDB may lose up to 60 seconds of data; AOF may have higher overhead.

How to Eliminate Wrong Answers

If the question mentions "no data loss" and "cache", look for persistence or replication options. Eliminate Basic tier.

If the question describes high read traffic, look for cache-aside pattern. Eliminate write-through unless updates are frequent.

If the question involves session state, look for Redis with Standard/Premium tier. Eliminate Basic.

If the question mentions "eviction", understand that noeviction is rarely correct for a cache.

Key Takeaways

Azure Cache for Redis provides sub-millisecond latency by storing data in memory.

Choose Standard or Premium tier for production; Basic has no SLA.

Default eviction policy is volatile-lru; use allkeys-lru for pure cache scenarios.

Always set a TTL for cached data to prevent stale data and memory leaks.

Use cache-aside pattern: check cache first, on miss load from DB and store in cache.

Enable persistence (RDB/AOF) only if data must survive restarts; this reduces performance.

Monitor Cache Hits, Cache Misses, and Evicted Keys in Azure Monitor.

For session state, use Standard or Premium tier and configure AddDistributedRedisCache.

Connection string should use SSL port 6380 and include abortConnect=false for resilience.

Clustering (Premium) allows scaling beyond 53 GB but limits multi-key operations.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

Azure Cache for Redis

In-memory storage, sub-millisecond latency

Limited data size (up to 1.2 TB with clustering)

Supports various data structures (strings, hashes, lists, sets)

No built-in SQL querying

Data loss on restart without persistence

Azure Cosmos DB

Disk-based storage, 5-10 ms latency

Virtually unlimited storage (multi-TB)

Document, graph, table, and key-value models

Supports SQL, MongoDB, Cassandra APIs

Data is durable and replicated automatically

Watch Out for These

Mistake

Redis persists all data to disk by default.

Correct

Redis persistence is optional and disabled by default. You must configure RDB snapshots or AOF logging to persist data. Without persistence, data is lost on restart.

Mistake

Basic tier is suitable for production because it is cheaper.

Correct

Basic tier has no SLA and no replication. If the node fails, all data is lost and the cache is unavailable. For production, use Standard (99.9% SLA) or Premium.

Mistake

Setting eviction policy to noeviction prevents data loss.

Correct

Noeviction causes Redis to return errors on write operations when memory is full. This can break the application. Use a policy like allkeys-lru or volatile-lru to evict data gracefully.

Mistake

Azure Cache for Redis can be used as a primary database.

Correct

Redis is designed as a cache or transient data store. It is not ACID compliant and data can be lost. For durable storage, use a database like Cosmos DB or SQL Database.

Mistake

All Redis commands work with clustering enabled.

Correct

Some commands (e.g., MGET, MSET with keys on different shards) are not supported. Use hash tags to co-locate related keys. Multi-key operations are limited to keys in the same slot.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What is the difference between Basic, Standard, and Premium tiers?

Basic tier offers a single node with no SLA, suitable for development and testing. Standard tier provides two nodes (primary and replica) with a 99.9% SLA, ideal for production. Premium tier adds support for clustering (up to 10 shards), data persistence (RDB/AOF), VNet injection, and geo-replication, with higher performance and a 99.9% SLA.

How do I set an expiration time on a key?

Use the EXPIRE command: `EXPIRE mykey 3600` sets a TTL of 3600 seconds (1 hour). Alternatively, use SETEX: `SETEX mykey 3600 "value"` sets both key and TTL atomically. You can also use SET with the EX option: `SET mykey "value" EX 3600`.

What eviction policy should I use for a cache?

For a typical cache, use `allkeys-lru` to evict the least recently used keys when memory is full. If you have keys with TTLs, `volatile-lru` (default) evicts only keys with TTLs. Avoid `noeviction` as it causes write errors. The choice depends on whether you want to evict any key or only those with expiration.

How do I implement cache-aside in .NET using StackExchange.Redis?

First, install the StackExchange.Redis NuGet package. Then, create a ConnectionMultiplexer and get a database. For each read: `string cached = db.StringGet(key); if (cached == null) { cached = db.Query(key); db.StringSet(key, cached, TimeSpan.FromMinutes(10)); } return cached;`. Ensure you handle connection failures with `abortConnect=false`.

Can I use Azure Cache for Redis for session state in ASP.NET Core?

Yes. Install `Microsoft.Extensions.Caching.StackExchangeRedis` and `Microsoft.AspNetCore.Session`. In Startup.cs, add `services.AddDistributedRedisCache(options => { options.Configuration = connectionString; });` and `services.AddSession();`. Then use `HttpContext.Session` to store and retrieve session data. Ensure the cache tier is Standard or Premium for production.

What happens when Redis reaches its memory limit?

Redis will evict keys based on the configured eviction policy. If the policy is `noeviction`, write operations (SET, LPUSH, etc.) will return an error. For other policies, Redis will remove keys to free memory. The eviction policy can be changed at runtime using the CONFIG SET command.

How do I monitor Azure Cache for Redis?

Use Azure Monitor to view metrics like Cache Hits, Cache Misses, Evicted Keys, Connected Clients, Server Load, and Memory Usage. You can set up alerts based on thresholds. For detailed diagnostics, enable diagnostic settings to stream metrics to Log Analytics, Storage, or Event Hubs.

Terms Worth Knowing

Ready to put this to the test?

You've just covered Azure Cache for Redis — now see how well it sticks with free AZ-204 practice questions. Full explanations included, no account needed.

Done with this chapter?