LESSON 9 OF 12

9. Hardening the Cache-Aside Flow and Error Handling

Build a resilient cache-aside service by handling Redis outages, timeouts, cancellation, and database fallback safely.

50 dk 81

Introduction

In the previous lesson, we examined cache invalidation and data consistency. This lesson makes the cache-aside pattern more resilient for production. The goal is not only to improve the cache hit ratio. We also need to ensure that the main business flow continues when Redis is slow, unavailable, or contains a corrupted cache entry.

A cache should accelerate access to the database, not become a mandatory source of truth. Therefore, a Redis failure should not automatically produce an HTTP 500 response for a normal read operation. The application may become slower without the cache, but it should still be able to retrieve correct data from the database whenever possible. This behavior is commonly called graceful degradation.

1. The steps of a resilient cache-aside flow

For a service that reads product details, the standard flow can be defined as follows:

  1. Create a deterministic and safe cache key from the route or request data.
  2. Read the cache.
  3. If the cache contains a value, deserialize and return it.
  4. On a cache miss, query the database using the request cancellation token.
  5. If a record exists, attempt to write it to the cache. A cache write failure must not invalidate the database result.
  6. Return the database result.

For update and delete operations, the database remains the source of truth. After a successful update, remove the related cache key. If Redis fails during invalidation, log the problem; however, if the database update succeeded, it is usually incorrect to report the entire business operation as failed only because the secondary cache could not be removed.

Separate cache failures from business failures

Not every exception should be handled in the same way. A database connection failure may stop the operation because the database is the authoritative data source. A Redis connection failure, timeout, or temporary network problem can usually be treated as a cache miss during a cache-aside read.

ConditionRecommended behavior
Cache connection failureLog it, treat it as a miss, and continue to the database.
Cache timeoutStop waiting and use the fallback path.
Serialization failureDelete the invalid entry if possible and rebuild it from the database.
Database failurePropagate the error according to the business and API policy.
Request cancellationStop unnecessary work and do not swallow the cancellation.

2. Managing timeouts and cancellation tokens

The HttpContext.RequestAborted token may be canceled when the client disconnects or when an ASP.NET Core request timeout is reached. Pass this token to both database and cache operations so that work for an abandoned request does not continue consuming resources.

However, the request token alone is not enough. If the Redis connection remains open but does not respond, a cache call may wait for the entire request timeout. For this reason, cache operations should have a shorter, local timeout. It is important to distinguish a local cache timeout from client cancellation: if the client really canceled the request, the cancellation should be propagated; if only the Redis operation exceeded its budget, graceful fallback can be used.

private static CancellationTokenSource CreateCacheTokenSource(
    CancellationToken requestToken,
    TimeSpan cacheTimeout)
{
    var source = CancellationTokenSource.CreateLinkedTokenSource(requestToken);
    source.CancelAfter(cacheTimeout);
    return source;
}

The timeout should be selected from measurements rather than guesswork. When the application and Redis are on the same network, a small budget may be sufficient. With a remote network or a busy Redis cluster, the value may need to be higher. The purpose is not to make the timeout as large as possible; it is to prevent the cache from blocking the main request unnecessarily.

3. A safe cache wrapper

The following service centralizes IDistributedCache operations. A failed cache read returns null. Write and removal operations return a Boolean indicating whether they completed successfully. The class does not hide every exception indiscriminately; it makes the cache’s secondary role explicit in the application design.

using System.Diagnostics;
using Microsoft.Extensions.Caching.Distributed;
using StackExchange.Redis;

public sealed class SafeDistributedCache
{
    private readonly IDistributedCache _cache;
    private readonly ILogger<SafeDistributedCache> _logger;
    private readonly TimeSpan _timeout = TimeSpan.FromMilliseconds(80);

    public SafeDistributedCache(
        IDistributedCache cache,
        ILogger<SafeDistributedCache> logger)
    {
        _cache = cache;
        _logger = logger;
    }

