LESSON 5 OF 12

5. Creating a Cache Abstraction with IDistributedCache

Move cache access behind a shared service using IDistributedCache, implement string and byte operations, configure JSON serialization, and prepare for provider changes.

55 dk 68

Introduction

In the previous lesson, we examined how cache keys can be designed and how cached data can be isolated. In this lesson, we will prevent endpoint code from depending directly on a specific cache provider. We will create a reusable cache service based on the ASP.NET Core IDistributedCache abstraction.

With this approach, a controller or endpoint does not need to know whether the application uses Redis or another cache provider. The application communicates with our service through operations such as GetAsync, SetAsync, and RemoveAsync. Provider configuration, serialization decisions, and expiration rules remain in one place instead of being scattered throughout the application.

Goal: Simplify endpoint code, centralize cache access, and make it possible to test the application with a fake IDistributedCache instead of a real Redis server.

Why use IDistributedCache?

IMemoryCache stores data in the memory of the application server. In a web farm with multiple servers, each server may contain a different cache state. IDistributedCache connects the application to a common cache contract. The implementation behind that contract can be Redis, SQL Server, PostgreSQL, or distributed memory cache for development purposes.

The name IDistributedCache does not by itself guarantee that data is distributed. For example, AddDistributedMemoryCache implements the same interface but stores data only in the memory of the current application instance. A real multi-server deployment requires an external provider such as Redis.

Core operations

OperationDescription
GetAsyncRetrieves the value for a key as a byte[].
SetAsyncStores a byte[] value with expiration options.
RefreshAsyncRefreshes the expiration of an entry using sliding expiration.
RemoveAsyncDeletes the specified key from the cache.

1. Configure the cache provider

For development, we can use distributed memory cache to test the abstraction. This makes a future Redis migration easier because application code depends on the interface rather than on a specific provider.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDistributedMemoryCache();
builder.Services.AddScoped<IProductCache>, ProductCache>();

var app = builder.Build();

The registration above is intended for development examples. When Redis is required, we can replace the provider registration without changing the rest of the application services:

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

Do not place the connection string directly in source code. Use Secret Manager, environment variables, or a secure configuration store. The InstanceName option can help separate keys belonging to applications that share the same Redis environment; application-level key design is still necessary.

2. Wrap string and byte operations

IDistributedCache fundamentally works with byte arrays. For text values, the SetStringAsync and GetStringAsync extension methods from Microsoft.Extensions.Caching.Distributed can be used. However, calling them directly from endpoints spreads cache decisions across the application. A dedicated service provides a more consistent design.

public interface IProductCache
{
    Task<ProductDto?> GetAsync(int productId, CancellationToken cancellationToken = default);
    Task SetAsync(ProductDto product, CancellationToken cancellationToken = default);
    Task RemoveAsync(int productId, CancellationToken cancellationToken = default);
}

Next, we will store the product as JSON:

using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;

public sealed class ProductCache : IProductCache
{
    private readonly IDistributedCache _cache;
    private readonly JsonSerializerOptions _jsonOptions;

    public ProductCache(IDistributedCache cache)
    {
        _cache = cache;
        _jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);
    }

    private static string BuildKey(int productId)
        => $"catalog:product:{productId}";

    public async Task<ProductDto?> GetAsync(
        int productId,
        CancellationToken cancellationToken = default)
    {
        var key = BuildKey(productId);
        var json = await _cache.GetStringAsync(key, cancellationToken);

        if (string.IsNullOrWhiteSpace(json))
        {
            return null;
        }

        return JsonSerializer.Deserialize<ProductDto>(json, _jsonOptions);
    }

    public async Task SetAsync(
        ProductDto product,
        CancellationToken cancellationToken = default)
    {
        var key = BuildKey(product.Id);
        var json = JsonSerializer.Serialize(product, _jsonOptions);
        var options = new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10),
            SlidingExpiration = TimeSpan.FromMinutes(2)
        };

        await _cache.SetStringAsync(key, json, options, cancellationToken);
    }

    public Task RemoveAsync(
        int productId,
        CancellationToken cancellationToken = default)
        => _cache.RemoveAsync(BuildKey(productId), cancellationToken);
}

The example uses string extension methods. The same flow can be implemented directly with bytes. This is useful when using a custom serializer or when you want explicit control over UTF-8 conversion.

