What are common cache invalidation strategies for ensuring cached data doesn't become stale, and why is invalidation considered a genuinely hard problem?
Short answer
Strategies include TTL-based expiration (simplest, but potential staleness until expiry), explicit invalidation (removing/updating a cache entry immediately when underlying data changes, requiring every mutation code path to remember to invalidate correctly), and tag-based bulk…
Advertisement
AModel answer
Strategies include TTL-based expiration (simplest, but potential staleness until expiry), explicit invalidation (removing/updating a cache entry immediately when underlying data changes, requiring every mutation code path to remember to invalidate correctly), and tag-based bulk invalidation (Output Caching's EvictByTagAsync or a custom tag-tracking scheme). It's hard because every place data can change must remember to invalidate the right entries, and distributed deployments make coordinating invalidation across multiple cache instances even trickier.
public async Task UpdateProductAsync(Product product) {
await _repository.UpdateAsync(product);
await _cache.RemoveAsync($"product-{product.Id}"); // must remember this on EVERY write path!
await _outputCacheStore.EvictByTagAsync("products", default);
}Real-world example
A bug where stale product prices were shown for hours was traced to a bulk-update script that updated the database directly, bypassing the normal service method that would have invalidated the corresponding cache entries.
Likely follow-ups
- Why is 'there are only two hard things in computer science: cache invalidation and naming things' such a common joke?
- How do cache tags simplify bulk invalidation compared to tracking individual keys?
Related topics