LESSON 10 OF 20

10. Cache-Aside and Distributed Caching with Redis

Add Redis to the Catalog service through Aspire and implement cache-aside, cache-key design, expiration, invalidation, and graceful behavior when Redis is unavailable.

50 dk 32

Introduction

In the previous lessons, we built Catalog as an independent ASP.NET Core Web API and connected services through the Aspire AppHost. In this lesson, we will reduce repeated SQL Server reads by adding a Redis-backed distributed cache. We will define a Redis resource in the application model, reference it from the Catalog service, and implement the cache-aside pattern in the API layer.

With cache-aside, the application first tries to read data from the cache. If the item is missing, the application loads it from the primary data source, the Catalog database, stores the result in Redis, and returns it to the caller. During an update or delete, the old cache entry is invalidated. If Redis is unavailable, the cache is treated as an optional performance component and the application can continue by reading from the database.

Distributed caching and cache-aside

Why Redis instead of a local memory cache?

IMemoryCache stores data only in the memory of the current application instance. When multiple Catalog instances are running, each instance may contain different cached values. Local entries are also lost when an instance restarts. Redis is an external cache that can be shared by multiple application instances.

ASP.NET Core provides the IDistributedCache abstraction so application code does not have to depend directly on one cache product. The Redis provider implements that contract. The service layer can therefore use GetStringAsync, SetStringAsync, and RemoveAsync without knowing Redis connection details.

The cache-aside flow

  1. Create a deterministic cache key for the request.
  2. Read the item from the cache.
  3. If the item exists, deserialize and return it. This is a cache hit.
  4. If it does not exist, load the item from the database. This is a cache miss.
  5. Store the database result in the cache with an appropriate expiration.
  6. Remove or replace the related key after an update or delete.

Cached data is a copy of the database data. Losing the cache must not mean losing business data. Redis should be designed as a secondary layer for performance and scale, not as the authoritative source of Catalog information.

Defining a Redis resource in the Aspire AppHost

After adding the Redis hosting integration to the AppHost project, declare a Redis resource and reference it from Catalog. In this example, the resource is named catalog-cache. The resource name is also used when resolving the connection configuration injected into the consuming application.

var builder = DistributedApplication.CreateBuilder(args);

var catalogDb = builder.AddSqlServer("catalog-sql")
    .AddDatabase("catalogdb");

var catalogCache = builder.AddRedis("catalog-cache");

builder.AddProject<Projects.CatalogService>("catalog")
    .WithReference(catalogDb)
    .WithReference(catalogCache)
    .WaitFor(catalogDb)
    .WaitFor(catalogCache);

builder.Build().Run();

WithReference(catalogCache) supplies Redis connection information to the Catalog service. WaitFor helps local orchestration start Catalog after Redis is ready. It does not guarantee that Redis will remain available for the entire lifetime of the application. A container can restart and a network connection can fail, so the application must still handle runtime failures.

Registering the distributed cache

Add the Microsoft.Extensions.Caching.StackExchangeRedis package to the Catalog project. Then register service defaults and the Redis-backed distributed cache in Program.cs.

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
builder.Services.AddControllers();

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration
        .GetConnectionString("catalog-cache");
    options.InstanceName = "catalog:";
});

builder.Services.AddScoped<CatalogReadService>();

var app = builder.Build();

app.MapDefaultEndpoints();
app.MapControllers();

app.Run();

InstanceName provides a logical prefix when multiple applications use the same Redis server. Even with that prefix, explicit key naming is useful because it communicates the bounded context, resource type, and version of the cached representation.

Designing cache keys

Key design is as important as serialization when building a maintainable cache. A key should identify the application, bounded context, resource type, and relevant identity or query parameters.

catalog:product:v1:{productId}
catalog:products:v1:category:{categoryId}:page:{page}:size:{size}

The v1 segment becomes useful when the cached DTO changes. If a new representation is incompatible with old entries, changing the key version to v2 allows the application to adopt the new format without relying on a risky global delete.

  • Do not use spaces or ambiguous characters in keys.
  • Include identity, pagination, and filter values that affect the result.
  • Include a tenant or store identifier when the application is multi-tenant.
  • Never expose user-specific data through a shared key.
  • Centralize key construction in one helper or key factory.

Implementing cache-aside

The following service first checks Redis. If the item is not present, it queries Entity Framework Core and stores the DTO in the cache. System.Text.Json is used for serialization.

public sealed class CatalogReadService
{
    private readonly IDistributedCache _cache;
    private readonly CatalogDbContext _db;
    private readonly ILogger<CatalogReadService> _logger;

    public CatalogReadService(
        IDistributedCache cache,
        CatalogDbContext db,
        ILogger<CatalogReadService> logger)
    {
        _cache = cache;
        _db = db;
        _logger = logger;
    }

