gRPC :👈 👉:EF-Core-Optimization

ASP.NET Core Distributed Caching with Redis: Advanced Implementation

ASP.NET Core Distributed Caching with Redis

Advanced Implementation, Architecture, Best Practices, Performance Optimization and Production-Ready Patterns

1. What Is Distributed Caching?

Distributed caching is a technique in which frequently accessed application data is stored in a separate cache server that can be accessed by multiple application instances.

Instead of retrieving the same information repeatedly from SQL Server, the application first checks Redis. If the requested information exists in Redis, it is returned immediately. Otherwise, the application retrieves it from the database and stores it in Redis for future requests.

Redis is an in-memory data store commonly used as a distributed cache.

Without Distributed Caching

Client Requests ASP.NET Core API SQL Server Every request

Problems:

  • Repeated database queries.
  • Increased SQL Server CPU and memory usage.
  • Higher response times.
  • Database becomes a bottleneck when traffic increases.
  • Multiple application instances generate duplicate database requests.

With Distributed Caching

Client Requests API Instance 1 ASP.NET Core API Instance 2 ASP.NET Core Redis Cache Shared distributed cache SQL Server Only on cache miss

Both application instances access the same Redis cache. When one instance stores a cache entry, another instance can retrieve it.

2. Why Use Redis?

Redis stores data in memory and provides fast access to frequently requested information.

Important Redis capabilities include:

  • In-memory storage: Data is primarily accessed from memory.
  • Key-value storage: Data is stored using unique keys.
  • Expiration: Keys can automatically expire after a configured duration.
  • Data structures: Supports strings, hashes, lists, sets, sorted sets and other structures.
  • Atomic operations: Individual Redis commands can execute atomically.
  • Persistence options: Redis can be configured to preserve data across restarts.
  • Replication: Supports primary-replica replication.
  • Pub/Sub: Supports message publication and subscription.

Important: Redis is not a replacement for SQL Server. SQL Server should normally remain the source of truth for business data. Redis is an additional performance layer.

3. Distributed Cache vs In-Memory Cache vs Redis

Feature IMemoryCache Distributed Memory Cache Redis
Storage Application memory Application memory External Redis server
Shared between servers No No Yes
Survives application restart No No Depends on Redis configuration
Network communication No No Yes
Suitable for multiple API instances Not as a shared cache No Yes
Typical use Local application caching Development and testing Distributed caching

Important distinction: AddDistributedMemoryCache() implements the IDistributedCache interface, but it does not create a real distributed cache. Each application instance has its own memory.

4. How ASP.NET Core Communicates with Redis

ASP.NET Core provides the IDistributedCache abstraction. The Redis provider implements this interface.

Controller Business Layer IDistributedCache .NET Abstraction Redis Provider StackExchange.Redis Redis Server Application uses a common caching interface

The application does not need to know the internal implementation of Redis when using IDistributedCache.

5. Important IDistributedCache Methods

The IDistributedCache interface provides these primary methods:

Method Purpose
GetAsync() Retrieves a cached value asynchronously.
SetAsync() Stores a value in the cache.
RefreshAsync() Refreshes sliding expiration for an existing entry.
RemoveAsync() Removes a cached value.
Get() Retrieves a cached value synchronously.
Set() Stores a cached value synchronously.
Refresh() Refreshes sliding expiration synchronously.
Remove() Removes a cached value synchronously.

Recommendation: Prefer asynchronous methods in ASP.NET Core request processing to avoid blocking request threads during I/O operations.

6. Project Setup

Step 1: Create an ASP.NET Core Web API

dotnet new webapi -n RedisCachingDemo
cd RedisCachingDemo

Step 2: Install the Redis caching package

dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

This package provides the Redis implementation of IDistributedCache.

Step 3: Start Redis for local development

You need a running Redis-compatible server. For example, if you already have Docker installed and an approved Redis image available, you can run a local development instance using your environment's Redis setup.

For a local Redis instance using the default port, the connection endpoint is commonly:

