Performance is an important consideration when developing modern web applications. As an application grows, the number of users, API requests, database queries, and background operations increases. Without proper optimization, these operations can lead to slower response times, increased database load, and poor user experience.
One of the simplest and most effective ways to improve application performance is caching.
Caching allows an application to temporarily store frequently accessed data so it can be retrieved quickly without repeatedly executing expensive operations such as database queries, API requests, or complex calculations.
ASP.NET Core provides several caching mechanisms, including IMemoryCache, distributed caching, and integration with Redis.
In this article, we'll explore how caching works, how to implement it in ASP.NET Core, and when to use each caching approach.
1. What Is Caching?
Caching is the process of storing frequently accessed data in a temporary storage location for faster retrieval.
For example, imagine an e-commerce application where thousands of users access the product categories page.
Without caching, every request might execute a database query:
var categories = await _context.Categories
.Where(x => x.IsActive)
.ToListAsync();
If this query executes thousands of times per day, it creates unnecessary database load.
With caching, the application can execute the query once, store the result, and reuse it for subsequent requests.
First Request
|
v
Check Cache
|
v
Cache Miss
|
v
Query Database
|
v
Store Result in Cache
|
v
Return Response
Subsequent Requests
|
v
Check Cache
|
v
Cache Hit
|
v
Return Cached Result
The primary benefits of caching include:
- Faster response times.
- Reduced database load.
- Lower infrastructure costs.
- Improved scalability.
- Better performance during traffic spikes.
- Reduced dependency on external services for frequently requested data.
2. Types of Caching in ASP.NET Core
ASP.NET Core supports different caching approaches depending on the application architecture.
In-Memory Caching
Data is stored directly in the memory of the application server.
ASP.NET Core provides the IMemoryCache interface for implementing in-memory caching.
It is ideal for:
- Small applications.
- Single-server deployments.
- Frequently accessed reference data.
- Temporary application-level data.
Distributed Caching
Data is stored in a separate caching system that can be accessed by multiple application instances.
Common distributed caching technologies include:
- Redis.
- SQL Server distributed cache.
- Other distributed storage implementations.
Distributed caching is useful when an application runs on multiple servers or containers.
Hybrid Caching
Hybrid caching combines local in-memory caching with a distributed cache.
The application can retrieve frequently accessed data from local memory first and use the distributed cache as a secondary storage layer.
This reduces network calls while supporting shared cache storage.
3. Implementing IMemoryCache in ASP.NET Core
IMemoryCache is one of the easiest caching mechanisms to implement in ASP.NET Core.
It stores data in the memory of the application process.
Step 1: Register Memory Cache
In Program.cs:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddMemoryCache(); builder.Services.AddControllers(); builder.Services.AddScoped<ProductService>(); var app = builder.Build(); app.MapControllers(); app.Run();
The following registration enables memory caching:
builder.Services.AddMemoryCache();
ASP.NET Core can now inject IMemoryCache into your services and controllers.
Step 2: Create a Product Service
Let's create a service that retrieves products from a database and caches the results.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
public class ProductService
{
private readonly ApplicationDbContext _context;
private readonly IMemoryCache _cache;
public ProductService(
ApplicationDbContext context,
IMemoryCache cache)
{
_context = context;
_cache = cache;
}
public async Task<List<Product>> GetProductsAsync()
{
const string cacheKey = "products_active";
if (_cache.TryGetValue(cacheKey, out List<Product>? products))
{
return products!;
}
products = await _context.Products
.Where(x => x.IsActive)
.ToListAsync();
var cacheOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(10))
.SetSlidingExpiration(TimeSpan.FromMinutes(2));
_cache.Set(cacheKey, products, cacheOptions);
return products;
}
}
How does this work?
First, we define a cache key:
const string cacheKey = "products_active";
A cache key uniquely identifies the cached data.
Next, we check whether the data already exists:
if (_cache.TryGetValue(cacheKey, out List<Product>? products))
{
return products!;
}
If the data is available, we return it immediately without querying the database.
If the cache doesn't contain the data, we execute the database query:
products = await _context.Products
.Where(x => x.IsActive)
.ToListAsync();
Finally, we store the result:
_cache.Set(cacheKey, products, cacheOptions);
The next request can retrieve the cached data instead of executing the database query again.
4. Understanding Cache Expiration
Cached data shouldn't remain in memory forever.
ASP.NET Core allows you to configure different expiration strategies.
Absolute Expiration
Absolute expiration defines a fixed maximum time for which an item can remain cached.
_cache.Set(
"products",
products,
TimeSpan.FromMinutes(10));
The cached item expires after ten minutes, regardless of how frequently it is accessed.
This is useful for data that should periodically refresh.
Sliding Expiration
Sliding expiration resets the expiration timer whenever the cached item is accessed.
var options = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(5));
_cache.Set("products", products, options);
If the item is accessed within five minutes, its expiration timer resets.
However, continuously accessed items can remain cached for a long time. For this reason, sliding expiration is often combined with absolute expiration.
Combining Both
var options = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(5))
.SetAbsoluteExpiration(TimeSpan.FromMinutes(30));
_cache.Set("products", products, options);
In this example:
- If the item is not accessed for five minutes, it expires.
- Even if it is accessed continuously, it cannot remain cached beyond thirty minutes.
5. Cache Invalidation: Updating Cached Data
One of the most important challenges in caching is keeping cached data synchronized with the actual database.
Suppose a product is cached, and an administrator updates its price.
If the cache isn't invalidated, users may continue seeing the old price.
A simple solution is to remove the cache entry whenever the data changes.
public async Task UpdateProductAsync(Product product)
{
_context.Products.Update(product);
await _context.SaveChangesAsync();
_cache.Remove("products_active");
}
After the cache is removed, the next request will execute the database query again and store the updated result.
Why Cache Invalidation Matters
Caching improves performance, but stale data can create business problems.
For example:
- Updated product prices may not appear immediately.
- Changes to customer information may not be reflected.
- Inventory quantities may become inaccurate.
- Updated permissions may not take effect.
- Reports may display outdated information.
Cache invalidation should therefore be part of the application's data update strategy.
6. Caching Individual Records
Instead of caching an entire list, we can cache individual records.
For example, a product details page may receive repeated requests for the same product.
public async Task<Product?> GetProductByIdAsync(int id)
{
var cacheKey = $"product_{id}";
if (_cache.TryGetValue(cacheKey, out Product? product))
{
return product;
}
product = await _context.Products
.FirstOrDefaultAsync(x => x.Id == id);
if (product != null)
{
_cache.Set(
cacheKey,
product,
TimeSpan.FromMinutes(10));
}
return product;
}
The cache key contains the product ID:
var cacheKey = $"product_{id}";
This allows each product to have its own cache entry.
When a product is updated, we can invalidate both its individual cache and the product list cache.
_cache.Remove($"product_{product.Id}");
_cache.Remove("products_active");
This approach provides more flexibility than caching every product under one key.
7. Distributed Caching in ASP.NET Core
In-memory caching works well for applications running on a single server.
However, consider an application deployed across multiple servers behind a load balancer.
Load Balancer
|
-----------------
| |
v v
App Server 1 App Server 2
| |
Local Cache Local Cache
Each application server has its own memory.
If a user requests data from Server 1, the cache is stored on Server 1.
When the next request reaches Server 2, that server may not have the cached data.
This can result in:
- Duplicate database queries.
- Different cached values across servers.
- Cache invalidation problems.
- Increased database load.
Distributed caching solves this problem by storing cache data in a shared external storage system.
Load Balancer
|
-----------------
| |
v v
App Server 1 App Server 2
| |
---------+-------
|
v
Distributed Cache
Redis
|
v
Database
Both application servers can access the same cached data.
8. Implementing Redis Distributed Cache
Redis is a popular distributed caching solution because it provides fast data access, flexible data structures, and support for multiple application instances.
Step 1: Install the Redis Cache Package
Install the following NuGet package:
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
Step 2: Configure Redis
In appsettings.json:
{
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}
For production environments, store sensitive connection information in environment variables, secret management systems, or other secure configuration providers.
Step 3: Register Distributed Cache
In Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration =
builder.Configuration.GetConnectionString("Redis");
options.InstanceName = "MyApp:";
});
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
The InstanceName property provides a prefix for cache keys generated by the application.
For example:
MyApp:products_active MyApp:product_10 MyApp:customer_100
This is useful when multiple applications share the same Redis instance.
9. Using IDistributedCache
ASP.NET Core provides the IDistributedCache interface for interacting with distributed cache implementations.
Unlike IMemoryCache, IDistributedCache stores values as byte arrays or strings.
Let's implement product caching using Redis.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
public class ProductService
{
private readonly ApplicationDbContext _context;
private readonly IDistributedCache _cache;
public ProductService(
ApplicationDbContext context,
IDistributedCache cache)
{
_context = context;
_cache = cache;
}
public async Task<List<Product>> GetProductsAsync()
{
const string cacheKey = "products_active";
var cachedData = await _cache.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cachedData))
{
return JsonSerializer.Deserialize<List<Product>>(cachedData)
?? new List<Product>();
}
var products = await _context.Products
.Where(x => x.IsActive)
.ToListAsync();
var serializedData = JsonSerializer.Serialize(products);
var options = new DistributedCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(10));
await _cache.SetStringAsync(
cacheKey,
serializedData,
options);
return products;
}
}
How Distributed Cache Works
The process is similar to in-memory caching:
- Check whether the data exists in Redis.
- If the cache contains the data, deserialize and return it.
- If the cache doesn't contain the data, query the database.
- Serialize the result.
- Store the serialized data in Redis.
- Return the result.
The difference is that the data is stored outside the application's memory and can be shared across multiple application instances.
10. Removing and Updating Redis Cache Entries
When data changes, we should invalidate the corresponding cache entry.
For example:
public async Task UpdateProductAsync(Product product)
{
_context.Products.Update(product);
await _context.SaveChangesAsync();
await _cache.RemoveAsync($"product_{product.Id}");
await _cache.RemoveAsync("products_active");
}
This ensures that the next request retrieves fresh data from the database.
Redis can also support more advanced caching strategies, such as:
- Cache versioning.
- Cache key namespaces.
- TTL-based expiration.
- Cache invalidation through messaging.
- Distributed locking.
- Cache warming.
- Cache stampede prevention.
For larger systems, cache invalidation should be designed carefully, especially when multiple services can update the same data.
11. IMemoryCache vs Distributed Cache
Understanding the differences helps you choose the right caching strategy.
FeatureIMemoryCacheDistributed CacheStorageApplication memoryExternal cache server/storageSpeedVery fastFast, but involves network communicationShared across serversNoYesServer restartCache is lostDepends on cache provider/configurationSuitable forSingle-server applicationsMulti-server applicationsImplementationSimpleRequires external infrastructureData formatObjectsUsually serialized dataCommon technologyBuilt-in memory cacheRedis, SQL Server
When Should You Use IMemoryCache?
Use IMemoryCache when:
- Your application runs on one server.
- You need extremely fast local access.
- You are caching small amounts of frequently accessed data.
- You don't need cache sharing across instances.
- The data can be regenerated easily.
When Should You Use Distributed Cache?
Use distributed caching when:
- Your application runs on multiple servers.
- You use containers or Kubernetes.
- You need a shared cache across multiple application instances.
- You want centralized cache storage.
- Your application needs to scale horizontally.
12. Common Caching Mistakes
Caching Everything
Not all data should be cached.
Frequently changing data, sensitive user information, and data requiring immediate consistency may not be suitable for caching.
Cache data based on actual access patterns and performance requirements.
Using Cache Keys Incorrectly
Cache keys should uniquely identify the data.
For example, caching all customer records under:
"customers"
may be incorrect if the result depends on the current user, branch, tenant, filters, or permissions.
Consider keys such as:
"customers_branch_10" "customers_branch_20" "product_category_5" "customer_100"
Ensure the key includes all parameters that affect the result.
Forgetting Cache Invalidation
Updating the database without invalidating the cache can result in outdated information.
Always consider cache invalidation whenever data is created, updated, or deleted.
Using In-Memory Cache in Multi-Server Applications Without a Strategy
Each server maintains its own cache.
Without synchronization or invalidation, users may receive different data depending on which server handles their request.
Caching Sensitive Information
Avoid caching sensitive data without appropriate security and access controls.
Never assume that cached data is safe simply because it is stored temporarily.
Ignoring Cache Stampedes
A cache stampede occurs when a cached item expires and many requests attempt to regenerate the same data simultaneously.
This can overload the database.
For high-traffic applications, consider strategies such as:
- Request coalescing.
- Distributed locking.
- Cache warming.
- Staggered expiration.
- Serving stale data while refreshing, where appropriate.
13. Choosing the Right Caching Strategy
For most ASP.NET Core applications, you can begin with a simple caching strategy.
Small Application
ASP.NET Core
|
v
IMemoryCache
|
v
PostgreSQL / SQL Server
Use local memory caching for frequently accessed reference data.
Scalable Application
Multiple ASP.NET Core Instances
|
v
Redis Distributed Cache
|
v
PostgreSQL / SQL Server
Use Redis when multiple application instances need to share cached data.
Advanced Application
Application
|
v
Hybrid Cache
|
+----> Local Memory Cache
|
+----> Redis Distributed Cache
|
v
Database
For applications requiring both very fast local reads and shared cache storage, a hybrid caching approach can be beneficial.
Modern ASP.NET Core also provides HybridCache, which combines in-memory and distributed caching and includes features such as protection against concurrent cache misses. It can be worth considering for new applications where a two-level cache is appropriate.
Conclusion
Caching is one of the most effective ways to improve the performance and scalability of ASP.NET Core applications.
By reducing unnecessary database queries and repeated computations, caching can significantly improve response times and reduce infrastructure load.
ASP.NET Core provides several caching options:
IMemoryCachefor fast local caching.IDistributedCachefor shared caching across application instances.- Redis as a powerful distributed caching provider.
HybridCachefor combining local and distributed caching strategies.
The key is not simply to cache more data, but to cache the right data with appropriate expiration and invalidation strategies.
When implemented properly, caching can make your application faster, more scalable, and more efficient without requiring significant changes to its overall architecture.