LESSON 8 OF 12

8. Cache Invalidation and Data Consistency

Learn how to invalidate cache keys during product changes, test stale data scenarios, and choose an appropriate consistency strategy between the database and cache.

35 dk 81

Introduction

Caching accelerates read operations, but if the application does not define how cached data will be updated or removed when the source changes, it can start returning old information. This problem is known as stale data. In product catalogs, prices, inventory, and campaign data, which are read frequently but change periodically, invalidation is just as important as performance.

In this lesson, we will connect the Redis-based cache service from the previous lessons to product operations. We will identify the keys affected by product creation, update, and deletion; compare direct deletion, pattern-based deletion, versioned keys, and write-through approaches; and observe stale data through a controlled test.

Why is cache invalidation necessary?

In the cache-aside model, the application checks the cache first. If the value is missing, it reads from the database and stores the result in the cache. A write operation, however, treats the database and cache as separate components. The following sequence can therefore produce an incorrect result:

  1. A client reads product details and the result is stored in Redis.
  2. Another operation updates the product price in the database.
  3. The old price remains in Redis.
  4. A new GET request returns the old price without accessing the database.

In this situation, the database is correct but the value exposed by the application is wrong. Expiration may reduce the problem after some time, but waiting for a TTL to expire is not sufficient for critical data such as prices or inventory. After a successful write, the affected cache entry should be removed or replaced with the new value.

Define the key scope

Before implementing invalidation, we need to know which cache entries a product change can affect. Assume that our product service uses the following keys:

product:{id}:detail
products:list:page:{page}:size:{size}:category:{categoryId}
products:category:{categoryId}
products:featured

An update does not necessarily affect only product:{id}:detail. The product may also appear in a category list, a featured list, or another filtered result. An invalidation plan should answer these questions:

  • What is the detail key for the changed product?
  • Which list and category caches contain the product?
  • Does the change affect only display data, or critical fields such as price and inventory?
  • Must the cache be cleared immediately, or is a short period of old data acceptable?

Approach 1: Direct key deletion

The simplest and, for many applications, the most predictable method is to delete known keys directly. IDistributedCache.RemoveAsync removes one specific key. Key construction should be centralized in a dedicated class.

public static class ProductCacheKeys
{
    public static string Detail(int productId) =>
        $"product:{productId}:detail";

    public static string Category(int categoryId) =>
        $"products:category:{categoryId}";

    public static string Featured => "products:featured";
}

The product update service can invalidate the cache after the database operation succeeds:

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

    await _cache.RemoveAsync(
        ProductCacheKeys.Detail(product.Id),
        cancellationToken);

    await _cache.RemoveAsync(
        ProductCacheKeys.Category(product.CategoryId),
        cancellationToken);

    await _cache.RemoveAsync(
        ProductCacheKeys.Featured,
        cancellationToken);
}

The important point is that the cache is not removed before the database update. If the cache is cleared first and the database update fails, the next read may repopulate the cache with an unexpected value. In a typical cache-aside flow, the safer order is to write to the database and, only after success, remove the affected cache entries.

Approach 2: Pattern-based deletion

Sometimes it is not practical to know every affected key individually. For example, product lists may be generated from combinations of page, category, brand, and sorting options. A single product update can then affect many list keys. In that case, scanning keys under a prefix such as product-list: may be considered.

For Redis, SCAN is generally preferred over KEYS for this purpose. KEYS can block the server for a long time on a large keyspace. SCAN uses cursor-based, incremental iteration; however, a key can be returned more than once and results should not be expected to arrive in one call.

public async Task RemoveByPatternAsync(string pattern)
{
    var server = _redisConnection.GetServer(
        _redisConnection.GetEndPoints()[0]);

    var keys = server.Keys(
        database: 0,
        pattern: pattern,
        pageSize: 500);

    foreach (var key in keys)
    {
        await _database.KeyDeleteAsync(key);
    }
}

This code can be suitable for administrative or low-volume maintenance operations. However, scanning the entire Redis keyspace on every product update can be expensive in a high-traffic system. Redis Cluster can also make the operation more complex when keys are distributed across slots.