localhost:6379

Do not expose a development Redis instance directly to the public internet.

7. Configure Redis in appsettings.json

For local development, you can configure a Redis endpoint in appsettings.Development.json:

{
  "ConnectionStrings": {
    "Redis": "localhost:6379"
  }
}

For production, do not store Redis passwords or sensitive connection details in source-controlled configuration files. Use environment variables, a secure configuration provider, or Azure Key Vault.

8. Register Redis in Program.cs

using Microsoft.Extensions.Caching.StackExchangeRedis;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var redisConnection =
    builder.Configuration.GetConnectionString("Redis");
if (string.IsNullOrWhiteSpace(redisConnection))
{
    throw new InvalidOperationException(
        "Redis connection string is missing.");
}
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = redisConnection;
    options.InstanceName = "MyApplication:";
});
builder.Services.AddScoped<ProductService>();
var app = builder.Build();
app.MapControllers();
app.Run();

Explanation

  • AddStackExchangeRedisCache(): Registers the Redis distributed cache provider.
  • Configuration: Specifies how the application connects to Redis.
  • InstanceName: Adds a common prefix to cache keys created by this provider.
  • AddScoped(): Registers ProductService with a scoped lifetime.

9. Understanding Cache-Aside Pattern

Cache-aside is one of the most commonly used caching patterns in ASP.NET Core applications.

The application controls when to read from the cache, when to query the database, and when to populate the cache.

Cache-Aside Flow

Client Request ASP.NET Core API Check Redis Cache Cache Hit Return Cached Data Cache Miss Query SQL Server Store in Redis Return Database Data

Cache Hit

A cache hit occurs when the requested key exists in Redis.

var cachedData = await cache.GetAsync("product:100");
if (cachedData != null)
{
    // Return cached data.
}

Cache Miss

A cache miss occurs when the requested key does not exist or has expired.

The application retrieves the data from the database and stores it in Redis.

var cachedData = await cache.GetAsync("product:100");
if (cachedData == null)
{
    var product = await repository.GetByIdAsync(100);
    // Store the result in Redis.
}

10. Store Complex Objects in Redis

IDistributedCache stores values as byte arrays. It does not directly store arbitrary C# objects.

We normally serialize objects into JSON bytes before storing them and deserialize them when retrieving them.

Product Model

public sealed class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public string Category { get; set; } = string.Empty;
}

Serialization and Deserialization

using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
public static class DistributedCacheExtensions
{
    public static async Task SetObjectAsync<T>(
        this IDistributedCache cache,
        string key,
        T value,
        DistributedCacheEntryOptions options,
        CancellationToken cancellationToken = default)
    {
        var bytes = JsonSerializer.SerializeToUtf8Bytes(value);
        await cache.SetAsync(
            key,
            bytes,
            options,
            cancellationToken);
    }
    public static async Task<T?> GetObjectAsync<T>(
        this IDistributedCache cache,
        string key,
        CancellationToken cancellationToken = default)
    {
        var bytes = await cache.GetAsync(
            key,
            cancellationToken);
        if (bytes == null)
        {
            return default;
        }
        return JsonSerializer.Deserialize<T>(bytes);
    }
}

Why Serialize to UTF-8?

  • Redis receives a byte array.
  • JSON provides a readable and portable data representation.
  • UTF-8 is an efficient encoding for JSON text.
  • Different services can exchange JSON data if they follow the same schema.

Production consideration: Use stable DTOs for cached data. Avoid caching entire Entity Framework entities with navigation properties, tracking state, or unwanted sensitive fields.

11. Implement a Complete Cache-Aside Service

Consider a product service that retrieves products from SQL Server and caches the result in Redis.

Repository Interface

public interface IProductRepository
{
    Task<Product?> GetByIdAsync(
        int id,
        CancellationToken cancellationToken);
}

Product Service

