AZ-204Chapter 63 of 102Objective 4.2

Redis Cache Patterns: Cache-Aside, Session, Pub/Sub

This chapter covers the three most important Redis cache patterns for the AZ-204 exam: Cache-Aside, Session Caching, and Pub/Sub messaging. These patterns are central to building high-performance, scalable Azure applications and appear in approximately 15-20% of exam questions related to caching and messaging. You will learn the internal mechanics, configuration details, and exam-specific nuances for each pattern. Mastery of these patterns is essential for the 'Monitor' domain (Objective 4.2) and the broader 'Develop for Azure storage' section.

25 min read
Intermediate
Updated May 31, 2026

Redis Cache Patterns: Warehouse, Locker, and Radio

Imagine a busy warehouse (database) that stores all products. A retail store (application) needs to serve customers quickly. The store has a small stockroom (cache) for high-demand items. In the Cache-Aside pattern, when a customer asks for an item, the store first checks the stockroom. If found (cache hit), it hands it over immediately. If not (cache miss), a clerk runs to the warehouse, retrieves the item, places a copy in the stockroom for next time, and gives it to the customer. The store is responsible for refreshing the stockroom when items are updated or expire. For Session pattern, imagine a large hotel with thousands of guests. Each guest has a locker (session cache) where they store personal belongings (session data) during their stay. The front desk (load balancer) can direct a guest to any floor (server) because all lockers are centrally accessible. The guest's key (session ID) is the same across all visits. For Pub/Sub, think of a radio station (publisher) broadcasting on a specific frequency (channel). Anyone with a radio tuned to that frequency (subscriber) receives the broadcast in real time. The station doesn't know who is listening; subscribers come and go. If a subscriber misses a broadcast, they don't get a replay (no message persistence). This mirrors Redis Pub/Sub's fire-and-forget, fan-out messaging.

How It Actually Works

Introduction to Redis Cache Patterns

Redis is an in-memory data structure store used as a database, cache, and message broker. On Azure, Redis Cache is available as Azure Cache for Redis. The AZ-204 exam focuses on three primary patterns: Cache-Aside, Session Caching, and Pub/Sub. Each pattern solves a distinct problem and has specific implementation requirements.

Cache-Aside Pattern (Lazy Loading)

What it is: Cache-Aside is a caching strategy where the application code explicitly loads data into the cache on cache misses and is responsible for keeping the cache consistent with the source of truth (e.g., a database). It is the most common caching pattern for read-heavy workloads.

How it works internally: 1. Application requests data from cache (e.g., a Redis key). 2. If the key exists (cache hit), Redis returns the value immediately. 3. If the key does not exist (cache miss), the application retrieves the data from the database, writes it into the cache with a Time-To-Live (TTL), and then uses the data. 4. Subsequent requests for the same key will hit the cache until the TTL expires or the data is evicted.

Key components and defaults: - TTL (Time-To-Live): Default is no expiration if not set. Common practice: set TTL to 5-60 minutes depending on data volatility. On Azure Cache for Redis, the EXPIRE command sets TTL in seconds. - Memory eviction policies: When memory is full, Redis evicts keys based on the maxmemory-policy setting. Default is noeviction (returns errors on writes). Common alternatives: allkeys-lru (evicts least recently used keys), volatile-lru (evicts keys with TTL set using LRU). - Serialization: Data stored in Redis is binary-safe strings. Complex objects must be serialized (e.g., JSON, Protocol Buffers).

Configuration and verification commands: - Connect to Redis using redis-cli or StackExchange.Redis in .NET. - Set a key with TTL: SET mykey "value" EX 3600 (expires in 1 hour). - Check TTL: TTL mykey returns -2 if key does not exist, -1 if no expiry, positive integer for seconds remaining. - Monitor evictions: INFO stats shows evicted_keys count.

How it interacts with related technologies: - Azure SQL Database: Typical combination. Application uses Entity Framework or ADO.NET to query SQL, then caches results in Redis. - Cosmos DB: Similar pattern; cache read-heavy queries to reduce RU consumption. - Consistency considerations: Cache-Aside does not automatically invalidate on writes. Applications must update or delete cache entries when data changes to avoid stale reads.