var bytes = JsonSerializer.SerializeToUtf8Bytes(product, _jsonOptions);
await _cache.SetAsync(key, bytes, options, cancellationToken);

var cachedBytes = await _cache.GetAsync(key, cancellationToken);
var cachedProduct = cachedBytes is null
    ? null
    : JsonSerializer.Deserialize<ProductDto>(cachedBytes, _jsonOptions);

3. Move the cache-aside flow into the endpoint

The endpoint should coordinate the business flow, not manage cache infrastructure. With the cache-aside pattern, the application checks the cache first. If the value is missing, it queries the database, stores the result in the cache, and returns the response.

app.MapGet("/products/{id:int}", async (
    int id,
    IProductCache productCache,
    ProductDbContext db,
    CancellationToken cancellationToken) =>
{
    var cachedProduct = await productCache.GetAsync(id, cancellationToken);
    if (cachedProduct is not null)
    {
        return Results.Ok(cachedProduct);
    }

    var product = await db.Products
        .Where(x => x.Id == id)
        .Select(x => new ProductDto(x.Id, x.Name, x.Price))
        .SingleOrDefaultAsync(cancellationToken);

    if (product is null)
    {
        return Results.NotFound();
    }

    await productCache.SetAsync(product, cancellationToken);
    return Results.Ok(product);
});

After a successful update, the related cache entry should be removed:

app.MapPut("/products/{id:int}", async (
    int id,
    UpdateProductRequest request,
    IProductCache productCache,
    ProductDbContext db,
    CancellationToken cancellationToken) =>
{
    var product = await db.Products.FindAsync([id], cancellationToken);
    if (product is null)
    {
        return Results.NotFound();
    }

    product.Name = request.Name;
    product.Price = request.Price;
    await db.SaveChangesAsync(cancellationToken);
    await productCache.RemoveAsync(id, cancellationToken);

    return Results.NoContent();
});

If the cache is removed before the database update, another request may read the old database value and place it back into the cache. For simple workflows, updating the persistent record first and invalidating the cache afterward is a safer starting point.

4. JSON serialization decisions

Instead of storing an Entity Framework Core entity directly, it is usually safer to cache the DTO returned by the API. Entities can contain navigation properties, lazy-loading behavior, or unnecessary fields. DTOs reduce payload size and make the cache contract explicit.

  • Use the same serializer options when reading and writing values.
  • When changing the cache format, use a versioned key such as catalog:v2:product:42.
  • Do not store sensitive personal or security data in the cache.
  • Evaluate null caching separately. Short-lived negative caching can help when missing records are requested frequently.
  • Add logging and measurements for serialization failures, but do not log complete product payloads.

Common mistakes

Injecting a provider into the endpoint

When an endpoint depends directly on RedisCache or a StackExchange.Redis connection, changing providers becomes harder and tests become more complicated. Inject your application-specific interface instead.

Forgetting expiration options

Every cache entry should have a lifetime policy. AbsoluteExpirationRelativeToNow provides an upper limit, while SlidingExpiration allows an accessed entry to remain available longer. When both are configured, the absolute expiration still limits the maximum lifetime.

Deserializing without checking for a miss

GetAsync can return null when the key is missing. Attempting to deserialize that result can create unnecessary exceptions. Check whether the byte or string value exists first.

Ignoring CancellationToken

Distributed cache calls involve network communication. Passing the request token to cache and database operations avoids unnecessary work after a request has been cancelled.

Depending on real Redis in every test

Because the service depends on IDistributedCache, a fake or test double can be used to test cache hits, misses, and invalidation quickly. Provider-specific integration tests should be maintained separately.

Short practice exercise

  1. Create the IProductCache interface.
  2. Implement GetAsync, SetAsync, and RemoveAsync in ProductCache.
  3. Store the product DTO as JSON with a ten-minute absolute expiration.
  4. Make the GET endpoint check the cache before querying the database.
  5. Remove the product key after a successful PUT operation.
  6. Verify in a test that a cache miss queries the database and a cache hit does not.

Conclusion

In this lesson, we separated cache access from endpoint code by creating an IDistributedCache-based abstraction. We centralized string and byte operations, JSON serialization, expiration policies, and the cache-aside flow in one service.

This layer allows the application to use distributed memory cache today and move to Redis later without rewriting endpoint logic. In the next lesson, we will go deeper into Redis integration, connection configuration, and behavior in multi-server environments.

Sources