Instead of pattern deletion, consider maintaining an index of product-to-list relationships, explicitly tracking affected keys in the application, or keeping list caches for a shorter period. If pattern deletion is used, keep prefixes narrow, measure the operation, and avoid unnecessary scans in the critical path of a user request.

Approach 3: Versioned keys

With versioned keys, a version value is added to part of the cache key:

products:list:v42:page:1:size:20
products:list:v42:page:2:size:20

When a change affects the list, the application increments the version instead of deleting every old key. The application then starts reading v43 keys. Old entries expire naturally when their TTL ends.

This approach reduces the need to delete many keys individually. However, the version must be stored and updated reliably. If the version is also stored in Redis, every read introduces another operation. Since old keys are not deleted immediately, temporary memory usage also increases. Direct deletion can be used for critical product details, while versioned keys can be useful for lists with many combinations.

Approach 4: Write-through

With write-through caching, the application updates the cache as part of the write flow. After writing the product to the database, the new product DTO can be serialized and stored under the detail key:

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

    var dto = ProductDto.FromEntity(product);

    await _cache.SetAsync(
        ProductCacheKeys.Detail(product.Id),
        dto,
        new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
        },
        cancellationToken);

    await _cache.RemoveAsync(
        ProductCacheKeys.Category(product.CategoryId),
        cancellationToken);
}

Write-through ensures that a detail read can immediately observe the new value. However, if writing to the cache fails, the database and cache can still diverge. The cache operation should not be assumed to be truly atomic with the database transaction. Treat the cache as an auxiliary layer, not as the system of record; the application must be able to continue from the database when the cache is unavailable.

Strategy for product creation, update, and deletion

A simple product service can use the following strategy:

OperationDatabaseCache operation
Product creationCreate the new record.Remove the relevant list and category keys.
Product updateUpdate the record.Remove or replace the detail key; remove list keys.
Product deletionDelete or deactivate the record.Remove detail, category, and relevant list keys.

A category change is a special case. If a product moves from one category to another, both the old category key and the new category key must be invalidated. If the update object does not contain the old category, that information should be read before the database update or carried in a domain event.

Testing a stale data scenario

Testing only a successful GET request is not enough to verify consistency. First populate the cache, then change the database without invalidation and observe stale data:

  1. Call GET /api/products/10 so the current product is stored in the cache.
  2. Change the price directly in the database with SQL.
  3. Send the same GET request again.
  4. Verify that the old price is returned while the cache entry is still valid.
  5. Make the same change through the product update endpoint.
  6. Send the GET request again and confirm that the new value is loaded from the database and written to the cache.

Logging cache hits and misses alongside the response value is useful during testing. You should be able to see that product:10:detail was removed, the next request accessed the database, and the new value was written to Redis.

Common mistakes

  • Deleting the cache before the database: A failed database operation can cause an unnecessary cache miss.
  • Deleting only the detail key: List caches may continue to show the old product.
  • Scanning a broad pattern on every write: This can increase Redis latency and CPU usage.
  • Treating a cache write failure as a database write failure: The cache is an auxiliary layer; data correctness belongs to the database.
  • Using different invalidation behavior on different application servers: A shared distributed cache cannot compensate for inconsistent application logic.
  • Using expiration instead of invalidation: TTL is a safety net for forgotten entries, not a replacement for intentional invalidation after writes.

Short practice exercise

Add UpdateProductAsync and DeleteProductAsync methods to the product service. In each method, complete the repository operation first, then remove the product detail key and the relevant category list key. If the product changes category, also clear the old and new category keys. As a test, read the same product through two API requests, populate the cache with the first request, update the product, and verify that the second request returns the current value.

Conclusion

Cache invalidation is not a detail added after the cache architecture; it is a fundamental part of data access design. Direct key deletion is simple and predictable. Pattern-based deletion is flexible but must be used carefully on a large keyspace. Versioned keys reduce the cost of bulk invalidation, while allowing old entries to remain temporarily. Write-through can provide fresher detail results for selected scenarios, but database and cache operations should not be assumed to share one transaction.

For our product application, the baseline strategy is to invalidate known detail and list keys after a successful database write. TTL should be used as a second safety layer for forgotten or missed entries. In the next lesson, we will examine cache stampede, concurrent misses, and how to control multiple requests that try to rebuild the same value at the same time.

Sources