In-memory caching
Caching keeps the result of slow work, such as a database query or an API call, in memory so later requests can reuse it. This lesson shows IMemoryCache, expiration options and the cache-aside pattern.
- StartA request needs dataFor example the list of product categories
- Step 2Check the cacheIMemoryCache is looked up with a key
- Step 3Found it?Return the cached copy straight away
- Step 4Not foundLoad the data from the database
- Step 5Store itPut it in the cache with an expiry time
- EndReturn itThe next requests get the fast cached copy
The idea in plain words
If many users ask for the same data and it changes rarely, loading it from the database on every request is wasted work. A cache stores a copy in the server's memory for a while. The first request pays the cost; later requests are almost free.
IMemoryCache stores data in the memory of one server process. It is shared by all users (unlike session), so never cache data that belongs to one user under a shared key. If you run several servers, consider IDistributedCache with Redis, or HybridCache, so every server works from the same cache.
Example
GetOrCreateAsync implements cache-aside in one call. The factory runs only when the key is missing or expired.
// Program.cs
builder.Services.AddMemoryCache();
public class CategoriesController : Controller
{
private readonly IMemoryCache _cache;
private readonly ShopContext _db;
public CategoriesController(IMemoryCache cache, ShopContext db)
{
_cache = cache;
_db = db;
}
public async Task<IActionResult> Index()
{
var categories = await _cache.GetOrCreateAsync("categories", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
entry.SlidingExpiration = TimeSpan.FromMinutes(2);
return await _db.Categories.AsNoTracking().ToListAsync();
});
return View(categories);
}
}Expiration options
- Absolute expiration: the entry is removed after a fixed time, no matter how often it is used.
- Sliding expiration: the entry is removed if it is not used for a while; combine it with absolute expiration so stale data cannot live forever.
- Remove(key): clear an entry yourself when the data changes, for example after an admin edits a category.
Common mistakes
- Caching per-user data under a shared key, so one user sees another user's data.
- Caching without any expiration, so changes never show up.
- Assuming the cache is always there; entries can be evicted at any time under memory pressure.
Interview question
What is the difference between IMemoryCache and IDistributedCache?
IMemoryCache stores .NET objects in the memory of a single app instance; it is fast but each server has its own copy and the data is lost on restart. IDistributedCache stores byte arrays in an external store such as Redis or SQL Server shared by all instances, so data is consistent across servers and survives app restarts, at the cost of network calls and serialization.
Want the full details? Read the official Microsoft documentation for this topic.