Introduction
In the previous lesson, we ran Redis with Docker and connected the ASP.NET Core application through IDistributedCache. In this lesson, we will make the cache layer maintainable for a real application. Instead of writing only strings or byte arrays manually, we will convert product DTOs to JSON, store the JSON in Redis, deserialize it back into strongly typed objects, and centralize these operations in a reusable service.
The distributed cache API treats values as byte arrays. Therefore, an object such as ProductDto cannot be sent to Redis directly. It must first be serialized into a transportable representation. When reading, the JSON payload is deserialized back into the DTO. Although this process is straightforward, production systems can develop difficult-to-diagnose problems if serializer options, null values, model versions, key design, and payload size are ignored.
The goal of this lesson is to create a generic RedisCacheService that prevents different parts of the application from duplicating JSON and byte-array logic. The service will return typed results, use centralized cache options, handle invalid or incompatible payloads safely, and provide a foundation for observable cache operations.
1. Data modeling in Redis with JSON
At a basic level, Redis is a key-value data store. When ASP.NET Core uses IDistributedCache, the value stored is commonly a UTF-8 encoded byte array rather than the original object. In this lesson, each product list will be stored as a JSON value under one Redis string key.
Assume that the API exposes the following DTO:
public sealed record ProductDto(
int Id,
string Name,
decimal Price,
string? Description,
DateTimeOffset UpdatedAt
);The cached JSON can look like this:
{
"id": 42,
"name": "Mechanical Keyboard",
"price": 89.99,
"description": null,
"updatedAt": "2026-11-03T12:00:00+00:00"
}The advantage of this approach is that multiple application servers can read the same payload, and the Redis value can be inspected when necessary. The disadvantage is that JSON can consume more space than a binary representation and serialization requires CPU time. For small web payloads, JSON is usually a practical starting point. For large object graphs, DTOs with hundreds of fields, or very high request rates, measure both payload size and serialization time.
2. Centralizing JsonSerializerOptions
Instead of creating serializer options on every call, use one application-level configuration. This keeps property naming, null handling, enum formatting, and case-insensitive reading consistent across all cache entries.
using System.Text.Json;
using System.Text.Json.Serialization;
public sealed class CacheOptions
{
public string KeyPrefix { get; set; } = "catalog";
public int DefaultMinutes { get; set; } = 5;
public int MaxPayloadBytes { get; set; } = 512 * 1024;
}
public static class CacheJsonOptions
{
public static JsonSerializerOptions Create()
{
return new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
WriteIndented = false
};
}
}JsonSerializerDefaults.Web provides a useful starting point for web applications. Setting WriteIndented = false avoids adding whitespace to cache payloads. Because production cache values are normally not formatted for human reading, indented JSON usually adds unnecessary bytes.
Should null values be preserved or ignored?
When Description is null, two behaviors are possible. Keeping the null property explicitly communicates that the property exists but has no value. Ignoring it reduces the payload slightly but removes the distinction between “the property is missing” and “the property exists with a null value.”
Make this decision according to the data contract. Preserve nulls when clients or a future application version need that distinction. If the property is merely optional display information, JsonIgnoreCondition.WhenWritingNull can be appropriate.
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNullDo not change this setting casually. Writing one JSON shape with null properties and another shape without them under the same key complicates troubleshooting and schema migration.
3. Centralized keys and expiration options
Key construction should belong to the cache layer. This prevents controllers and repositories from independently inventing prefixes, whitespace conventions, or version formats. For example, product keys can use the following structure:
catalog:v1:products:page:1:size:20
catalog:v1:product:42The v1 segment identifies the data contract version. If the DTO changes in a backward-incompatible way, the application can switch to v2 keys without attempting to read old entries. Old keys will disappear when their expiration time is reached.
public static class CacheKeys
{
public static string Product(int id) => $"product:{id}";
public static string ProductPage(int page, int size) =>
$"products:page:{page}:size:{size}";
}Combine the key with the configured prefix and version:
private readonly CacheOptions _options;
private string BuildKey(string key)
=> $"{_options.KeyPrefix}:v1:{key}";This prevents applications sharing the same Redis instance from accidentally overwriting each other’s entries. In a multi-tenant application, include a trusted and normalized tenant identifier in the key as well.
4. A generic Redis cache service
The following service uses IDistributedCache, so higher layers do not depend directly on Redis APIs. If another distributed cache provider is selected later, most application code can remain unchanged.
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
public interface ICacheService
{
Task<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default);
Task SetAsync<T>(string key, T value, TimeSpan? lifetime = null,
CancellationToken cancellationToken = default);
Task RemoveAsync(string key, CancellationToken cancellationToken = default);
}public sealed class RedisCacheService : ICacheService
{
private readonly IDistributedCache _cache;
private readonly CacheOptions _options;
private readonly JsonSerializerOptions _jsonOptions;
private readonly ILogger<RedisCacheService> _logger;
public RedisCacheService(
IDistributedCache cache,
IOptions<CacheOptions> options,
ILogger<RedisCacheService> logger)
{
_cache = cache;
_options = options.Value;
_jsonOptions = CacheJsonOptions.Create();
_logger = logger;
}
public async Task<T?> GetAsync<T>(
string key,
CancellationToken cancellationToken = default)
{
var fullKey = BuildKey(key);
var bytes = await _cache.GetAsync(fullKey, cancellationToken);
if (bytes is null || bytes.Length == 0)
return default;
try
{
return JsonSerializer.Deserialize<T>(bytes, _jsonOptions);
}
catch (JsonException exception)
{
_logger.LogWarning(exception,
"Cache payload could not be deserialized. Key: {CacheKey}", fullKey);
await _cache.RemoveAsync(fullKey, cancellationToken);
return default;
}
}
public async Task SetAsync<T>(
string key,
T value,
TimeSpan? lifetime = null,
CancellationToken cancellationToken = default)
{
var fullKey = BuildKey(key);
var bytes = JsonSerializer.SerializeToUtf8Bytes(value, _jsonOptions);
if (bytes.Length > _options.MaxPayloadBytes)
{
throw new InvalidOperationException(
$"Cache payload is too large: {bytes.Length} bytes.");
}
var cacheEntryOptions = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow =
lifetime ?? TimeSpan.FromMinutes(_options.DefaultMinutes)
};
await _cache.SetAsync(
fullKey, bytes, cacheEntryOptions, cancellationToken);
}
public Task RemoveAsync(
string key,
CancellationToken cancellationToken = default)
=> _cache.RemoveAsync(BuildKey(key), cancellationToken);
private string BuildKey(string key)
=> $"{_options.KeyPrefix}:v1:{key}";
}SerializeToUtf8Bytes produces UTF-8 bytes directly, which can avoid an unnecessary intermediate string compared with serializing to a string and encoding it afterward. The size check does not represent every Redis limitation; it enforces an application-level payload policy. A limit such as 512 KB can reveal early that a product list has accidentally become a huge object graph.
5. Dependency injection and configuration
Assuming the Redis provider was registered in the previous lesson, register the options and service in Program.cs:
builder.Services.Configure<CacheOptions>(
builder.Configuration.GetSection("Cache"));
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration =
builder.Configuration.GetConnectionString("Redis");
options.InstanceName = "catalog-api:";
});
builder.Services.AddSingleton<ICacheService, RedisCacheService>();Example appsettings.json:
{
"ConnectionStrings": {
"Redis": "localhost:6379"
},
"Cache": {
"KeyPrefix": "catalog-api",
"DefaultMinutes": 5,
"MaxPayloadBytes": 524288
}
}Connection strings should not be kept in source control in production. Use Secret Manager, environment variables, or a secure secret store. The cache service can be registered as a singleton because it does not keep request-specific state and the distributed cache provider is designed to be managed through the application lifetime.
6. Using typed cache results in a product query
Controllers or application services can now use typed results without knowing JSON details:
public sealed class ProductService
{
private readonly ICacheService _cache;
private readonly ProductDbContext _db;
public ProductService(ICacheService cache, ProductDbContext db)
{
_cache = cache;
_db = db;
}
public async Task<ProductDto?> GetAsync(
int id,
CancellationToken cancellationToken)
{
var cacheKey = CacheKeys.Product(id);
var cached = await _cache.GetAsync<ProductDto>(
cacheKey, cancellationToken);
if (cached is not null)
return cached;
var product = await _db.Products
.Where(x => x.Id == id)
.Select(x => new ProductDto(
x.Id,
x.Name,
x.Price,
x.Description,
x.UpdatedAt))
.SingleOrDefaultAsync(cancellationToken);
if (product is not null)
{
await _cache.SetAsync(
cacheKey,
product,
TimeSpan.FromMinutes(10),
cancellationToken);
}
return product;
}
}On a cache miss, the database is queried and the result is stored in Redis. Caching a dedicated DTO avoids serializing entity navigation properties or unrelated fields. DTOs designed specifically for caching are usually safer for payload size and contract evolution.
7. Version compatibility and invalid payloads
Cache is not the primary data source, but old JSON payloads can still remain in Redis after an application deployment. If the new DTO is backward-compatible, missing properties may receive default values. If a property name or type changes, deserialization can fail.
The simplest strategy is to increment the key version: use catalog:v2:product:42 instead of catalog:v1:product:42. A more advanced approach adds a schemaVersion property to the payload and converts older versions. Because cached data can normally be regenerated, key versioning is often simpler and safer for performance-oriented scenarios.
When deserialization fails, the service can remove the entry and treat it as a cache miss rather than returning the exception to the user. This is safe only when the cache value can be regenerated. Track these events with logs and metrics; repeated invalid payloads usually indicate a deployment or serializer contract problem.
8. Common mistakes
- Caching entities directly: Navigation properties, lazy loading, and reference cycles can create serialization problems. Use cache-specific DTOs.
- Creating different JsonSerializerOptions for every call: The same type may be written in multiple JSON shapes. Centralize the options.
- Ignoring nulls without a contract decision: A missing property and a null property may not mean the same thing.
- Leaving versions out of keys: Model changes can make older payloads unreadable.
- Caching unnecessarily large lists: Apply pagination and measure payload size.
- Using WriteIndented: Production cache values gain unnecessary bytes and CPU cost in exchange for human readability.
- Treating cache failures like database failures: The application needs a controlled fallback policy when the cache is unavailable.
9. Practice exercise
- Create a
CategoryDtorecord withId,Name, and nullableDescriptionproperties. - Store the category list through
ICacheServiceusing a key following thecatalog:v1:categoriesconvention. - Test one serializer configuration that preserves nulls and another that omits them.
- Measure the JSON byte length and compare the two payloads.
- Add a new DTO property, change the key version to
v2, and verify that old cache entries do not affect the new application version. - Use Redis CLI or another Redis client to inspect the key’s TTL.
Conclusion
In this lesson, we stored product DTOs in Redis through JSON serialization and converted them back into typed objects. By centralizing serializer options, we kept naming policies, null behavior, and payload shape consistent. Generic GetAsync, SetAsync, and RemoveAsync helpers separated cache mechanics from the application layer.
We also covered key versioning, payload size limits, invalid JSON cleanup, and the value of dedicated DTOs in production systems. In the next stage, this service can be strengthened against cache stampede, stale data, and invalidation problems within a complete cache-aside workflow.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/deserialization
- https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/ignore-properties
- https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions?view=net-10.0