Introduction
In the previous lesson, we used MemoryCache to build a cache that lives inside a single ASP.NET Core application instance. This approach is fast, but every server or container instance has its own cache. When an application is scaled horizontally, a value written by instance A is invisible to instance B. The result can be inconsistent responses, repeated database queries, and cache loss whenever a process restarts.
This lesson introduces distributed caching, where cached data is stored outside the application process and shared by multiple API instances. We will use the provider-independent IDistributedCache abstraction, connect it to Redis, store product data as JSON, implement the cache-aside pattern, configure TTL and invalidation, and design a controlled response when Redis is slow or unavailable.
MemoryCache versus distributed cache
| Property | MemoryCache | Distributed cache with Redis |
|---|---|---|
| Data location | Application process memory | External Redis service |
| Multiple instances | Each instance has a separate cache | Instances share the same cache |
| Application restart | Cached values are lost | Values may remain, depending on Redis configuration |
| Network cost | Minimal | A network call is required |
| Typical use | Local, short-lived data | Horizontally scaled applications |
AddDistributedMemoryCache can be useful because it implements the same abstraction, but it is not a truly distributed cache. Each application instance still keeps its own values. It is suitable for development, testing, or a single-server scenario. When several production instances must share cached data, use an external provider such as Redis.
The IDistributedCache contract
IDistributedCache hides provider-specific details from the application layer. Its core operations are GetAsync, SetAsync, RefreshAsync, and RemoveAsync. The GetStringAsync and SetStringAsync extension methods are convenient for text values. Because the underlying abstraction stores byte arrays, complex objects must be serialized before they are cached.
The abstraction also keeps the service layer independent of the Redis client API. Tests can use a distributed memory provider, while production can use Redis without changing the main cache-aside flow. If an application needs Redis-specific atomic operations or advanced data structures, using the native client is possible, but that should be an explicit architectural decision.
Installing and configuring Redis
Install the Redis provider package:
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedisRegister the provider in Program.cs:
using Microsoft.Extensions.Caching.Distributed;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("Redis");
options.InstanceName = "catalog-api:";
});
builder.Services.AddScoped<ProductCatalogService>();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();Keep the connection string in configuration or a secure secret store rather than in source code:
{
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}The InstanceName option helps separate keys belonging to different applications that share a Redis service. In production, TLS, authentication, network access, and connection settings should follow the recommendations of the Redis service being used.
Building a JSON-based cache service
Cache keys should be deliberate rather than arbitrary strings. Include the resource, schema version, and relevant query parameters. For example, catalog:products:v1:page:1:size:20 is easier to inspect and invalidate than a key with no structure.
The following service stores a product list as JSON:
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
public sealed record ProductDto(int Id, string Name, decimal Price);
public sealed class ProductCatalogService
{
private readonly IDistributedCache _cache;
private readonly ProductRepository _repository;
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
public ProductCatalogService(
IDistributedCache cache,
ProductRepository repository)
{
_cache = cache;
_repository = repository;
}
public async Task<IReadOnlyList<ProductDto>> GetProductsAsync(
int page,
int pageSize,
CancellationToken cancellationToken)
{
var key = $"catalog:products:v1:page:{page}:size:{pageSize}";
var cachedJson = await _cache.GetStringAsync(key, cancellationToken);
if (!string.IsNullOrWhiteSpace(cachedJson))
{
return JsonSerializer.Deserialize<List<ProductDto>>(
cachedJson, JsonOptions) ?? [];
}
var products = await _repository.GetPageAsync(
page, pageSize, cancellationToken);
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(2),
SlidingExpiration = TimeSpan.FromSeconds(30)
};
var json = JsonSerializer.Serialize(products, JsonOptions);
await _cache.SetStringAsync(key, json, options, cancellationToken);
return products;
}
}The service first asks Redis for the key. On a hit, the database is skipped. On a miss, the source repository is called, the result is serialized, and the JSON is stored with an expiration policy. This is the cache-aside pattern: the application reads from the cache and populates it when necessary.
TTL and expiration strategies
TTL defines how long a cache entry can remain available. AbsoluteExpirationRelativeToNow gives the entry a fixed maximum lifetime from the time it is written. SlidingExpiration renews the lifetime when the entry is accessed. When both are used, frequently accessed data can remain available through sliding expiration, while the absolute expiration provides an upper bound.
Choose a TTL based on how frequently the data changes, the cost of serving stale data, and the load imposed on the source system. A product description might tolerate several minutes, while inventory or price data may require a shorter TTL or explicit invalidation. TTL limits staleness; it does not guarantee immediate consistency.
Invalidation when data changes
When a product is updated, both its detail entry and related list entries may become stale. For a small application, known detail keys can be removed after a successful update:
public async Task UpdateProductAsync(
ProductUpdateModel model,
CancellationToken cancellationToken)
{
await _repository.UpdateAsync(model, cancellationToken);
await _cache.RemoveAsync(
$"catalog:product:{model.Id}:v1", cancellationToken);
// For paginated lists, use a key catalog or versioning strategy.
}Avoid using Redis KEYS with a wildcard during normal production traffic. Searching a large keyspace can be expensive. Safer options include explicitly tracking keys, using versioned key prefixes, or designing the cache around Redis data structures. For example, changing catalog:products:v1 to catalog:products:v2 makes an old query format logically obsolete without scanning every old key.
Testing multiple API instances
Assume that two API instances are running: instance A and instance B. With MemoryCache, a value created by A cannot be read by B. With Redis, both instances use the same external store:
| Operation | MemoryCache | Redis |
|---|---|---|
| A receives the first request | A populates its local cache | A populates shared Redis |
| B receives the same request | B queries the database | B receives a Redis cache hit |
| A restarts | A loses its entries | Redis entries may remain until expiration |
| A updates data | B may retain stale data | B sees new data after invalidation |
Run both instances on different ports or in separate containers. Confirm through logs or metrics that the first request reaches the repository and the request to the second instance reads from Redis. Measure cache hits, misses, serialization time, Redis round-trip duration, and database query count separately instead of looking only at total request time.
Handling Redis latency and failures
Redis is an external network dependency. If every cache failure causes the API request to fail, a performance component has become a single point of failure. Cache data should normally not be treated as the only source of critical business data. A controlled fail-open approach can allow the application to fall back to the source system:
public async Task<string?> TryGetCachedAsync(
string key,
CancellationToken cancellationToken)
{
try
{
return await _cache.GetStringAsync(key, cancellationToken);
}
catch (RedisConnectionException ex)
{
_logger.LogWarning(ex, "Redis read failed. Key: {CacheKey}", key);
return null;
}
}In a real application, catch only the relevant Redis and timeout exceptions, use bounded timeouts, and monitor error rates. Falling back to the database can create a sudden load spike during a Redis outage. Rate limiting, circuit breakers, short dependency timeouts, request coalescing, or temporarily serving stale data can reduce this risk.
Another risk is a cache stampede. When a popular key expires, many requests can miss at the same time and all query the database. A small random component in TTL values, a key-specific lock, or a mechanism that allows only one request to refresh the entry can help. A process-local lock, however, does not coordinate different API instances, so a distributed solution requires additional design and testing.
Common mistakes
- Assuming DistributedMemoryCache is Redis: The abstraction is the same, but entries are not shared between instances.
- Using unlimited or very long TTL values: Forgotten invalidation can expose stale data for too long.
- Leaving query parameters out of keys: Different users, languages, pages, or filters may accidentally share a value.
- Caching sensitive data without a scope: User-specific data must include the correct identity and authorization dimensions.
- Propagating every cache exception: A cache outage should not automatically make the entire API unavailable.
- Ignoring JSON size: Large objects increase serialization cost, network traffic, and Redis memory usage.
- Invalidating only from one write endpoint: Imports, background jobs, and direct data changes must also be considered.
Practice exercise
Add Redis caching to the existing product API:
- Start Redis and register
IDistributedCache. - Design a versioned key containing page and page-size parameters.
- Log cache hits and misses.
- Store the list result as JSON with a two-minute absolute expiration.
- Remove the product detail key after an update.
- Run two API instances and compare the first request with the request sent to the second instance.
- Stop Redis temporarily and verify that the API falls back to the repository in a controlled manner.
- Report average latency, p95 latency, Redis errors, cache hit ratio, and database query count.
Conclusion
A distributed cache is not simply a larger MemoryCache. It introduces network latency, shared data ownership, consistency concerns, expiration policies, and dependency-failure scenarios. IDistributedCache allows the application to remain provider-independent, while Redis enables multiple API instances to use a common cache and can preserve entries beyond an individual process lifetime.
Design cache-aside behavior, meaningful keys, appropriate TTLs, explicit invalidation rules, and a resilient fallback path together. Always verify the result with measurements: a cache should reduce expensive work without introducing unacceptable staleness, memory usage, or dependency risk.