Cache Patterns and Expiration
Apply cache-aside and set expirations.
Caching Patterns
How you read and write a cache is a pattern. The most common in web apps is cache-aside, where your code manages the cache around the data source.
The Cache-Aside Pattern
Cache-aside (lazy loading) works in three steps: check the cache; on a miss, load from the source and populate the cache; return the value. The cache fills on demand.
async Task<string> GetForecastAsync(string city)
{
string key = $"forecast:{city}";
string cached = await _cache.GetStringAsync(key);
if (cached is not null) return cached;
string fresh = await _api.LoadForecastAsync(city);
await _cache.SetStringAsync(key, fresh);
return fresh;
}All lessons in this course
- IDistributedCache Abstraction
- Connecting to Redis
- Cache Patterns and Expiration
- Caching Serialized Objects