using Microsoft.Extensions.Caching.Distributed;
public sealed class ProductService
{
    private readonly IDistributedCache _cache;
    private readonly IProductRepository _repository;
    public ProductService(
        IDistributedCache cache,
        IProductRepository repository)
    {
        _cache = cache;
        _repository = repository;
    }
    public async Task<Product?> GetProductAsync(
        int id,
        CancellationToken cancellationToken = default)
    {
        var cacheKey = $"products:v1:{id}";
        // 1. Check Redis.
        var cachedProduct =
            await _cache.GetObjectAsync<Product>(
                cacheKey,
                cancellationToken);
        if (cachedProduct != null)
        {
            return cachedProduct;
        }
        // 2. Cache miss: query the database.
        var product = await _repository.GetByIdAsync(
            id,
            cancellationToken);
        if (product == null)
        {
            return null;
        }
        // 3. Store the result in Redis.
        var cacheOptions = new DistributedCacheEntryOptions()
            .SetAbsoluteExpiration(
                TimeSpan.FromMinutes(10));
        await _cache.SetObjectAsync(
            cacheKey,
            product,
            cacheOptions,
            cancellationToken);
        // 4. Return the product.
        return product;
    }
}

How This Works

  1. The API receives a product request.
  2. ProductService creates a cache key.
  3. Redis is checked first.
  4. If the product exists, it is returned immediately.
  5. If it does not exist, SQL Server is queried.
  6. The product is serialized and saved in Redis.
  7. The product is returned to the caller.

12. Cache Expiration Strategies

Cache expiration determines how long data remains available in the cache.

Two important expiration strategies are absolute expiration and sliding expiration.

Absolute Expiration

Absolute expiration specifies a fixed time after which the cached item expires, regardless of how often it is accessed.

var options = new DistributedCacheEntryOptions()
    .SetAbsoluteExpiration(
        TimeSpan.FromMinutes(30));

Example: A product category list is cached for 30 minutes. It expires after 30 minutes even if users access it repeatedly.

Sliding Expiration

Sliding expiration resets the expiration timeout whenever the cached entry is accessed.

var options = new DistributedCacheEntryOptions()
    .SetSlidingExpiration(
        TimeSpan.FromMinutes(10));

Example: If the cache entry is accessed every five minutes, it can remain available because its expiration is continually extended.

Combining Both

var options = new DistributedCacheEntryOptions()
    .SetSlidingExpiration(TimeSpan.FromMinutes(10))
    .SetAbsoluteExpiration(TimeSpan.FromHours(1));

This gives the entry a sliding timeout of ten minutes, while the absolute expiration places a one-hour maximum lifetime on it.

Expiration Type Behavior Suitable For
Absolute Expires at a fixed time Product lists, reference data
Sliding Extends when accessed Frequently used session-related entries
Both Sliding timeout with a maximum lifetime Frequently accessed data that still needs a hard expiry

Important: Expiration is not a substitute for cache invalidation when business data changes.

13. Cache Invalidation

Cache invalidation means removing or updating cached information when the original database data changes.

This is one of the most important parts of a reliable caching implementation.

The Problem

  1. Product price is ₹1,000 in SQL Server.
  2. The application stores the product in Redis.
  3. An administrator updates the price to ₹1,200 in SQL Server.
  4. Redis still contains the old price.
  5. Users may receive stale information until the cached entry expires.

Solution: Remove the Cache Entry After a Successful Update

public async Task UpdateProductAsync(
    Product product,
    CancellationToken cancellationToken)
{
    await _repository.UpdateAsync(
        product,
        cancellationToken);
    var cacheKey = $"products:v1:{product.Id}";
    await _cache.RemoveAsync(
        cacheKey,
        cancellationToken);
}

The next request will miss the cache, read the updated product from SQL Server, and populate Redis with the new value.

Update vs Remove

Two common strategies are:

  • Cache removal: Delete the cached value after the database update. The next request reloads it.
  • Cache replacement: Update the database and write the new value to Redis.

Cache removal is often simpler and reduces the chance of writing an incorrect representation to the cache.

