| ASP.NET Core Global Exception Handling and ProblemDetails :👈 | 👉:ASP.NET Core Microservices Architecture |
ASP.NET Core Caching: In-Memory, Distributed Cache and Redis |
ASP.NET Core Caching: In-Memory, Distributed Cache and Redis
1. Introduction
Caching is a technique used to temporarily store frequently accessed data so that future requests can retrieve it faster without repeatedly performing expensive operations.
In ASP.NET Core applications, caching helps improve:
- Application response time.
- Database performance.
- Application scalability.
- Throughput under heavy traffic.
- Overall user experience.
The main caching approaches covered here are:
- In-Memory Caching
- Distributed Caching
- Redis Distributed Caching
2. Why Do We Need Caching?
Consider an API that retrieves product information from a database.
Without caching:
- The client sends a request.
- The API queries SQL Server.
- The database executes the query.
- The API returns the result.
If thousands of users request the same product information, the database may execute the same query repeatedly.
With caching:
- The client sends a request.
- The API checks the cache.
- If the data exists, the API returns it immediately.
- If the data does not exist, the API queries the database.
- The API stores the result in the cache.
- Subsequent requests retrieve the cached result.
Simple Caching Flow
3. Types of Caching in ASP.NET Core
| Cache Type | Storage Location | Shared Between Application Instances? |
|---|---|---|
| In-Memory Cache | Application process memory | No |
| Distributed Cache | External cache storage | Yes, when instances use the same cache |
| Redis Cache | Redis server | Yes, with a shared Redis deployment |
| Output Cache | Configured output-cache store | Depends on the configured store |
| Response Cache | HTTP caching infrastructure | Depends on the infrastructure |
The two main application-data caching approaches are In-Memory Caching and Distributed Caching.
4. In-Memory Caching (IMemoryCache)
In-Memory Caching stores data directly in the memory of the ASP.NET Core application process.
It is useful when:
- The application runs on a single server or instance.
- Cached data is relatively small.
- Very fast cache access is required.
- Sharing cached data between servers is not necessary.
Architecture
Client | v ASP.NET Core Application | +---- IMemoryCache | +---- SQL Server
The cache exists inside the application's process. If the application restarts, its in-memory cache is lost.
4.1 Register IMemoryCache
In Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
AddMemoryCache() registers the services required to use IMemoryCache.
4.2 Inject IMemoryCache
Example service:
public class ProductService
{
private readonly IMemoryCache _cache;
private readonly AppDbContext _context;
public ProductService(
IMemoryCache cache,
AppDbContext context)
{
_cache = cache;
_context = context;
}
public async Task<Product?> GetProductAsync(int id)
{
string cacheKey = $"product_{id}";
if (_cache.TryGetValue(cacheKey, out Product? product))
{
return product;
}
product = await _context.Products.FindAsync(id);
if (product != null)
{
_cache.Set(
cacheKey,
product,
TimeSpan.FromMinutes(10));
}
return product;
}
}
4.3 Understanding the Code
Step 1: Generate a cache key
string cacheKey = $"product_{id}";
A unique key identifies each product.
- product_101
- product_102
- product_103
Step 2: Check whether the data exists
if (_cache.TryGetValue(cacheKey, out Product? product))
{
return product;
}
If the product exists in the cache, return it without querying the database.
Step 3: Retrieve data from the database
product = await _context.Products.FindAsync(id);
This executes only when the cache does not contain the requested product.
Step 4: Store the result
_cache.Set(
cacheKey,
product,
TimeSpan.FromMinutes(10));
The product is stored for up to 10 minutes.
4.4 Cache Expiration Options
Absolute Expiration
The cache entry expires after a fixed duration, regardless of how frequently it is accessed.
_cache.Set(
"products",
products,
new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(30)
});
Sliding Expiration
The expiration timer is refreshed whenever the cache entry is accessed.
_cache.Set(
"products",
products,
new MemoryCacheEntryOptions
{
SlidingExpiration =
TimeSpan.FromMinutes(10)
});
If the data is accessed within each 10-minute interval, it can remain cached. It expires after 10 minutes without access.
Combining Absolute and Sliding Expiration
_cache.Set(
"products",
products,
new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow =
TimeSpan.FromHours(1),
SlidingExpiration =
TimeSpan.FromMinutes(10)
});
The entry expires after one hour at the latest, even if it is accessed frequently.
4.5 Removing Cached Data
When product information changes, the corresponding cache entry should be removed.
_cache.Remove($"product_{id}");
This prevents the application from continuing to return outdated information.
4.6 Memory Cache Limitations
- Cache data is stored only inside one application process.
- Different application instances have independent caches.
- Application restarts clear the cache.
- Multiple servers cannot automatically share cached values.
- Large cache entries can consume application memory.
5. Distributed Caching (IDistributedCache)
Distributed caching stores data outside the application process.
Instead of each application instance maintaining its own independent cache, multiple application instances can access a shared cache service.
Typical distributed cache implementations include:
- Redis
- SQL Server distributed cache
- Other distributed cache providers implementing IDistributedCache
Architecture
Both API instances can access the same distributed cache.
For example, if API 1 stores product 101 in Redis, API 2 can retrieve that cached product.
5.1 What Is IDistributedCache?
IDistributedCache is an abstraction provided by ASP.NET Core for distributed caching.
It provides common methods for storing and retrieving cache values.
| Method | Purpose |
|---|---|
| GetAsync() | Retrieves a cached value |
| SetAsync() | Stores a cached value |
| RefreshAsync() | Refreshes a cache entry's sliding expiration |
| RemoveAsync() | Removes a cached value |
The interface primarily stores and retrieves byte arrays. For JSON-based application data, serialization and deserialization are commonly used.
5.2 Register Distributed Cache
The exact registration depends on the distributed cache provider.
For example, SQL Server distributed cache:
builder.Services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString =
builder.Configuration.GetConnectionString("DefaultConnection");
options.SchemaName = "dbo";
options.TableName = "AppCache";
});
The cache table must be created using the supported SQL Server cache-table creation process.
This is one implementation of IDistributedCache; it is not Redis.
5.3 Using IDistributedCache
Example service:
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
public class ProductCacheService
{
private readonly IDistributedCache _cache;
private readonly AppDbContext _context;
public ProductCacheService(
IDistributedCache cache,
AppDbContext context)
{
_cache = cache;
_context = context;
}
public async Task<Product?> GetProductAsync(int id)
{
string cacheKey = $"product_{id}";
string? cachedData =
await _cache.GetStringAsync(cacheKey);
if (cachedData != null)
{
return JsonSerializer.Deserialize<Product>(
cachedData);
}
var product =
await _context.Products.FindAsync(id);
if (product != null)
{
string json =
JsonSerializer.Serialize(product);
await _cache.SetStringAsync(
cacheKey,
json,
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(10)
});
}
return product;
}
}
5.4 How It Works
- The application generates a cache key.
- It calls
GetStringAsync()to retrieve the cached value. - If a value exists, it deserializes the JSON and returns the product.
- If the value does not exist, it retrieves the product from SQL Server.
- It serializes the product into JSON.
- It stores the JSON using
SetStringAsync(). - Future requests can retrieve the cached value.
5.5 Distributed Cache Expiration
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(30),
SlidingExpiration =
TimeSpan.FromMinutes(10)
};
await _cache.SetStringAsync(
"products",
json,
options);
The distributed cache provider manages expiration according to its implementation.
5.6 Distributed Cache Advantages
- Multiple application instances can share cached data.
- Cache data survives an individual application process restart.
- Cache storage can be managed separately from application memory.
- It supports horizontally scaled applications.
- It provides a common abstraction through IDistributedCache.
5.7 Distributed Cache Limitations
- Requires an external cache provider or service.
- Network communication introduces additional latency.
- Serialization and deserialization add processing overhead.
- Cache infrastructure needs monitoring and maintenance.
- Cache availability becomes an additional operational consideration.
6. Redis Distributed Cache
Redis is an in-memory data store commonly used as a distributed cache.
It stores data in memory and supports different data structures, expiration policies and high-performance data access.
Redis is widely used in distributed applications because multiple application instances can access the same Redis server or Redis deployment.
6.1 Redis Architecture
Both API instances use the same Redis cache.
If API 1 caches product 101, API 2 can retrieve the same value from Redis.
6.2 Redis vs IDistributedCache
- Redis is a cache/data-store technology.
IDistributedCacheis an ASP.NET Core abstraction.- Redis can be used as the implementation behind
IDistributedCache.
This separation allows application code to depend on an abstraction rather than directly depending on Redis-specific APIs.
6.3 Install Redis Cache Package
Install the NuGet package:
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
This package provides the Redis implementation of IDistributedCache.
6.4 Configure Redis 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();
6.5 Configure Redis Connection String
In appsettings.json:
{
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}
Here:
localhostis the Redis server address.6379is the default Redis port.InstanceNameadds a common prefix to cache keys.
In production, store credentials and sensitive connection information securely rather than committing them to source control.
6.6 Use Redis Through IDistributedCache
The same ProductCacheService example shown earlier works with Redis.
No Redis-specific code is required in the service because it depends on IDistributedCache.
public class ProductCacheService
{
private readonly IDistributedCache _cache;
public ProductCacheService(IDistributedCache cache)
{
_cache = cache;
}
public async Task SetProductAsync(
int id,
Product product)
{
string key = $"product_{id}";
string json = JsonSerializer.Serialize(product);
await _cache.SetStringAsync(
key,
json,
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(15)
});
}
public async Task<Product?> GetProductAsync(int id)
{
string key = $"product_{id}";
string? json = await _cache.GetStringAsync(key);
if (json == null)
{
return null;
}
return JsonSerializer.Deserialize<Product>(json);
}
public async Task RemoveProductAsync(int id)
{
await _cache.RemoveAsync($"product_{id}");
}
}
6.7 Using Redis Directly
Sometimes applications need Redis-specific features that are not exposed by IDistributedCache.
For example:
- Redis data structures.
- Atomic operations.
- Distributed locks.
- Pub/Sub messaging.
- Redis transactions.
- Advanced key operations.
For these requirements, developers can use the StackExchange.Redis package directly.
Install the package:
dotnet add package StackExchange.Redis
Register a Redis connection:
builder.Services.AddSingleton<IConnectionMultiplexer>(
ConnectionMultiplexer.Connect("localhost:6379"));
Use Redis directly:
public class RedisService
{
private readonly IDatabase _database;
public RedisService(IConnectionMultiplexer connection)
{
_database = connection.GetDatabase();
}
public async Task SetValueAsync(string key, string value)
{
await _database.StringSetAsync(
key,
value,
TimeSpan.FromMinutes(10));
}
public async Task<string?> GetValueAsync(string key)
{
RedisValue value =
await _database.StringGetAsync(key);
return value.HasValue ? value.ToString() : null;
}
}
ConnectionMultiplexer is designed to be shared and reused. Avoid creating a new connection for every request.
7. In-Memory Cache vs Distributed Cache vs Redis
| Feature | In-Memory Cache | Distributed Cache | Redis |
|---|---|---|---|
| Storage | Application memory | External storage | Redis server memory |
| ASP.NET Core abstraction | IMemoryCache | IDistributedCache | Can implement IDistributedCache |
| Shared between servers | No | Yes, with shared provider | Yes, with shared Redis deployment |
| Network call | No | Usually yes | Yes |
| Access speed | Very fast | Depends on provider | Generally very fast |
| Survives application restart | No | Depends on provider | Generally yes, depending on Redis configuration |
| Serialization | Usually not required | Commonly required | Depends on the API and data format |
| Best suited for | Single-instance or local cache | Multi-instance applications | High-performance shared caching |
Important: Distributed Cache is a category of caching, whereas Redis is one technology that can implement it.
8. Cache-Aside Pattern
Cache-Aside is one of the most commonly used caching patterns in ASP.NET Core.
The application controls when to read from the cache, retrieve data from the database and update the cache.
Flow
Example:
public async Task<Product?> GetProductAsync(int id)
{
string key = $"product_{id}";
var product = await _cache.GetStringAsync(key);
if (product != null)
{
return JsonSerializer.Deserialize<Product>(product);
}
var result = await _context.Products.FindAsync(id);
if (result != null)
{
var json = JsonSerializer.Serialize(result);
await _cache.SetStringAsync(
key,
json,
TimeSpan.FromMinutes(10));
}
return result;
}
This pattern is useful when:
- Reads are more frequent than writes.
- Some data is requested repeatedly.
- The application can tolerate a defined period of stale data.
9. Cache Invalidation
Cache invalidation means removing or updating cached data when the original data changes.
Consider this scenario:
- Product price is ₹1,000 in SQL Server.
- The application caches the product.
- An administrator changes the price to ₹1,200.
- The cache still contains ₹1,000.
- Users may receive outdated information.
9.1 Remove Cache After Updating Database
public async Task UpdateProductAsync(Product product)
{
_context.Products.Update(product);
await _context.SaveChangesAsync();
await _cache.RemoveAsync($"product_{product.Id}");
}
The next request retrieves the latest product from the database and repopulates the cache.
9.2 Cache Expiration
Set a limited expiration time so outdated entries eventually disappear.
AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(10)
9.3 Cache Versioning
Include a version number in cache keys when a group of cached data needs to be invalidated by changing the key namespace.
products_v1
products_v2
Versioning can help during deployments or changes to cached data formats.
10. Cache Stampede Problem
A cache stampede happens when a popular cache entry expires and many requests attempt to rebuild it simultaneously.
Example:
- A popular product is cached.
- The cache entry expires.
- Hundreds of requests arrive at the same time.
- Every request finds a cache miss.
- Every request queries the database.
- The database receives a sudden load spike.
Prevention Techniques
- Use a per-key lock or request coalescing.
- Add randomized expiration times to reduce simultaneous expiry.
- Refresh important cache entries before expiration.
- Use background refresh for suitable data.
- Apply rate limiting and database protection where appropriate.
For a single application instance, SemaphoreSlim can help coordinate cache population. For multiple application instances, use an appropriate distributed coordination strategy when required.
11. Cache-Aside vs Write-Through vs Write-Behind
| Pattern | Description | Typical Use |
|---|---|---|
| Cache-Aside | Application reads from cache first and loads from database on a miss. | Read-heavy applications |
| Write-Through | Writes update the cache and underlying data store as part of the write workflow. | Data that needs coordinated updates |
| Write-Behind | Writes are first accepted by the cache and persisted to the database later. | Specialized high-throughput workloads |
Write-Behind requires careful handling of failures and data durability because the database update may happen asynchronously.
12. Output Caching vs Response Caching vs Data Caching
| Type | What It Caches | Typical Purpose |
|---|---|---|
| Data Caching | Application data or query results | Avoid repeated database or service calls |
| Output Caching | Generated HTTP responses on the server | Avoid repeating endpoint execution |
| Response Caching | HTTP responses according to HTTP caching rules | Support HTTP client and intermediary caching |
12.1 Output Caching
Output caching stores the generated response on the server and can avoid executing the endpoint again for matching requests.
Registration:
builder.Services.AddOutputCache();
var app = builder.Build();
app.UseOutputCache();
app.MapGet("/products", () =>
{
return Results.Ok(new[]
{
new { Id = 1, Name = "Laptop" },
new { Id = 2, Name = "Mobile" }
});
})
.CacheOutput();
app.Run();
Output caching can also be configured with policies that define expiration and other rules.
12.2 Response Caching
Response caching uses HTTP cache headers and HTTP caching rules.
Registration:
builder.Services.AddResponseCaching();
var app = builder.Build();
app.UseResponseCaching();
app.MapGet("/products", (HttpContext context) =>
{
context.Response.Headers.CacheControl =
"public,max-age=60";
return Results.Ok(new[]
{
"Laptop",
"Mobile"
});
});
app.Run();
Response caching is not a replacement for application-level data caching.
13. When Should You Use Each Cache?
Use In-Memory Cache When
- The application runs on a single instance.
- Data is small and frequently accessed.
- Extremely low-latency local access is important.
- Losing the cache during application restart is acceptable.
Examples: Static application configuration, reference data and small lookup collections.
Use Distributed Cache When
- The application runs on multiple servers.
- All application instances need access to the same cached data.
- Cache data should remain independent of an individual application process.
- A shared cache service is already available.
Examples: Shared lookup data, user-related application data and frequently accessed API results.
Use Redis When
- High-performance shared caching is required.
- Multiple API instances need the same cache.
- Redis-specific data structures or operations are useful.
- The application needs additional Redis capabilities beyond basic key-value caching.
Examples: Product catalog data, frequently accessed configuration, session-related state and real-time application data.
14. Best Practices for ASP.NET Core Caching
- Cache frequently accessed data: Avoid caching everything. Focus on data that is expensive to retrieve and frequently requested.
- Choose appropriate expiration: Use absolute and sliding expiration according to the data's freshness requirements.
- Use meaningful cache keys: Use consistent names such as product_101 or category_10.
- Invalidate cache after updates: Remove or refresh entries when the underlying data changes.
- Avoid caching sensitive information unnecessarily: Consider privacy, authorization, tenant isolation and data retention requirements.
- Use distributed caching for multiple instances: Do not depend on IMemoryCache for data that must be shared across servers.
- Avoid large cache entries: Large objects can increase memory usage, network traffic and serialization costs.
- Handle cache failures: A cache outage should not automatically make the entire application unavailable. Define suitable fallback behavior.
- Monitor cache performance: Track hit rate, miss rate, memory usage, latency and eviction activity.
- Prevent cache stampedes: Coordinate concurrent cache population for frequently requested entries.
- Use appropriate serialization: Ensure cached data can be safely serialized and deserialized across application versions.
- Do not cache user-specific data under shared keys: Include relevant user or tenant identifiers where appropriate, and enforce authorization independently of the cache.
15. Common Caching Mistakes
| Mistake | Why It Is a Problem | Better Approach |
|---|---|---|
| Using IMemoryCache in a multi-server application for shared data | Each server has a different cache. | Use distributed caching. |
| Never expiring cache entries | Data may become stale indefinitely. | Configure expiration. |
| Not invalidating cache after updates | Users receive outdated data. | Remove or refresh affected entries. |
| Creating Redis connections per request | Connection overhead and resource waste. | Reuse ConnectionMultiplexer. |
| Caching very large objects | High memory and network consumption. | Cache only required data. |
| Using identical keys for different users | Can expose incorrect or unauthorized data. | Use properly scoped keys. |
| Ignoring cache failures | Application may fail when cache is unavailable. | Define fallback and timeout behavior. |
| Caching everything | Adds complexity without necessarily improving performance. | Cache based on measured access patterns. |
16. Interview Questions and Answers
Q1. What is caching in ASP.NET Core?
Caching is the process of storing frequently accessed data temporarily so that subsequent requests can retrieve it faster without repeatedly accessing the original data source.
Q2. What is the difference between IMemoryCache and IDistributedCache?
IMemoryCache stores data inside the application process. IDistributedCache stores data in an external cache provider that can be shared across multiple application instances.
Q3. What is Redis?
Redis is an in-memory data store that is commonly used as a distributed cache. It supports high-performance data access, expiration and several data structures.
Q4. Is Redis the same as IDistributedCache?
No. Redis is a technology, whereas IDistributedCache is an ASP.NET Core abstraction. Redis can implement IDistributedCache.
Q5. What happens to IMemoryCache when an application restarts?
The cached data is lost because it exists in the application's process memory.
Q6. Can multiple ASP.NET Core instances share IMemoryCache?
No. Each application instance maintains its own independent in-memory cache.
Q7. What is cache expiration?
Cache expiration defines how long a cached entry remains valid before it is removed or treated as expired.
Q8. What is the difference between absolute and sliding expiration?
Absolute expiration expires an entry after a fixed duration. Sliding expiration refreshes the expiration timer whenever the entry is accessed.
Q9. What is cache invalidation?
Cache invalidation is the process of removing or updating cached data when the underlying source data changes.
Q10. What is a cache stampede?
A cache stampede occurs when many requests simultaneously try to rebuild the same expired or missing cache entry, potentially overloading the database.
Q11. Why is Redis preferred in distributed applications?
Redis provides fast shared data access and can be accessed by multiple application instances. It also offers capabilities beyond basic caching through its data structures and operations.
Q12. What is Cache-Aside?
Cache-Aside is a pattern where the application checks the cache first, retrieves data from the database on a cache miss, and then stores the result in the cache.
Q13. What is the difference between Output Caching and Data Caching?
Data caching stores application data or query results. Output caching stores generated HTTP responses to avoid repeating endpoint execution.
Q14. Should every database query be cached?
No. Caching is useful when data is expensive to retrieve, frequently accessed and can tolerate the chosen freshness policy. Frequently changing or rarely requested data may not benefit from caching.
17. Summary
- IMemoryCache: Stores data in the application's local memory. Best for single-instance or local caching scenarios.
- IDistributedCache: Provides an abstraction for accessing shared external cache storage.
- Redis: A high-performance in-memory data store commonly used to implement distributed caching.
- Cache-Aside: A common pattern where the application checks the cache first and loads data from the database on a miss.
- Cache Invalidation: Ensures cached data does not remain outdated after the original data changes.
- Output Caching: Stores generated HTTP responses on the server to reduce repeated endpoint execution.
Practical recommendation: For a multi-instance ASP.NET Core Web API, Redis through IDistributedCache is a common choice for shared application-data caching. Use IMemoryCache for small, instance-local data where sharing is not required.
| ASP.NET Core Global Exception Handling and ProblemDetails :👈 | 👉:ASP.NET Core Microservices Architecture |