Caching Strategies
Overview
Caching reduces latency and backend load by storing frequently accessed data closer to application consumers.
Common Cache Patterns
- Cache-aside: application loads and writes cache explicitly
- Read-through: cache fetches from source on miss
- Write-through: writes update cache and source together
- Write-behind: cache writes asynchronously to source
sequenceDiagram
participant App
participant Cache
participant Database
App->>Cache: GET product:42
alt Cache hit
Cache-->>App: Return cached value
else Cache miss
App->>Database: Query product 42
Database-->>App: Return row
App->>Cache: SET product:42
end
Practical Example
var key = $"product:{productId}";
var cached = await redis.StringGetAsync(key);
if (cached.IsNullOrEmpty)
{
var product = await repository.GetProductAsync(productId);
await redis.StringSetAsync(key, JsonSerializer.Serialize(product), TimeSpan.FromMinutes(5));
return product;
}
return JsonSerializer.Deserialize<Product>(cached!)!;
Operational Guidance
- Define TTL based on data freshness requirements
- Monitor hit ratio and eviction rates
- Use key namespacing to avoid collisions
- Invalidate cache after critical data updates
Common Pitfalls
- Unbounded key growth
- Stale data due to weak invalidation
- Caching sensitive data without encryption controls
Key Takeaways
- Cache pattern choice depends on consistency needs.
- TTL and invalidation strategy are central design decisions.
- Metrics are required to validate cache effectiveness.