Important: Database and Redis Are Not One Transaction

A SQL Server transaction cannot automatically make a separate Redis operation part of the same atomic transaction.

For example, SQL Server might successfully update a product, but Redis might temporarily be unavailable when the application attempts to remove the cache entry.

For important business workflows, consider reliable invalidation using an outbox pattern:

ASP.NET Core API Update Product SQL Transaction Product + Outbox Event Outbox Processor Redis Invalidation Mark Event Processed

The database update and outbox event are committed in one SQL transaction. A background processor reads pending events and performs the Redis invalidation. The processor retries failures and must handle duplicate event delivery safely.

14. Cache Stampede Problem

A cache stampede occurs when many requests attempt to retrieve the same item after it expires or is removed.

All those requests may query SQL Server simultaneously, increasing database load.

Example

Imagine a product catalog entry expires at the same moment that 500 users request it.

  1. All 500 requests check Redis.
  2. All 500 requests receive a cache miss.
  3. All 500 requests query SQL Server.
  4. All 500 requests attempt to repopulate Redis.
Redis Cache Miss Request Group 1 Request Group 2 Request Group 3 SQL Server Overloaded

Solution 1: Local SemaphoreSlim

A SemaphoreSlim can ensure that only one request per application instance performs the expensive database operation for a particular key at a time.

using System.Collections.Concurrent;
public sealed class ProductCacheService
{
    private readonly IDistributedCache _cache;
    private readonly IProductRepository _repository;
    private static readonly ConcurrentDictionary<string, SemaphoreSlim>
        Locks = new();
    public ProductCacheService(
        IDistributedCache cache,
        IProductRepository repository)
    {
        _cache = cache;
        _repository = repository;
    }
    public async Task<Product?> GetAsync(
        int id,
        CancellationToken cancellationToken)
    {
        var key = $"products:v1:{id}";
        var cached = await _cache.GetObjectAsync<Product>(
            key,
            cancellationToken);
        if (cached != null)
        {
            return cached;
        }
        var semaphore = Locks.GetOrAdd(
            key,
            _ => new SemaphoreSlim(1, 1));
        await semaphore.WaitAsync(cancellationToken);
        try
        {
            // Check again after acquiring the lock.
            cached = await _cache.GetObjectAsync<Product>(
                key,
                cancellationToken);
            if (cached != null)
            {
                return cached;
            }
            var product = await _repository.GetByIdAsync(
                id,
                cancellationToken);
            if (product == null)
            {
                return null;
            }
            var options = new DistributedCacheEntryOptions()
                .SetAbsoluteExpiration(
                    TimeSpan.FromMinutes(10));
            await _cache.SetObjectAsync(
                key,
                product,
                options,
                cancellationToken);
            return product;
        }
        finally
        {
            semaphore.Release();
        }
    }
}

Limitation: SemaphoreSlim is local to one process. If there are five API instances, each instance can still have one request performing the same database operation. This is not a distributed lock.

For a multi-instance application, consider distributed coordination, request coalescing, background cache warming, and carefully designed Redis locking when necessary. Distributed locks require ownership tokens, expiration, safe release, and failure handling.

Solution 2: Cache Warming

Cache warming means loading frequently requested data into Redis before users request it.

Examples:

  • Popular product categories.
  • Frequently accessed configuration.
  • Common reference data.
  • Frequently requested public content.

15. Cache Key Design

Redis uses keys to identify cached entries. A well-designed key structure makes cache management easier.

Recommended Key Format

{application}:{environment}:{entity}:{version}:{identifier}

Examples

shop:prod:products:v1:1001
shop:prod:categories:v1:all
shop:prod:customers:v1:250
shop:prod:orders:v1:5001
catalog:prod:search:v2:phones:page1
identity:prod:user-permissions:v1:123

Why include a version?

Suppose you change the structure of the Product DTO. Older Redis entries might not deserialize correctly into the new model.

Changing the key version from v1 to v2 creates a separate namespace for the new data format.

