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.

Time O(1)Space O(k) cached keysCode C#
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

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.