Session Caching Pattern

What it is: Session caching stores user session data in Redis, allowing stateless web servers and enabling session sharing across multiple instances. This is critical for load-balanced web applications (e.g., Azure App Service with multiple instances).

How it works internally: 1. When a user first visits the application, a unique session ID (e.g., a cookie) is generated. 2. Session data (e.g., shopping cart, user preferences) is stored in Redis with the session ID as the key. 3. On subsequent requests, the application reads the session ID from the request, retrieves the data from Redis, and uses it. 4. Session data can be set to expire after a period of inactivity (e.g., 20 minutes).

Key components and defaults: - Session ID: Typically a GUID or random string. Stored in a cookie (e.g., ASP.NET_SessionId) or in the URL. - Session timeout: Default is 20 minutes in ASP.NET. Configured using SessionState provider. - Data serialization: Same as Cache-Aside; session objects must be serializable. - Redis data type: Usually a Redis Hash or String. Hash allows storing multiple fields (e.g., username, role) under one key.

Configuration and verification commands: - In ASP.NET Core, configure Redis session state in Startup.cs:

services.AddStackExchangeRedisCache(options =>
  {
      options.Configuration = "your-redis-connection-string";
  });
  services.AddSession(options =>
  {
      options.IdleTimeout = TimeSpan.FromMinutes(20);
      options.Cookie.HttpOnly = true;
  });

Verify session data exists: KEYS * (avoid in production; use SCAN).

Check session TTL: TTL <session-id>.

How it interacts with related technologies: - Azure App Service: Session caching enables sticky-session-free load balancing. Without it, users would lose session on server restart or scale-out. - Traffic Manager / Application Gateway: Any load balancer works because session data is external. - SignalR: For real-time web features, SignalR can use Redis backplane for scaling out, but session caching is separate.

Pub/Sub Pattern (Publish/Subscribe)

What it is: Redis Pub/Sub is a messaging paradigm where publishers send messages to channels, and subscribers receive messages in real time. It is a fire-and-forget, fan-out pattern with no message persistence.

How it works internally: 1. A subscriber connects to Redis and issues SUBSCRIBE channelname. 2. A publisher connects and issues PUBLISH channelname "message". 3. Redis forwards the message to all currently connected subscribers of that channel. 4. If a subscriber is not connected at the time of publish, it misses the message.

Key components and defaults: - Channels: String names. Pattern subscriptions (e.g., news.*) are supported using PSUBSCRIBE. - Message delivery: At most once. No acknowledgment, no retry. - Maximum message size: 512 MB (same as Redis string value). - Number of subscribers: No hard limit, but performance degrades with many subscribers due to fan-out.

Configuration and verification commands: - Subscribe: SUBSCRIBE mychannel (blocks). - Publish: PUBLISH mychannel "Hello" returns number of subscribers that received the message. - Verify subscriptions: PUBSUB CHANNELS lists active channels. PUBSUB NUMSUB mychannel returns subscriber count.

How it interacts with related technologies: - Real-time updates: Chat applications, live scoreboards, notifications. - Azure Functions: Use Redis Pub/Sub trigger (preview) to invoke functions on messages. - Comparison with Azure Service Bus: Redis Pub/Sub is simpler, lower latency, but lacks persistence, dead-letter queues, and advanced features. Use Service Bus for reliable messaging.

Advanced Considerations

Redis Clustering: In a clustered Redis deployment (e.g., Azure Cache for Redis Premium tier with clustering), keys are distributed across shards using hash slots. Pub/Sub messages are broadcast to all shards, but subscribers only receive messages from their connected shard. Cache-Aside and session caching work normally if the key design ensures data locality.

Persistence: Azure Cache for Redis offers RDB (snapshot) and AOF (append-only file) persistence. For cache patterns, persistence is optional; losing cache data is acceptable. For session caching, persistence is recommended to avoid mass logout on node failure.