Key Design Best Practices

  • Use consistent naming conventions.
  • Include an application or service prefix.
  • Include environment information when Redis is shared between environments.
  • Use versioning when cached data structures change.
  • Avoid extremely long keys.
  • Never place passwords, access tokens, or sensitive personal information in cache keys.
  • Do not create keys that can grow without a defined limit.

16. Cache Different Types of Data

Product Details

products:v1:1001

Cache product information for a short period and remove or refresh it when the product changes.

Product Categories

categories:v1:all

Category data is often read frequently and changed less frequently.

User Permissions

users:v1:123:permissions

Permission caching requires careful invalidation. A stale permission entry can cause an authorization decision to use outdated information. Do not rely on a long cache lifetime for security-sensitive authorization data.

Search Results

search:v1:phones:page1:sort-price

Search results can be cached when the search parameters are represented consistently in the key.

17. Cache-Aside vs Read-Through vs Write-Through

Pattern How It Works Typical Use
Cache-Aside Application checks cache and loads data from the database on a miss. Common ASP.NET Core applications
Read-Through Cache provider or caching layer loads missing data from the backing store. Specialized caching layers
Write-Through Writes pass through a caching layer to the backing store. Systems requiring coordinated write behavior
Write-Behind Writes are initially buffered and persisted later. Specialized high-throughput systems with durability controls

With IDistributedCache, cache-aside is a straightforward application-level pattern. Do not assume that registering Redis automatically provides read-through or write-through behavior.

18. Redis in Microservices Architecture

In a microservices architecture, multiple services can use a shared Redis infrastructure or separate Redis deployments, depending on isolation and operational requirements.

API Gateway Product Service Order Service Customer Service Redis Cache Product Database Order Database Customer Database

Architecture consideration: Sharing a Redis server does not mean every microservice should freely read and write every other service's keys.

Each service should own its cached data and define its own key namespace and invalidation rules. Consider separate logical deployments or access boundaries when stronger isolation is required.

19. Using Redis with Multiple ASP.NET Core Instances

Consider an application deployed to Kubernetes with three API pods.

Kubernetes Cluster API Pod 1 ASP.NET Core API Pod 2 ASP.NET Core API Pod 3 ASP.NET Core Redis Shared cache

All three pods use Redis as a shared cache. If Pod 1 writes a product entry, Pod 2 and Pod 3 can retrieve it.

Benefits include:

  • Cache is shared across replicas.
  • Application pods can scale independently.
  • Cache entries are not lost simply because one API pod restarts.
  • Application instances can be replaced without relying on local cached data.

20. Redis Connection Management

Connection management is important for Redis performance and reliability.

When using the ASP.NET Core Redis distributed-cache provider, the provider manages its Redis connection infrastructure.

If your application also uses advanced StackExchange.Redis functionality directly, use a shared ConnectionMultiplexer rather than creating a new connection for each request.

Register ConnectionMultiplexer for Direct Redis Operations

using StackExchange.Redis;
var builder = WebApplication.CreateBuilder(args);
var redisConnection =
    builder.Configuration.GetConnectionString("Redis")
    ?? throw new InvalidOperationException(
        "Redis configuration is missing.");
builder.Services.AddSingleton<IConnectionMultiplexer>(
    _ => ConnectionMultiplexer.Connect(redisConnection));
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = redisConnection;
    options.InstanceName = "MyApplication:";
});

Important: This example registers a multiplexer for direct Redis operations. The distributed-cache provider also manages its own connection internally. Do not assume that the provider automatically uses this separately registered multiplexer.

For asynchronous connection initialization or more advanced configuration, use ConnectionMultiplexer.ConnectAsync during application startup and register the resulting shared instance.

21. Using StackExchange.Redis Directly

IDistributedCache is useful for common cache operations. However, advanced Redis features may require direct access to StackExchange.Redis.