    public async Task<byte[]?> GetAsync(
        string key,
        CancellationToken requestToken)
    {
        var stopwatch = Stopwatch.StartNew();

        try
        {
            using var timeoutSource =
                CancellationTokenSource.CreateLinkedTokenSource(requestToken);
            timeoutSource.CancelAfter(_timeout);

            var value = await _cache.GetAsync(key, timeoutSource.Token);
            _logger.LogDebug(
                "Cache read completed. Key: {Key}, Hit: {Hit}, ElapsedMs: {ElapsedMs}",
                key, value is not null, stopwatch.Elapsed.TotalMilliseconds);

            return value;
        }
        catch (OperationCanceledException) when (!requestToken.IsCancellationRequested)
        {
            _logger.LogWarning(
                "Cache read timed out. Key: {Key}, ElapsedMs: {ElapsedMs}",
                key, stopwatch.Elapsed.TotalMilliseconds);
            return null;
        }
        catch (RedisConnectionException exception)
        {
            _logger.LogWarning(exception, "Redis connection failed for key {Key}", key);
            return null;
        }
        catch (RedisTimeoutException exception)
        {
            _logger.LogWarning(exception, "Redis operation timed out for key {Key}", key);
            return null;
        }
    }

    public async Task<bool> SetAsync(
        string key,
        byte[] value,
        DistributedCacheEntryOptions options,
        CancellationToken requestToken)
    {
        try
        {
            using var timeoutSource =
                CancellationTokenSource.CreateLinkedTokenSource(requestToken);
            timeoutSource.CancelAfter(_timeout);
            await _cache.SetAsync(key, value, options, timeoutSource.Token);
            return true;
        }
        catch (OperationCanceledException) when (!requestToken.IsCancellationRequested)
        {
            _logger.LogWarning("Cache write timed out for key {Key}", key);
            return false;
        }
        catch (RedisConnectionException exception)
        {
            _logger.LogWarning(exception, "Redis write failed for key {Key}", key);
            return false;
        }
        catch (RedisTimeoutException exception)
        {
            _logger.LogWarning(exception, "Redis write timed out for key {Key}", key);
            return false;
        }
    }

    public async Task<bool> RemoveAsync(
        string key,
        CancellationToken requestToken)
    {
        try
        {
            using var timeoutSource =
                CancellationTokenSource.CreateLinkedTokenSource(requestToken);
            timeoutSource.CancelAfter(_timeout);
            await _cache.RemoveAsync(key, timeoutSource.Token);
            return true;
        }
        catch (OperationCanceledException) when (!requestToken.IsCancellationRequested)
        {
            _logger.LogWarning("Cache removal timed out for key {Key}", key);
            return false;
        }
        catch (RedisConnectionException exception)
        {
            _logger.LogWarning(exception, "Redis removal failed for key {Key}", key);
            return false;
        }
        catch (RedisTimeoutException exception)
        {
            _logger.LogWarning(exception, "Redis removal timed out for key {Key}", key);
            return false;
        }
    }
}

The filter on OperationCanceledException is essential. When requestToken.IsCancellationRequested is true, the client or request pipeline canceled the operation. Swallowing that exception and continuing to the database would be incorrect. When only the local cache timeout fired, the request token remains active and the fallback path can continue.

4. Implementing the cache-aside service

Next, use the safe cache wrapper inside a product service. The example stores the ProductDto from the previous lesson as JSON bytes.

public sealed class ProductService
{
    private readonly IProductRepository _repository;
    private readonly SafeDistributedCache _cache;
    private readonly ILogger<ProductService> _logger;

    public ProductService(
        IProductRepository repository,
        SafeDistributedCache cache,
        ILogger<ProductService> logger)
    {
        _repository = repository;
        _cache = cache;
        _logger = logger;
    }

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

        if (cachedBytes is not null)
        {
            return JsonSerializer.Deserialize<ProductDto>(cachedBytes);
        }

        var product = await _repository.GetAsync(productId, cancellationToken);
        if (product is null)
        {
            return null;
        }

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

        var cacheWriteSucceeded = await _cache.SetAsync(
            key, bytes, options, cancellationToken);

        if (!cacheWriteSucceeded)
        {
            _logger.LogInformation(
                "Product {ProductId} returned through database fallback",
                productId);
        }