Security: All Redis patterns should use TLS (port 6380) and access keys. Azure Cache for Redis supports private endpoints for VNet integration.

Walk-Through

1

Cache-Aside: Application checks cache

The application initiates a data request. It first queries the Redis cache using a key (e.g., 'product:123'). The cache client (e.g., StackExchange.Redis) sends a GET command. If the key exists, Redis returns the serialized value. This is a cache hit. The application deserializes the value and uses it immediately. No database query is made. The latency for a cache hit is typically <1 ms. If the key does not exist, Redis returns nil. This is a cache miss. The application then proceeds to the next step.

2

Cache-Aside: Retrieve from database

On a cache miss, the application queries the source database (e.g., Azure SQL) using the same identifier. This involves a network round trip to the database server, execution of a SQL query, and retrieval of the result. Typical latency is 5-50 ms. The application receives the data (e.g., a product record with price, description). It then serializes the data (e.g., to JSON) and prepares to store it in the cache.

3

Cache-Aside: Store in cache with TTL

The application calls the Redis SET command with the key and serialized value, specifying an expiration using the EX or PX flag (e.g., SET product:123 <json> EX 3600). The TTL should be chosen based on how often the data changes. After storing, the application returns the data to the caller. The next request for the same key will hit the cache until the TTL expires or the key is evicted. The application must also handle cache invalidation on data updates: either delete the key or update it.

4

Session Caching: Session ID creation

When a user first accesses the web application, the server generates a unique session ID (e.g., a GUID). This ID is sent to the client as a cookie (e.g., ASP.NET_SessionId) or appended to URLs. The session data (e.g., user profile, cart items) is stored in Redis with the session ID as the key. The server may also set an idle timeout (e.g., 20 minutes) using the EXPIRE command. The session ID is the only piece of state the server needs to track; all session data is in Redis.

5

Pub/Sub: Channel subscription and publishing

Subscribers connect to Redis and issue SUBSCRIBE channel_name. Redis maintains a list of subscribed connections per channel. When a publisher sends PUBLISH channel_name message, Redis iterates over all subscriber connections for that channel and writes the message to each connection's output buffer. The message is delivered at most once. If a subscriber's buffer is full (e.g., slow consumer), Redis may disconnect the subscriber. After delivery, the message is discarded. Subscribers receive the message asynchronously; they must parse the message type (e.g., message, subscribe) from the response.

What This Looks Like on the Job

Enterprise Scenario 1: E-commerce Product Catalog A large online retailer uses Cache-Aside to serve product details. The product database is Azure SQL with millions of SKUs. Product data changes infrequently (price updates, descriptions). The application uses Redis Cache (Premium tier with 10 GB memory) to cache product data with a TTL of 1 hour. On cache miss, the application queries SQL and populates Redis. To handle inventory updates, the application publishes an event to invalidate the cache for the affected product. This pattern reduces database load by 90% and improves page load times from 200 ms to 5 ms. Common misconfiguration: setting TTL too long leads to stale pricing; too short defeats caching. The team uses allkeys-lru eviction policy to handle memory pressure.

Enterprise Scenario 2: Multi-Region Web Application with Session Persistence A SaaS provider runs a web app on Azure App Service across three regions. Users are load-balanced globally via Azure Traffic Manager. The app uses Redis Cache (Standard tier with geo-replication) for session caching. Each user's session data (authentication token, preferences) is stored in Redis with a 30-minute idle timeout. When a user's request hits a different region, the session data is still available because Redis is replicated. Without this, users would be logged out or lose state on region failover. The team monitors session count using DBSIZE and sets alerts when memory usage exceeds 80%. A common pitfall: forgetting to set SameSite cookie attributes, causing session loss in modern browsers.