Examples include:

  • Redis hashes and sorted sets.
  • Atomic counters.
  • Transactions and Lua scripts.
  • Distributed coordination primitives.
  • Redis Pub/Sub.
  • Specialized data structures.

Example: Redis Counter

using StackExchange.Redis;
public sealed class RedisCounterService
{
    private readonly IDatabase _database;
    public RedisCounterService(
        IConnectionMultiplexer multiplexer)
    {
        _database = multiplexer.GetDatabase();
    }
    public Task<long> IncrementAsync(string key)
    {
        return _database.StringIncrementAsync(key);
    }
    public Task<long> GetValueAsync(string key)
    {
        return _database.StringGetAsync(key)
            .ContinueWith(
                task => (long?)task.Result ?? 0L);
    }
}

For a simpler asynchronous implementation of the read method:

public async Task<long> GetValueAsync(string key)
{
    RedisValue value = await _database.StringGetAsync(key);
    return value.HasValue
        ? (long)value
        : 0L;
}

Note: This is a direct Redis operation, not an IDistributedCache operation. It is useful when the application needs Redis-specific capabilities.

22. Redis Database and Key Expiration

Redis supports key expiration. An entry can be removed automatically after its time-to-live (TTL) has elapsed.

Example using StackExchange.Redis:

await _database.StringSetAsync(
    "product:1001",
    "Sample Product",
    expiry: TimeSpan.FromMinutes(10));

To check the remaining TTL:

var ttl = await _database.KeyTimeToLiveAsync(
    "product:1001");

To delete a key:

await _database.KeyDeleteAsync("product:1001");

Expiration helps prevent old cache entries from remaining indefinitely. Choose expiration periods based on data freshness requirements and access patterns.

23. Cache Failure Handling

Redis is an external dependency. It can become temporarily unavailable because of network problems, maintenance, failover, or resource exhaustion.

Your application should have a deliberate cache failure strategy.

Cache-Aside Failure Flow

API Request Try Redis Available Use Cached Data Unavailable Cache Fallback Query SQL Server if appropriate

For non-critical cached data, a common strategy is to continue using the database when Redis is unavailable.

However, this must be implemented carefully. If Redis is unavailable during a traffic spike, allowing every request to query SQL Server can overload the database.

Recommended Failure Handling

  • Set sensible connection and operation timeouts.
  • Use cancellation tokens.
  • Log cache failures.
  • Monitor Redis availability and latency.
  • Use circuit breakers where appropriate.
  • Protect SQL Server from sudden traffic increases.
  • Do not retry every failed operation indefinitely.
  • Define which operations can safely continue without Redis.

Important: A cache fallback is appropriate only when the database can safely handle the additional load and the cached information is not essential to correctness or security.

24. Redis Security Best Practices

  • Use TLS for connections when supported by the deployment.
  • Require authentication.
  • Use Redis ACLs to limit permissions.
  • Keep Redis on a private network.
  • Do not expose Redis ports publicly.
  • Use secure secret storage for connection credentials.
  • Rotate credentials according to organizational policy.
  • Restrict access to the minimum required application identities.
  • Use separate environments for development, testing and production.
  • Avoid storing sensitive personal information unless the design, access controls and retention requirements explicitly permit it.

25. Redis Performance Optimization

1. Cache Only Frequently Used Data

Do not cache every database query. Prioritize frequently accessed and relatively expensive data.

2. Use Appropriate Expiration

Choose TTL values according to the business requirements and data update frequency.

3. Avoid Large Cache Values

Large values consume memory, increase network transfer time, and can increase serialization costs.

4. Use Pagination

Do not cache thousands of records when the application only needs one page.

5. Use Asynchronous Operations

Prefer GetAsync(), SetAsync() and RemoveAsync() in request-processing code.

6. Avoid Unnecessary Serialization

Use suitable DTOs and cache only the fields needed by consumers.

7. Avoid Excessive Redis Calls

Group related operations where appropriate and avoid repeatedly reading the same key within a single request.

8. Use Cache Warming for Hot Data