    public async Task<ProductDto?> GetProductAsync(
        Guid productId,
        CancellationToken cancellationToken)
    {
        var key = $"catalog:product:v1:{productId}";
        var cached = await _cache.GetStringAsync(key, cancellationToken);

        if (!string.IsNullOrWhiteSpace(cached))
        {
            _logger.LogDebug("Catalog cache hit for {ProductId}", productId);
            return JsonSerializer.Deserialize<ProductDto>(cached);
        }

        _logger.LogDebug("Catalog cache miss for {ProductId}", productId);

        var product = await _db.Products
            .AsNoTracking()
            .Where(x => x.Id == productId)
            .Select(x => new ProductDto(x.Id, x.Name, x.Price, x.IsActive))
            .SingleOrDefaultAsync(cancellationToken);

        if (product is null)
        {
            return null;
        }

        var serialized = JsonSerializer.Serialize(product);
        var options = new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5),
            SlidingExpiration = TimeSpan.FromMinutes(1)
        };

        await _cache.SetStringAsync(key, serialized, options, cancellationToken);
        return product;
    }
}

AbsoluteExpirationRelativeToNow limits the maximum lifetime of a product entry to five minutes. SlidingExpiration allows frequently used entries to remain available for a shorter moving window. Using both prevents a frequently accessed item from surviving indefinitely without a refresh.

Invalidation after updates and deletes

If a product is updated while the old representation remains in Redis, clients may receive stale data. A simple and safe strategy is to remove the key after the database update succeeds. The next read becomes a miss, loads the new value, and repopulates the cache.

public async Task UpdateProductAsync(
    Product product,
    CancellationToken cancellationToken)
{
    _db.Products.Update(product);
    await _db.SaveChangesAsync(cancellationToken);

    var key = $"catalog:product:v1:{product.Id}";
    await _cache.RemoveAsync(key, cancellationToken);
}

Cache removal is not automatically atomic with the database transaction. The database update may succeed while Redis removal fails, which can temporarily expose stale data. That is why TTLs, retry policies, or event-driven invalidation may be necessary for important data. Cache invalidation failures should be logged and measured rather than silently ignored.

Handling Redis unavailability

Redis is a performance component, not the source of truth for Catalog data. For read operations, it is often preferable to continue with a database query when a Redis connection failure occurs.

try
{
    var cached = await _cache.GetStringAsync(key, cancellationToken);
    if (cached is not null)
    {
        return JsonSerializer.Deserialize<ProductDto>(cached);
    }
}
catch (RedisException ex)
{
    _logger.LogWarning(ex, "Redis read failed for key {CacheKey}", key);
}

var product = await LoadFromDatabaseAsync(productId, cancellationToken);

try
{
    if (product is not null)
    {
        await _cache.SetStringAsync(
            key,
            JsonSerializer.Serialize(product),
            new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
            },
            cancellationToken);
    }
}
catch (RedisException ex)
{
    _logger.LogWarning(ex, "Redis write failed for key {CacheKey}", key);
}

return product;

This fallback should not be applied blindly to every endpoint. If Redis fails, database traffic may increase significantly. Use logs, metrics, timeouts, and, when appropriate, rate limiting to control the effect. A failed cache write usually should not fail a read request, but a cache read failure may need a different policy when the data has strict consistency or security requirements.

Common mistakes

  • Using the cache as the database: The application should remain functionally correct if Redis is cleared.
  • Skipping expiration: Entries without TTLs can remain stale and consume memory indefinitely.
  • Skipping invalidation: A user may continue to see an old product name or price after an update.
  • Creating uncontrolled keys for every query variation: High key cardinality can consume Redis memory quickly.
  • Caching large objects without measurement: Consider payload size, serialization cost, and network traffic.
  • Ignoring cache stampede: When one key expires, many requests may query the database simultaneously. Consider locking, request coalescing, or expiration jitter where necessary.

Practice exercise

  1. Add a Redis resource named catalog-cache to the AppHost and reference it from Catalog.
  2. Implement GET /api/products/{id} in the Catalog API.
  3. Observe the database access on the first request and the cache hit on the second request.
  4. Update a product and verify that its cache key is removed.
  5. Stop the Redis resource and verify that product reads fall back to the database in a controlled way.
  6. List the production metrics you would need for cache hits, misses, Redis errors, database fallback count, and cache write failures.

Conclusion

In this lesson, we defined a Redis resource in the Aspire AppHost and connected it to the Catalog service. We implemented cache-aside with IDistributedCache, designed versioned keys, added expiration and invalidation, and handled Redis failures by falling back to the database. Most importantly, we preserved the rule that Redis is an optimization layer rather than the authoritative data store.

In the next lesson, we will add RabbitMQ and examine how services can communicate through events instead of relying only on direct HTTP calls. The resource-reference, failure-handling, and observability principles used with Redis will also apply to the messaging infrastructure.

Sources