High-throughput enterprise web applications face severe scaling bottlenecks when repeated database queries and full HTML render cycles consume excessive CPU and I/O bandwidth. Traditional caching mechanisms force developers to choose between fast in-memory L1 caches (which suffer from memory overhead and multi-instance synchronization issues) or slower distributed L2 stores like Redis (which introduce network serialization latency and cache stampede vulnerabilities).
Introduced to unify and modernize caching in .NET, HybridCache bridges in-memory speed with distributed durability while automatically preventing cache stampedes. Combined with Distributed Output Caching middleware, modern ASP.NET Core MVC applications can cache entire rendered responses across distributed server farms with tag-based invalidation. This guide examines how to configure, implement, and test both strategies end-to-end.
1. Architectural Blueprint & Caching Tiers
To achieve optimal performance and multi-instance consistency, enterprise caching is stratified into two complementary layers:
Caching Layer | Technology | Primary Responsibility | Key Advantage |
L1 / L2 Hybrid Caching | HybridCache (.NET 9+)
| Caching domain data, business models, and service query results. | Combines local memory speed with distributed Redis backing; native stampede protection (coalescing concurrent requests). |
Distributed Output Caching | IOutputCacheStore + Redis
| Caching rendered HTML fragments or full controller JSON/HTML responses. | Server-side rendering acceleration with fine-grained tag-based eviction (EvictByTagAsync). |
HTTP Request
│
▼
[Output Cache Middleware] ──(Hit)──> Returns Cached HTML/JSON directly
│ (Miss)
▼
[MVC Controller Action]
│
▼
[HybridCache (L1 Memory + L2 Redis)] ──(Hit)──> Returns Domain Model
│ (Miss)
▼
[Database / Enterprise Service]
2. Configuring HybridCache and Distributed Output Caching (Program.cs)
Modern enterprise setup requires registering HybridCache alongside Redis-backed output caching and distributed memory stores:
C#
var builder = WebApplication.CreateBuilder(args);
// 1. Configure Distributed Redis Cache (serves as L2 for HybridCache and Output Cache backend)
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("RedisConnection") ?? "localhost:6379";
options.InstanceName = "EnterpriseMvc_";
});
// 2. Configure HybridCache (.NET 9+) with L1 memory limits and L2 Redis backing
builder.Services.AddHybridCache(options =>
{
options.MaximumPayloadBytes = 1024 * 1024; // 1 MB max per entry
options.DefaultEntryOptions = new Microsoft.Extensions.Caching.Hybrid.HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(10),
LocalCacheExpiration = TimeSpan.FromMinutes(2)
};
});
// 3. Configure Distributed Output Caching with Redis store and custom policies
builder.Services.AddStackExchangeRedisOutputCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("RedisConnection") ?? "localhost:6379";
});
builder.Services.AddOutputCache(options =>
{
// Default policy: cache for 60 seconds
options.AddBasePolicy(builder => builder.Expire(TimeSpan.FromSeconds(60)));
// Custom named policy with tag support for instant invalidation
options.AddPolicy("CatalogPolicy", builder =>
builder.Expire(TimeSpan.FromMinutes(10))
.Tag("catalog-cache")
.SetVaryByQuery("category", "page"));
});
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseRouting();
app.UseOutputCache(); // Must be placed after Routing and before MapControllers
app.MapControllers();
app.Run();
3. Implementing HybridCache in Domain Services
HybridCache eliminates the classic cache stampede (dogpile effect) by using internal locks (GetOrCreateAsync) so that concurrent requests for an expired cache key only trigger a single database query while other callers await the result.
C#
using Microsoft.Extensions.Caching.Hybrid;
public interface IProductCatalogService
{
Task<ProductDetailsDto> GetProductDetailsAsync(int productId, CancellationToken cancellationToken = default);
}
public class ProductCatalogService : IProductCatalogService
{
private readonly HybridCache _hybridCache;
private readonly ApplicationDbContext _dbContext;
private readonly ILogger<ProductCatalogService> _logger;
public ProductCatalogService(
HybridCache hybridCache,
ApplicationDbContext dbContext,
ILogger<ProductCatalogService> logger)
{
_hybridCache = hybridCache;
_dbContext = dbContext;
_logger = logger;
}
public async Task<ProductDetailsDto> GetProductDetailsAsync(int productId, CancellationToken cancellationToken = default)
{
string cacheKey = $"product-details-{productId}";
// GetOrCreateAsync handles L1 (memory), L2 (Redis), stampede locking, and factory execution transparently
return await _hybridCache.GetOrCreateAsync(
cacheKey,
async cancel =>
{
_logger.LogInformation("Cache miss for product {ProductId}. Fetching from database.", productId);
var entity = await _dbContext.Products
.AsNoTracking()
.Include(p => p.Category)
.FirstOrDefaultAsync(p => p.Id == productId, cancel);
if (entity is null)
{
throw new KeyNotFoundException($"Product with ID {productId} was not found.");
}
return new ProductDetailsDto(
entity.Id,
entity.Name,
entity.Price,
entity.Category.Name,
DateTime.UtcNow
);
},
tags: ["catalog", $"category-{productId}"],
cancellationToken: cancellationToken
);
}
}
public sealed record ProductDetailsDto(int Id, string Name, decimal Price, string CategoryName, DateTime RetrievedAt);
4. Consuming Output Caching and Handling Invalidation in Controllers
Controllers can leverage the [OutputCache] attribute with named policies, while administrative actions can instantly invalidate cached responses and hybrid entries using IOutputCacheStore and HybridCache.
C#
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OutputCaching;
using Microsoft.Extensions.Caching.Hybrid;
[Route("catalog")]
public class CatalogController : Controller
{
private readonly IProductCatalogService _productService;
private readonly IOutputCacheStore _outputCacheStore;
private readonly HybridCache _hybridCache;
public CatalogController(
IProductCatalogService productService,
IOutputCacheStore outputCacheStore,
HybridCache hybridCache)
{
_productService = productService;
_outputCacheStore = outputCacheStore;
_hybridCache = hybridCache;
}
// Cached at the output level using the "CatalogPolicy"
[HttpGet("product/{id:int}")]
[OutputCache(PolicyName = "CatalogPolicy")]
public async Task<IActionResult> Details(int id, CancellationToken cancellationToken)
{
try
{
var product = await _productService.GetProductDetailsAsync(id, cancellationToken);
return View("ProductDetails", product);
}
catch (KeyNotFoundException)
{
return NotFound();
}
}
// Administrative action to update product and invalidate all related caches instantly
[HttpPost("product/update")]
public async Task<IActionResult> UpdateProduct([FromBody] UpdateProductCommand command, CancellationToken cancellationToken)
{
// 1. Update database record...
// await _productService.UpdateAsync(command);
// 2. Invalidate HybridCache entry and tag groups explicitly
await _hybridCache.RemoveAsync($"product-details-{command.Id}", cancellationToken);
// 3. Purge all output cached pages tagged with "catalog-cache" across the server farm
await _outputCacheStore.EvictByTagAsync("catalog-cache", cancellationToken);
return Ok(new { Status = "Product updated and cache evicted successfully." });
}
}
5. Conclusion
Implementing HybridCache alongside Distributed Output Caching establishes a high-performance, resilient caching tier in ASP.NET Core MVC. HybridCache protects your relational databases from traffic spikes via built-in stampede protection and multi-tier memory/Redis synchronization, while Distributed Output Caching eliminates redundant server-side rendering overhead. By pairing these technologies with tag-based cache eviction, you maintain strict data consistency and achieve lightning-fast response times at scale.
Join the conversation! Your thoughts help the community grow.