Load predictable, frequently accessed data before traffic arrives when the operational cost is justified.

9. Monitor Memory Usage

Monitor cache memory, evictions, expiration rates, and key growth.

10. Deploy Redis Close to the Application

Network latency affects cache performance. For cloud applications, deploy the application and Redis in the same region when possible.

26. Redis Monitoring

Monitoring is essential for production Redis deployments.

Important metrics include:

Metric Meaning
Cache Hit Rate Percentage of cache lookups successfully served from the cache.
Cache Miss Rate Percentage of lookups where the key was not found.
Memory Usage Memory consumed by Redis.
Evictions Keys removed because of memory policy or other eviction conditions.
Command Latency Time taken to execute Redis commands.
Connected Clients Number of clients connected to Redis.
Network Throughput Data transferred to and from Redis.
Cache Errors Failed operations, timeouts and connection errors.

Cache Hit Rate Formula

Cache Hit Rate indicates how often requested data is found in Redis.

Formula:

Cache Hit Rate =
    (Cache Hits / Total Cache Requests) * 100

Example:

Cache Hits = 900
Cache Misses = 100
Total Requests = 1000
Cache Hit Rate = (900 / 1000) * 100
Cache Hit Rate = 90%

A high hit rate can indicate effective caching, but it does not automatically prove that the system is performing well. Also monitor data freshness, latency, errors, and database load.

27. Redis with Azure

For applications hosted in Azure, a managed Redis service can reduce the operational burden of maintaining Redis infrastructure.

Azure Managed Redis is Microsoft's managed Redis offering. Select the appropriate service tier and deployment configuration according to workload requirements.

Typical Azure Architecture

Users / Clients Azure Application Gateway ASP.NET Core API / AKS Azure Managed Redis Distributed Cache Azure SQL Database Persistent Data

Azure Configuration Example

Configure the Redis connection string securely. The exact endpoint, port, TLS and authentication settings depend on the selected managed Redis deployment.

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration =
        builder.Configuration.GetConnectionString("Redis");
    options.InstanceName = "MyApplication:";
});

In production, retrieve the connection configuration through a secure configuration mechanism such as Azure Key Vault or an appropriately configured managed identity integration where supported by the selected service and client.

Important: Managed identity support and authentication configuration depend on the Redis service and client version. Do not assume that every Redis connection string can be replaced with a managed identity without additional configuration.

28. Redis in Docker and Kubernetes

In containerized environments, Redis should normally be deployed as a managed service or as a properly operated infrastructure component rather than bundled into every API container.

Important deployment considerations:

  • Use private networking between the API and Redis.
  • Store credentials in Kubernetes Secrets or a managed secret store.
  • Configure readiness and liveness checks appropriately.
  • Monitor Redis resource usage.
  • Configure persistence and replication based on the required durability.
  • Use resource limits and capacity planning.
  • Do not assume Kubernetes pod storage is permanent.

29. Redis Cache vs Output Cache vs Response Cache

These caching approaches solve different problems.

Type Purpose Example
Distributed Cache Stores application data for reuse. Product details, categories
Output Cache Stores generated HTTP responses on the server. Public catalog endpoint
Response Caching Uses HTTP caching semantics and headers. Browser or intermediary caching
In-Memory Cache Stores data inside one application process. Local configuration lookup

Redis can be used as a distributed backing store for application caching and can also be configured for ASP.NET Core output caching using the relevant provider package.

Output Cache with Redis

Install the output-cache Redis provider package:

dotnet add package
Microsoft.AspNetCore.OutputCaching.StackExchangeRedis

Example configuration:

builder.Services.AddStackExchangeRedisOutputCache(options =>
{
    options.Configuration =
        builder.Configuration.GetConnectionString("Redis");
    options.InstanceName = "MyOutputCache:";
});
builder.Services.AddOutputCache();
var app = builder.Build();
app.UseOutputCache();
app.MapGet("/products", () =>
{
    return Results.Ok(new[]
    {
        new { Id = 1, Name = "Laptop" },
        new { Id = 2, Name = "Keyboard" }
    });
})
.CacheOutput();
app.Run();