Enterprise Scenario 3: Real-Time Notification System A financial trading platform uses Redis Pub/Sub to broadcast real-time stock price updates to thousands of web clients. Each client subscribes to specific stock channels (e.g., stock:AAPL). The backend publisher sends price updates every 100 ms. The web front-end uses WebSockets to relay messages from Redis to browsers. The system handles 10,000+ subscribers with sub-10 ms latency. A critical issue: if a subscriber's WebSocket connection drops, they miss updates until they reconnect. The team implemented a fallback: clients periodically poll a REST endpoint for missed updates. They also use PSUBSCRIBE for pattern matching (e.g., stock:*). Misconfiguration: publishing too many messages per second can overwhelm Redis single-threaded event loop, causing latency spikes. They throttle publishes to 50,000 msg/s per instance.

How AZ-204 Actually Tests This

AZ-204 Exam Focus on Redis Cache Patterns The exam tests these patterns under Objective 4.2: 'Monitor and optimize Azure solutions' and also under 'Develop for Azure storage' (cache for Redis). Key areas:

1.

Cache-Aside Pattern (Most Tested): You must know the exact flow: check cache, miss, load from DB, store in cache, return. The exam often asks: 'What happens on a cache miss?' Correct answer: application retrieves from database and populates cache. Wrong answer: Redis automatically loads from database (it does not).

2.

TTL and Eviction Policies: Know the difference between volatile-lru and allkeys-lru. The exam may present a scenario where memory is full and you need to ensure only keys with TTL are evicted. Answer: volatile-lru. Common wrong answer: allkeys-lru (evicts any key).

3.

Session Caching: Be able to identify that ASP.NET Core uses AddStackExchangeRedisCache and AddSession. The exam asks: 'Which service enables session sharing across multiple instances?' Answer: Azure Cache for Redis. Wrong answer: In-Process session state (does not scale out).

4.

Pub/Sub: Understand that messages are not persisted. The exam may ask: 'What happens if a subscriber is offline when a message is published?' Answer: The message is lost. Wrong answer: It is queued for later delivery (Redis does not queue).

5.

Connection Strings and Security: Know that the default port for SSL is 6380 and non-SSL is 6379. The exam expects you to use SSL in production.

6. Common Wrong Answers: - 'Redis automatically refreshes data from the database when TTL expires' – False. Cache-Aside requires application code. - 'Session data is stored in memory on the web server' – Only for single-instance; for multiple instances, use Redis. - 'Pub/Sub messages are stored until acknowledged' – No, at most once delivery.

7. Edge Cases: - Stale data: Cache-Aside does not invalidate on writes; application must explicitly delete or update cache. - Cache stampede: When many requests miss simultaneously (e.g., after TTL expiry), they all hit the database. Mitigation: use mutex locks or early re-computation. - Redis Cluster: In cluster mode, all keys for a session must be in same hash slot; use hash tags like {session:123}.

8.

Eliminating Wrong Answers: If a question mentions 'automatic data refresh', 'message persistence', or 'in-memory session across servers', eliminate those options. Focus on the mechanism: application-driven for Cache-Aside, external store for sessions, fire-and-forget for Pub/Sub.

Key Takeaways

Cache-Aside pattern: application checks cache, on miss loads from database and stores in cache with TTL.

Default TTL for session caching in ASP.NET Core is 20 minutes; configure via `IdleTimeout`.

Redis eviction policy `volatile-lru` evicts keys with TTL set; `allkeys-lru` evicts any key.

Pub/Sub messages are not persisted; if subscriber is offline, message is lost.

Azure Cache for Redis default port for SSL is 6380; non-SSL is 6379.

Use `StackExchange.Redis` as the .NET client for Redis on Azure.

Session caching requires `AddStackExchangeRedisCache` and `AddSession` in ASP.NET Core.

Cache-Aside does not auto-invalidate on writes; application must update or delete cache entries.

Redis supports pattern subscriptions with `PSUBSCRIBE` (e.g., `news.*`).

In Redis Cluster, use hash tags (e.g., `{user:123}:session`) to ensure related keys are in same shard.

Easy to Mix Up

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

Cache-Aside

Application code explicitly manages cache population and invalidation.

Works with any database; no special provider needed.

More control over what is cached and when.

Risk of cache stampede if many requests miss simultaneously.

Commonly used with Redis on Azure.

Read-Through Cache

Cache library automatically loads data from database on miss.

