Introduction
When an ASP.NET Core API reads the same categories, brands, or product summaries from the database for every request, it performs unnecessary work. For data that is requested frequently and changes infrequently, in-process caching can reduce database queries, lower response times, and allow the same server to handle more requests.
In this lesson, we will use IMemoryCache to store category and product data in the memory of the running ASP.NET Core process. We will use GetOrCreateAsync to load data asynchronously on a cache miss and apply both sliding and absolute expiration strategies. We will also examine cache stampede, stale data, large cache entries, and consistency concerns in multi-server deployments.
The examples build on projection, AsNoTracking, and pagination techniques from earlier lessons. Caching should not hide an inefficient query. It should reduce the cost of a query that is already designed correctly and is executed repeatedly.
1. How in-process caching works
IMemoryCache stores cache entries in the memory of the process running the ASP.NET Core application. Requests handled by that process can share the cached value. However, the cache is lost when the application restarts. In a multi-server deployment, each server has its own memory, so a value created on one server is not automatically available on another server.
A typical cache flow looks like this:
- Create a deterministic cache key for the requested data.
- Look for that key in the cache.
- If the value exists, return it without querying the database. This is a cache hit.
- If it does not exist, load the value from the source system. This is a cache miss.
- Store the result with an appropriate expiration policy.
The cache is not the authoritative data source. The database or another service must remain available as a fallback. The application should continue to work when an entry expires, the cache is empty, or the process has restarted.
2. Registering IMemoryCache
Many ASP.NET Core applications make memory caching available through framework services such as MVC, controllers, or Razor Pages. An explicit registration makes the dependency clear:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache();
builder.Services.AddControllers();
builder.Services.AddScoped<ICatalogService, CatalogService>();
var app = builder.Build();
app.MapControllers();
app.Run();Keeping cache access in an application or domain service is usually better than placing database and cache logic directly in a controller. The cache policy becomes centralized, and the service can be tested independently.
3. Designing cache keys
A cache key should clearly identify the value and produce the same string for the same logical request. For example, all categories can use catalog:categories:v1, while one product can use catalog:product:42:v1.
Follow these guidelines:
- Start keys with a namespace such as
catalog:orproducts:. - Include all parameters that affect the result. For paged queries, page number, page size, and filters must be represented.
- Do not use unlimited raw external input as a cache key.
- Consider adding a version suffix such as
v2when the DTO or cache shape changes. - Use one consistent key format across services.
For example, products:page:1:size:20:category:5 and products:category=5&page=1 may describe the same result but create two separate entries. Inconsistent key generation lowers the cache hit rate.
4. Caching categories with GetOrCreateAsync
The following example loads a category list with projection and AsNoTracking. Selecting only the required fields prevents unnecessary entity graphs from being stored in the cache.
public sealed record CategoryListItem(int Id, string Name);
public interface ICatalogService
{
Task<IReadOnlyList<CategoryListItem>> GetCategoriesAsync(
CancellationToken cancellationToken);
}
public sealed class CatalogService : ICatalogService
{
private const string CategoriesKey = "catalog:categories:v1";
private readonly CatalogDbContext _db;
private readonly IMemoryCache _cache;
public CatalogService(CatalogDbContext db, IMemoryCache cache)
{
_db = db;
_cache = cache;
}
public async Task<IReadOnlyList<CategoryListItem>> GetCategoriesAsync(
CancellationToken cancellationToken)
{
return await _cache.GetOrCreateAsync(
CategoriesKey,
async entry =>
{
entry.SlidingExpiration = TimeSpan.FromMinutes(2);
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15);
return await _db.Categories
.AsNoTracking()
.OrderBy(x => x.Name)
.Select(x => new CategoryListItem(x.Id, x.Name))
.ToListAsync(cancellationToken);
}) ?? Array.Empty<CategoryListItem>();
}
}GetOrCreateAsync returns the value when the key exists. When the key is absent, it executes the factory and stores the result. Because a cache factory can produce a nullable value, the example uses an empty collection as a safe fallback. Whether missing values should be cached should be an explicit application decision.
5. Sliding and absolute expiration
Sliding expiration removes an entry after it has not been accessed for a specified period. With a two-minute sliding expiration, an access refreshes the inactivity window. A frequently used entry may therefore remain in the cache.
Absolute expiration defines the maximum amount of time an entry can remain cached after it is created. Even if category data is requested every minute, a fifteen-minute absolute expiration forces it to be refreshed eventually.
Using only sliding expiration can be risky. A heavily used entry may theoretically stay in memory forever. Combining both policies is usually safer:
| Strategy | Behavior | Suitable use |
|---|---|---|
| Sliding expiration | Removes data that is not accessed for a period | Data that should remain while actively used |
| Absolute expiration | Refreshes data after a fixed maximum lifetime | Controlling the upper bound for stale data |
| Both together | Controls inactivity and maximum lifetime | Most catalog and configuration data |
6. Caching product details by key
For product details, the key must contain the product identifier. Otherwise, one product's result could be returned for another product. The application must also decide how to handle products that do not exist.
public sealed record ProductDetailsDto(
int Id,
string Name,
decimal Price,
string CategoryName);
public async Task<ProductDetailsDto?> GetProductAsync(
int productId,
CancellationToken cancellationToken)
{
var key = $"catalog:product:{productId}:v1";
return await _cache.GetOrCreateAsync(
key,
async entry =>
{
entry.SlidingExpiration = TimeSpan.FromMinutes(1);
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
return await _db.Products
.AsNoTracking()
.Where(x => x.Id == productId && x.IsActive)
.Select(x => new ProductDetailsDto(
x.Id,
x.Name,
x.Price,
x.Category.Name))
.SingleOrDefaultAsync(cancellationToken);
});
}Validate productId before building the key. Negative or meaningless identifiers can create unnecessary entries. User-specific or authorization-dependent data must not be placed in a shared cache unless the user and authorization context are part of the key and the security implications are understood.
7. Stale data and cache invalidation
Cached data can be older than the data in the database. If a category is renamed, the catalog:categories:v1 entry may continue returning the old name until it expires. If that delay is acceptable, expiration may be enough. If faster consistency is required, remove the related key after the write operation.
public async Task UpdateCategoryAsync(
int id,
string name,
CancellationToken cancellationToken)
{
var category = await _db.Categories
.SingleAsync(x => x.Id == id, cancellationToken);
category.Name = name;
await _db.SaveChangesAsync(cancellationToken);
_cache.Remove("catalog:categories:v1");
_cache.Remove($"catalog:category:{id}:v1");
}If the update also affects product details, filtered product lists, or paged results, removing one key may not be sufficient. A clear key naming convention, grouped invalidation strategy, or shorter absolute expiration may be needed.
8. Understanding cache stampede
A cache stampede occurs when a popular key expires and many concurrent requests attempt to rebuild it at the same time. For example, when the category entry expires, one hundred requests arriving within the same moment may all send a query to the database.
GetOrCreateAsync is convenient, but expensive factories should not automatically be assumed to collapse every concurrent call into one database operation. For critical and costly resources, consider these approaches:
- Use a per-key
SemaphoreSlimor keyed lock so only one request refreshes a value. - Refresh important entries in advance with a background service.
- Add small randomized variations to expiration times to avoid synchronized expiration.
- Use an appropriate two-level cache solution that provides stampede protection in multi-server scenarios.
When implementing locks, ensure that the lock is always released after an exception, does not remain held indefinitely, and does not create an unlimited number of lock objects for unbounded keys.
9. Memory limits and common mistakes
- Caching unlimited data: Caching every search result or the complete product catalog can consume memory quickly.
- Storing entity graphs: Prefer compact DTOs over large entities with navigation properties.
- Skipping expiration: Define at least a lifetime or invalidation policy for every entry.
- Sharing user-specific data: Do not use a common key without accounting for user and authorization context.
- Treating cache as truth: Expiration, eviction, process restarts, and cache misses are normal conditions.
- Ignoring multiple servers: IMemoryCache is local to each application instance. Use distributed caching or a suitable two-level approach when shared consistency is required.
- Not measuring hit rate: Do not assume caching helps until query counts, response times, and resource usage confirm it.
10. Measuring the performance effect
Measure the same scenario before and after caching. Send 100 or 1000 requests to the category endpoint and compare average latency, p95 latency, total SQL query count, and database CPU usage.
Application telemetry can record cache hits, cache misses, loading duration, and result counts. However, writing detailed logs for every request can introduce its own overhead. Production systems often benefit more from metrics, tracing, and sampled logging.
A practical test plan is:
- Clear the cache and measure the first request.
- Send the same request repeatedly and measure warm-cache behavior.
- Measure the first request after expiration.
- Send concurrent requests and observe the behavior during a cache miss.
- Update source data and verify that invalidation returns fresh data.
Practice exercise
Add or update a GET /api/categories endpoint in the catalog API.
- Register
IMemoryCache. - Implement
GetCategoriesAsyncwith a projection. - Use the
catalog:categories:v1key. - Apply two minutes of sliding expiration and ten minutes of absolute expiration.
- Remove the related key after a category update.
- Measure SQL query count and p95 latency before and after caching.
- Send at least 20 concurrent requests during a cold-cache test and inspect how many database queries are generated.
Conclusion
IMemoryCache provides a low-latency cache layer for data that is read frequently and changed relatively infrequently. A reliable implementation requires more than calling GetOrCreateAsync. Key design, projection, expiration policies, invalidation, memory limits, and measurement must be considered together.
MemoryCache is a strong starting point for single-server applications or scenarios where per-instance cache consistency is acceptable. As the application becomes multi-server, cache loss after restarts becomes important, or stampede protection is required, distributed and two-level caching options should be evaluated. The next step is to compare this approach with distributed caching and Redis so that the cache architecture matches the application's consistency and scalability requirements.