Introduction
In the previous lessons, we configured cache entries and expiration policies. This lesson focuses on one of the most important but frequently underestimated parts of caching: cache key design. A cache key is the address of a value inside the cache. If unrelated requests use the same key, one request can receive another request’s data. If every request generates an unnecessarily unique key, the cache grows, the hit ratio decreases, and invalidation becomes difficult.
A good key standard clearly represents the data type, scope, identity, and all parameters that affect the result. Redis does not provide application-level namespaces automatically, so boundaries between applications and resources must be expressed through a naming convention. For that reason, key generation should be centralized instead of being recreated inside controllers, handlers, and repositories.
Why cache keys define data isolation
Consider a product details endpoint:
GET /api/products/42For this endpoint, product:42 may be sufficient. A product listing endpoint is different:
GET /api/products?category=books&page=1&pageSize=20&sort=price&minPrice=10The result is affected by the category, page number, page size, sort order, and price filter. A key containing only the resource name, or only the page number, allows different requests to share the same cached value.
User-specific responses require the same level of care. Favorites, personalized prices, tenant-specific catalogs, and permission-filtered results may depend on a user ID, tenant ID, locale, or authorization scope. If those dimensions are omitted, the cache can become a data isolation boundary failure rather than a performance feature.
Designing a key standard
A practical schema can look like this:
{service}:{environment}:{version}:{resource}:{scope}:{identifier}:{parameters}Examples include:
catalog:prod:v1:product:public:42catalog:prod:v1:category:public:bookscatalog:prod:v1:products:list:category-books:page-1:size-20:sort-pricecatalog:prod:v1:favorites:user-8
Not every key needs every segment, but the following principles should remain consistent:
- Namespace: Prevents collisions between services sharing a Redis instance.
- Version: Separates old and new payload formats when DTOs or serialization rules change.
- Resource: Identifies whether the value represents a product, category, list, or another data type.
- Scope: Expresses whether the value is public, tenant-specific, or user-specific.
- Parameters: Includes every input that can change the response.
Normalizing key components
Normalization ensures that equivalent requests produce the same key. If the application treats BOOKS and books as the same category, convert both to a canonical form. Collections should be sorted before being included in a key; otherwise color-red,size-large and size-large,color-red create separate entries despite representing the same filter.
Define consistent rules for missing, empty, and default values. If omitted page and page=1 have the same meaning, they should map to the same key. If null and an empty string have different business meanings, they must remain distinct.
Representing list filters
Appending the raw query string to a key may appear convenient, but query parameter order, casing, special characters, and length can create inconsistent results. Instead, normalize the query model into a deterministic representation. For large parameter sets, hash the canonical representation with SHA-256.
public sealed record ProductListQuery(
string? Category,
int Page,
int PageSize,
string? Sort,
decimal? MinPrice,
decimal? MaxPrice);A canonical representation might be:
category=books|page=1|size=20|sort=price|min=10.00|max=100.00If the representation is short enough, it can be used directly. For long or externally controlled values, use a restricted character set and a hash. Do not place raw user input into a key without validating length and format.
A centralized cache key factory
Moving key generation into one service protects the naming contract as the application evolves. The following factory creates keys for products, categories, product lists, and user favorites:
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
public interface ICacheKeyFactory
{
string Product(Guid productId);
string Category(string slug);
string ProductList(ProductListQuery query);
string UserFavorites(Guid userId);
}
public sealed class CacheKeyFactory : ICacheKeyFactory
{
private const string Prefix = "catalog:prod:v1";
public string Product(Guid productId) =>
$"{Prefix}:product:public:{productId:N}";
public string Category(string slug) =>
$"{Prefix}:category:public:{NormalizeSlug(slug)}";
public string ProductList(ProductListQuery query)
{
var normalized = string.Join("|", new[]
{
$"category={NormalizeOptional(query.Category)}",
$"page={Math.Max(query.Page, 1)}",
$"size={Math.Clamp(query.PageSize, 1, 100)}",
$"sort={NormalizeOptional(query.Sort)}",
$"min={query.MinPrice?.ToString("0.00", CultureInfo.InvariantCulture) ?? "none"}",
$"max={query.MaxPrice?.ToString("0.00", CultureInfo.InvariantCulture) ?? "none"}"
});
return $"{Prefix}:products:list:{ShortHash(normalized)}";
}
public string UserFavorites(Guid userId) =>
$"{Prefix}:favorites:user:{userId:N}";
private static string NormalizeSlug(string value) =>
value.Trim().ToLowerInvariant();
private static string NormalizeOptional(string? value) =>
string.IsNullOrWhiteSpace(value)
? "none"
: value.Trim().ToLowerInvariant();
private static string ShortHash(string value)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(value));
return Convert.ToHexString(bytes)[..16].ToLowerInvariant();
}
}The important detail is that the factory does not hash arbitrary input without a defined process. The hash is generated from a deterministic canonical representation. This keeps the final key short while preserving a clear and testable contract. The normalized representation can also be logged separately when diagnosing unexpected key behavior.
Register the factory as a singleton because it is stateless:
builder.Services.AddSingleton<ICacheKeyFactory, CacheKeyFactory>();Using the factory with cache-aside
The key factory makes the cache-aside flow explicit. The service generates one canonical key, checks the distributed cache, and stores a database result under that same key after a miss:
public sealed class ProductService(
IDistributedCache cache,
ICacheKeyFactory keys,
IProductRepository repository,
IJsonCacheSerializer serializer)
{
public async Task<ProductDto?> GetAsync(
Guid productId,
CancellationToken cancellationToken)
{
var key = keys.Product(productId);
var cached = await cache.GetStringAsync(key, cancellationToken);
if (cached is not null)
return serializer.Deserialize<ProductDto>(cached);
var product = await repository.GetAsync(productId, cancellationToken);
if (product is null)
return null;
var json = serializer.Serialize(product);
await cache.SetStringAsync(
key,
json,
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
},
cancellationToken);
return product;
}
}The same factory must be used for list queries. Writing a string such as $"products:{page}:{sort}" directly in a controller makes it easy for another endpoint to use a slightly different format, which later causes invalidation gaps and duplicate entries.
Testing incorrect key design
One of the most dangerous mistakes is leaving filters out of a list key:
public static string BadProductListKey(int page) =>
$"catalog:products:page:{page}";With this implementation, two different category requests share the same cache record:
var books = BadProductListKey(1);
var electronics = BadProductListKey(1);
Assert.Equal(books, electronics); // Incorrect isolationThe correct implementation must include every input that affects the result:
[Fact]
public void Different_categories_must_have_different_keys()
{
var factory = new CacheKeyFactory();
var books = factory.ProductList(
new ProductListQuery("books", 1, 20, "price", null, null));
var electronics = factory.ProductList(
new ProductListQuery("electronics", 1, 20, "price", null, null));
Assert.NotEqual(books, electronics);
}
[Fact]
public void Equivalent_category_values_should_produce_the_same_key()
{
var factory = new CacheKeyFactory();
var first = factory.Category(" Books ");
var second = factory.Category("books");
Assert.Equal(first, second);
}At minimum, test the following cases:
- Different product IDs generate different keys.
- Different tenants or users never share a key when the response is scoped.
- Category, page, page size, sort, and price changes isolate list results.
- Equivalent normalized inputs generate the same key.
- Default values and explicitly supplied equivalent values follow the same contract.
- Every key contains the expected namespace and version.
User and tenant isolation
Authorization at the endpoint level is not enough when the response is cached. A user or tenant boundary should also be represented in the key. If tenant 7 and tenant 8 have different catalogs, their keys must be different:
public string TenantProductList(Guid tenantId, ProductListQuery query)
{
var queryKey = ProductList(query);
return $"{Prefix}:tenant:{tenantId:N}:{queryKey}";
}Avoid putting sensitive values such as email addresses or access tokens into keys. Cache keys can appear in logs, dashboards, tracing data, and operational tools. Use a stable internal identifier or a controlled hash when necessary, and never treat a key as a secure storage location.
Preventing unnecessary cache growth
Adding every possible parameter improves isolation but can also create a new entry for every tiny variation. First identify which fields actually change the response. Correlation IDs, request IDs, client IP addresses, and other diagnostic values should not be included if they do not affect the returned data.
Limit page sizes and validate filter lengths. An endpoint that allows users to generate unlimited unique search expressions can produce significant key churn even when expiration is short. Cache popular, reusable queries and consider stricter limits or no caching for extremely rare variations.
Common mistakes
- Omitting the resource type: Generic keys such as
42can collide across data types. - Ignoring case sensitivity: Redis treats
Booksandbooksas different keys. - Leaving out a filter: Using only a page number allows unrelated lists to share a value.
- Omitting user context: Personalized responses must not be stored under a public key.
- Generating keys manually everywhere: Inconsistent formats make invalidation incomplete.
- Using very long keys: Canonicalization and hashing are preferable to embedding an entire query or JSON document.
- Skipping key versions: DTO and serialization changes can make old payloads incompatible with new code.
Practice exercise
Implement a centralized ICacheKeyFactory method for a product search endpoint with these inputs: tenantId, category, page, pageSize, sort, minPrice, and maxPrice.
- Prefix the key with the application name, environment, and version.
- Normalize category and sort values.
- Clamp the page number to at least 1 and page size between 1 and 100.
- Verify that tenant identity is part of the key.
- Make equivalent textual forms produce the same key.
- Use xUnit tests to prove that different tenants, categories, and pages generate different keys.
- Create a failing design intentionally by removing category from the key, then demonstrate that two different requests share the same cache entry.
Conclusion
A cache key is not merely a string. It is part of the application’s contract for data isolation, invalidation, observability, and maintenance. Well-designed keys identify the resource and scope, include every parameter that changes the result, and normalize equivalent inputs so that the cache does not fill with duplicates.
In this lesson, we created a centralized key factory for products, categories, lists, pagination, filters, users, and tenants. The next step is to connect these keys to data changes and invalidation policies. The more consistent the key format is, the more predictable cache invalidation, monitoring, and performance measurement become.