Recipe 3.1 · C#
Cache-Aside with GetOrCreateAsync
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
A list of countries, tax rates or product categories is read on every request and changes a few times a year. Reading it from the database each time is wasteful. The usual hand-written cache around it has race conditions and never expires.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: static dictionary, check-then-read, no expiry.
public static class CountryCache
{
private static Hashtable _cache = new Hashtable();
public static DataTable GetCountries()
{
if (_cache["Countries"] == null)
{
_cache["Countries"] = CountryData.LoadAll();
}
return (DataTable)_cache["Countries"];
}
}
The data never expires, so a new country requires an application restart. Two threads that miss at the same moment both load. Hashtable tolerates one writer with many readers, but a Dictionary swapped in later during a "modernization" would corrupt itself under concurrent writes. And the cast at the end will break the first time someone stores the wrong type under that key.
The improved recipe
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
namespace ImproveCode.Caching;
public sealed record Country(string Code, string Name);
public interface ICountryRepository
{
Task<IReadOnlyList<Country>> GetAllAsync(CancellationToken ct);
}
public sealed class CountryService(
IMemoryCache cache, ICountryRepository repository)
{
private const string CacheKey = "countries:all";
public async Task<IReadOnlyList<Country>> GetAllAsync(
CancellationToken ct = default)
{
IReadOnlyList<Country>? countries =
await cache.GetOrCreateAsync(CacheKey, async entry =>
{
entry.AbsoluteExpirationRelativeToNow =
TimeSpan.FromHours(6);
return await repository.GetAllAsync(ct);
});
return countries ?? [];
}
}
How it works
Cache-aside means the application owns the logic: look in the cache, and on a miss, load from the source and put the result in the cache. GetOrCreateAsync packages that into one call. It returns the cached value if there is one. Otherwise it creates a cache entry, runs your factory, stores the result and returns it.
The factory receives the ICacheEntry, which is where you set the entry's lifetime. Here the list lives for six hours, then the next request reloads it. Six hours is a business decision, not a technical one: ask how stale this data is allowed to be, and write that number down in the code.
The cached type is an immutable record in a read-only list. That matters more than it looks. IMemoryCache stores a reference, not a copy, so every caller gets the same object. If the cached value were a List<Country> or a DataTable, one caller could add or remove a row and change the data for everyone else. Cache immutable things.
Register the cache once with builder.Services.AddMemoryCache(); and the service as a singleton or scoped service, depending on its other dependencies.
Variations and pitfalls
GetOrCreateAsyncreturnsTItem?. The factory might returnnull, and the cache stores it. The?? []turns that into an empty list so callers never seenull.- The factory is not locked. Two requests that miss at the same moment both run the factory, and the second result wins. For cheap loads that is fine. For expensive ones, see Recipe 3.4.
- Capturing the token. The factory uses the token of the request that happened to miss. If that request is cancelled, the load fails, nothing is cached, and the next request tries again. That is acceptable for small loads. The single-flight cache in Recipe 3.4 shows how to decouple the shared load from any one caller.
- Do not cache per-user data under a shared key. A key like
"orders"that holds the current user's orders will show them to the next user. Put the user or tenant ID in the key.
On .NET Framework
Microsoft.Extensions.Caching.Memory supports .NET Framework 4.6.2 and later through .NET Standard 2.0, so the same code works there. System.Runtime.Caching.MemoryCache is the older built-in option; it works, but its API is string-keyed and synchronous.