Cache Patterns and Expiration
Apply cache-aside and set expirations.
Cache Patterns and Expiration is a free C# Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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;
}Why Expiration Is Essential
Cached data can go stale. Expiration automatically evicts entries after a period so the next read reloads fresh data, balancing performance against staleness.
Absolute Expiration
Absolute expiration evicts an entry at a fixed point in time regardless of usage. Use it when data is valid only for a known window.
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
};Sliding Expiration
Sliding expiration resets the timer on each access. An entry survives as long as it is used regularly but is evicted after a period of inactivity. Great for session-like data.
var options = new DistributedCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(5)
};Combining Both
You can set both: sliding keeps frequently used data alive, while an absolute cap guarantees the entry never lives longer than a maximum, forcing eventual refresh.
var options = new DistributedCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(5),
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
};Applying Options On Set
Pass the options as the third argument to SetStringAsync (or SetAsync) so the entry carries its own expiration policy.
await _cache.SetStringAsync(key, fresh, options);Write-Through And Invalidation
When the source data changes, evict or update the cache so reads do not serve stale values. Cache-aside typically pairs writes with a RemoveAsync on the affected key.
await _repository.UpdateForecastAsync(city, value);
await _cache.RemoveAsync($"forecast:{city}");Avoiding Cache Stampede
If a popular key expires, many requests may reload it at once (a stampede). Mitigate with short locks, slightly randomized expirations, or background refresh so only one request rebuilds the entry.
Choosing Expiration Values
Pick durations from how often the data changes and how much staleness is acceptable. Reference data tolerates long TTLs; rapidly changing data needs short ones or event-based invalidation.
The Cost Of A Miss
Every miss costs a source load, so design keys and TTLs to maximize hit rate. Monitor hit and miss ratios to tune your cache over time.
Quick Check
Test cache patterns and expiration.
Recap
The cache-aside pattern checks the cache, loads on a miss, and populates it. Absolute expiration evicts at a fixed time; sliding expiration resets on access; combine them with DistributedCacheEntryOptions. Invalidate on writes with RemoveAsync, guard against stampedes, and tune TTLs and keys from access patterns and acceptable staleness.
Frequently asked questions
Is the “Cache Patterns and Expiration” lesson free?
Yes — the full text of “Cache Patterns and Expiration” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Cache Patterns and Expiration”?
Apply cache-aside and set expirations. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Cache Patterns and Expiration” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- IDistributedCache Abstraction
- Connecting to Redis
- Cache Patterns and Expiration
- Caching Serialized Objects