Requires a cache provider that supports read-through (e.g., NCache, AppFabric).

Simpler application code; less control.

Usually includes built-in stampede protection.

Less common with Azure Cache for Redis (not natively supported).

Redis Pub/Sub

Fire-and-forget; no message persistence.

Low latency (<1 ms).

Simple publish/subscribe with channels.

No dead-letter queue, no retries.

Best for real-time notifications where loss is acceptable.

Azure Service Bus Topics

Persistent messaging with at-least-once delivery.

Higher latency (typically 10-100 ms).

Supports subscriptions with filters and rules.

Includes dead-letter queue, scheduled delivery, duplicate detection.

Best for enterprise messaging requiring reliability.

Watch Out for These

Mistake

Redis Cache-Aside automatically refreshes expired keys from the database.

Correct

Redis never initiates database queries. On key expiry, the key is simply deleted. The application must detect the miss and repopulate the cache.

Mistake

Session data stored in Redis is automatically encrypted.

Correct

Redis does not encrypt data at rest by default. You must enable encryption in Azure Cache for Redis (e.g., using Microsoft-managed keys or customer-managed keys).

Mistake

Pub/Sub messages are persisted until at least one subscriber receives them.

Correct

Pub/Sub is fire-and-forget. If no subscriber is listening, the message is lost. For persistent messaging, use Azure Service Bus or Redis Streams.

Mistake

You can use Pub/Sub to send messages to specific subscribers.

Correct

Pub/Sub broadcasts to all subscribers of a channel. There is no direct addressing. If you need point-to-point, use Redis Lists or Service Bus queues.

Mistake

Setting TTL to 0 means the key never expires.

Correct

TTL 0 means the key expires immediately. To set no expiry, do not set TTL or use `PERSIST` command.

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 Cache-Aside and Read-Through caching?

Cache-Aside requires the application to manually check the cache and load data from the database on a miss. Read-Through uses a caching library that automatically loads data from the database when a cache miss occurs, making the application code simpler but requiring a compatible cache provider. Azure Cache for Redis does not natively support Read-Through; it is typically used with Cache-Aside.

How do I configure session caching in ASP.NET Core with Azure Redis?

Install the `Microsoft.Extensions.Caching.StackExchangeRedis` NuGet package. In `Startup.cs`, call `services.AddStackExchangeRedisCache(options => { options.Configuration = "your-redis-connection-string"; })` and then `services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(20); })`. Finally, call `app.UseSession()` in the middleware pipeline.

What happens if Redis runs out of memory?

The behavior depends on the `maxmemory-policy`. Default is `noeviction`, which causes write operations to return errors. Common policies include `allkeys-lru` (evicts least recently used keys regardless of TTL) and `volatile-lru` (evicts keys with TTL set using LRU). Choose based on whether you want to protect keys without TTL.

Can I use Redis Pub/Sub for reliable messaging?

No. Redis Pub/Sub is fire-and-forget with at-most-once delivery. If you need guaranteed delivery, use Azure Service Bus, Azure Event Grid, or Redis Streams (which provides persistence and consumer groups).

How do I invalidate cache in Cache-Aside pattern?

When data is updated in the database, the application should either delete the corresponding cache key (using `DEL`) or update it with the new value. This ensures the next read fetches fresh data. Failure to invalidate leads to stale data.

What is the default eviction policy for Azure Cache for Redis?

The default eviction policy is `volatile-lru`, which evicts keys with an expiration set using an LRU algorithm when memory is full. You can change it in the Azure portal or via CLI.

How do I monitor Redis cache performance?

Azure Cache for Redis provides metrics in the portal: Cache Hits, Cache Misses, Evicted Keys, Server Load, and Memory Usage. You can also use `redis-cli` commands like `INFO stats` and `MONITOR` (for debugging).

Terms Worth Knowing

Ready to put this to the test?

You've just covered Redis Cache Patterns: Cache-Aside, Session, Pub/Sub — now see how well it sticks with free AZ-204 practice questions. Full explanations included, no account needed.

Done with this chapter?