Output caching is different from caching product objects using IDistributedCache. Choose the correct approach based on whether you want to cache data or an HTTP response.

30. Common Mistakes to Avoid

Mistake Why It Is a Problem Better Approach
No expiration Entries may remain longer than intended. Define suitable TTL values.
No invalidation Users may receive stale data. Invalidate after successful updates.
Caching everything Consumes Redis memory unnecessarily. Cache valuable, frequently accessed data.
Creating a connection per request Increases connection overhead. Reuse the shared connection infrastructure.
Ignoring cache failures Can cause request failures or database overload. Implement a deliberate failure strategy.
Very large cache values Increases memory and network costs. Use compact DTOs and pagination.
Using local memory in a multi-instance system as if shared Each instance sees different values. Use a genuine distributed cache.
No cache versioning Old data formats may conflict with new code. Version cache keys.
Storing sensitive information carelessly Creates security and privacy risks. Minimize data and enforce access controls.
Blind retries Can increase load during outages. Use bounded retries and timeouts.

31. Advanced Production Architecture

A production caching architecture may combine Redis, SQL Server, a background worker, and a message broker.

Client ASP.NET Core API Redis Cache SQL Server Message Broker Background Worker Processes invalidation events

Responsibilities:

  • ASP.NET Core API: Handles incoming requests and cache-aside logic.
  • Redis: Stores frequently accessed data.
  • SQL Server: Stores persistent business data.
  • Message Broker: Delivers cache invalidation events.
  • Background Worker: Processes events and invalidates cache entries.

For reliable updates, combine the outbox pattern with idempotent event processing. The exact design depends on the application's consistency requirements.

32. When Should You Use Redis?

Redis is a good choice when:

  • Your application runs on multiple servers or containers.
  • The same data is requested frequently.
  • Database queries are expensive.
  • Response-time requirements are strict.
  • Multiple microservices need a shared caching infrastructure.
  • You need fast counters or other Redis data structures.
  • You need distributed session storage.

33. When Should You Avoid Redis?

  • Data is rarely requested.
  • The database query is already inexpensive.
  • The data changes constantly and is difficult to cache consistently.
  • The application does not benefit enough to justify the additional infrastructure.
  • The cache would contain large amounts of data that cannot fit within the available memory budget.
  • Strong transactional consistency is required and the application cannot tolerate cache staleness.

34. Production Implementation Checklist

  • Install the correct Redis provider package.
  • Configure Redis through secure configuration.
  • Register IDistributedCache using AddStackExchangeRedisCache().
  • Use asynchronous cache operations.
  • Implement cache-aside correctly.
  • Serialize and deserialize DTOs safely.
  • Define expiration for every cache entry.
  • Implement cache invalidation after database updates.
  • Use an outbox pattern where reliable invalidation is required.
  • Protect against cache stampedes.
  • Use structured cache keys and versioning.
  • Configure Redis authentication and TLS.
  • Monitor Redis latency, memory, evictions and errors.
  • Define a fallback strategy for Redis outages.
  • Test cache behavior across multiple API instances.
  • Benchmark the system under realistic traffic.

35. Final Architecture Summary

A well-designed ASP.NET Core distributed caching solution follows this general flow:

  1. ASP.NET Core receives a request.
  2. The service checks Redis using IDistributedCache.
  3. If the data exists, the cached result is returned.
  4. If the data is missing, SQL Server is queried.
  5. The result is serialized and stored in Redis with an expiration.
  6. When business data changes, the corresponding cache entry is invalidated.
  7. Monitoring and failure-handling mechanisms keep the system reliable.

Most important principle: Redis improves read performance, but correct cache expiration, invalidation, consistency, security, and failure handling are what make a distributed caching solution production-ready.

36. Official Documentation

🔙
gRPC :👈 👉:EF-Core-Optimization