        return product;
    }

    public async Task UpdateAsync(
        ProductDto product,
        CancellationToken cancellationToken)
    {
        await _repository.UpdateAsync(product, cancellationToken);

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

        if (!removed)
        {
            _logger.LogWarning(
                "Database updated but cache invalidation failed for product {ProductId}",
                product.Id);
        }
    }
}

Deserialization must also be treated as a possible failure point. A cache entry may be corrupted or written by an older application version. In production, consider handling deserialization errors, deleting the invalid entry, and rebuilding the value from the database. Do not hide systematic serialization problems by silently ignoring every exception; add structured logs, metrics, and alerts.

5. Redis configuration and connection lifetime

ConnectionMultiplexer should be long-lived and shared by the application. Opening a new connection for every HTTP request increases connection overhead and can exhaust resources under load.

var redisConfiguration = builder.Configuration.GetConnectionString("Redis")!;

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

StackExchange.Redis exposes connection and asynchronous command timeout settings. These settings do not replace the local application timeout in the wrapper; they serve different purposes. Client configuration controls connection and command behavior, while the application timeout defines how much of a single HTTP request’s budget may be spent waiting for the cache.

6. Measuring fallback performance

Graceful degradation is not complete until it is measurable. When Redis is unavailable, monitor the additional database load and latency. At minimum, collect the following metrics:

  • Cache hit and miss counts.
  • Cache timeout count.
  • Redis connection failure count.
  • Requests completed through the database fallback.
  • Cache hit, cache miss, and database fallback duration.
  • Database CPU, connection pool usage, and query latency during fallback.

A Stopwatch is enough for a small experiment. In a larger service, define counters and histograms with System.Diagnostics.Metrics.

private static readonly Meter Meter = new("Catalog.Api.Cache");
private static readonly Counter<long> FallbackCounter =
    Meter.CreateCounter<long>("cache.fallback");
private static readonly Histogram<double> FallbackDuration =
    Meter.CreateHistogram<double>("cache.fallback.duration", "ms");

Run a load test with Redis enabled, then repeat it after disconnecting Redis. Compare p95 and p99 latency, error rate, database query count, and database resource usage. During fallback, the error rate should remain controlled while latency and database load increase within an expected range. If the entire application becomes slow, the cache timeout may be too long or the database has not been sized for fallback traffic.

7. Common mistakes

  • Returning HTTP 500 for every cache failure: In most read scenarios, the cache is not the authoritative source.
  • Silently swallowing exceptions: The request may succeed, but operators lose visibility. Add structured logs and metrics.
  • Ignoring request cancellation: Continuing database and Redis calls after a client disconnect wastes resources.
  • Increasing the timeout without measurement: Waiting longer does not fix the underlying problem and may consume request, thread, and connection capacity.
  • Using synchronous Redis or database calls: Calls such as .Result and .Wait() can increase thread pool pressure in ASP.NET Core.
  • Making cache writes mandatory during fallback: Returning correct database data is more important than successfully repopulating the cache.
  • Creating a connection per request: Use a shared multiplexer and an appropriate connection lifetime.

8. Practice exercise

Run the following experiment for a GET /products/{id} endpoint:

  1. Add SafeDistributedCache and route cache reads, writes, and removals through it.
  2. Pass HttpContext.RequestAborted to the service method.
  3. Configure a cache timeout between 50 and 100 milliseconds.
  4. Stop the Redis container and request the same product again.
  5. Verify that the response still comes from the database and that the logs report a fallback.
  6. Start Redis again and verify that a later request is a cache hit.
  7. Compare p95 latency and database query count with Redis enabled and disabled.

Success criterion: when Redis is unavailable, the product endpoint should not unnecessarily return HTTP 500; when the client cancels the request, a long-running fallback operation should not continue.

Conclusion

This lesson moved the cache-aside pattern beyond the basic “check the cache, otherwise query the database” flow. We centralized cache reads, writes, and removals; limited the time Redis can block a request; separated request cancellation from a local cache timeout; and implemented database fallback when Redis fails.

The next step is to strengthen this flow against cache stampede, coordinate concurrent misses, and introduce techniques such as stale-while-revalidate. A reliable cache strategy does not assume that the cache will never fail. It defines in advance how the application should behave when it does.

Sources