Caching: cache-aside, TTL and invalidation
Read through the cache, write to the database and delete the cached copy. Plus the two classic failure modes: stale data and the stampede.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
In cache-aside the application owns the cache: on a read it checks the cache, falls back to the database on a miss, and fills the cache. On a write it updates the database and deletes the cached entry, so the next read loads the fresh value. A TTL limits how stale a value can ever get.
Code
async Task<User> GetUser(int id)
{
var cached = await _cache.GetAsync<User>($"user:{id}");
if (cached != null) return cached;
var user = await _db.Users.FindAsync(id);
await _cache.SetAsync($"user:{id}", user, TimeSpan.FromMinutes(10));
return user;
}
async Task UpdateUser(User u)
{
await _db.SaveAsync(u);
await _cache.RemoveAsync($"user:{u.Id}");
}Tips
- Delete on write rather than update: two concurrent updates writing the cache can leave the older value behind.
- Cache stampede: a hot key expires and thousands of requests hit the database at once. Fix it with a per-key lock, request coalescing, or random jitter on TTLs.
- What not to cache: data that must be exactly current, like account balances at payment time.
In the .NET library
.NET 9 added HybridCache, which combines an in-memory and a distributed cache and protects against stampedes by letting only one caller load a missing key.