Exploring the new HybridCache in .NET
New major dotnet releases always come with their bunch of new interesting features.
With the release of .NET 9, Microsoft introduced a powerful new caching mechanism called HybridCache
. Itβs designed to combine the benefits of both in-memory and distributed caching, providing better performance and scalability for modern applications. Let’s dive into it π
What is HybridCache?
HybridCache is a new caching abstraction that intelligently uses both:
- MemoryCache: Fast, local, in-memory cache.
- DistributedCache: Shared cache like Redis or SQL Server, used across multiple app instances.
The goal of HybridCache is to give you the best of both worlds:
- Super-fast local access.
- Centralized consistency and scalability.
- Safety against cache stampede .
Why use HybridCache and how it works ?
Traditionally, developers had to choose between performance (using MemoryCache) or scalability (using DistributedCache).
With HybridCache, you can use both without the struggle of handling and syncing 2 different implementations in your code ! π₯
Here is how the HybridCache
implementation works under the hood:
- Try read from memory first (fast).
- If not found, fallback to distributed cache (shared).
- Then, automatically populate caches from available providers.
If we think about a use case using 2 instances of a dotnet api, both connected with a shared redis instance, it could be:
-
User A makes a request on Instance 1 β the local memory cache is empty β Redis is also empty β the data is fetched from the database, then stored in Redis and locally (in Instance 1’s memory).
-
User B makes a request on Instance 2 β the local memory cache is empty β Redis has the data β Redis returns the data β it’s then stored in Instance 2’s local cache.
-
Any subsequent requests on either instance will hit the local in-memory cache, skipping both Redis and the database, resulting in faster response times.
This helps reduce latency and offloads traffic from distributed caches, by smartly using both implementation. π
How to use it
To use HybridCache
, first install the necessary NuGet package:
dotnet add package Microsoft.Extensions.Caching.Hybrid
Then configure it in your app:
builder.Services.AddMemoryCache();
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
});
builder.Services.AddHybridCache();
You don’t actually need to configure both memory and distributed cache providers, that’s where the magic happens here. If you configure only one of those, the HybridCache mechanism will automatically use the implementation configured in your app, giving you some flexibility and abstraction in your business code. π
And use it like this, for example using the GetOrCreateAsync()
method to get a cache entry or create it if missing:
var cache = app.Services.GetRequiredService<HybridCache>();
var value = await cache.GetOrCreateAsync("my-key", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
return await GetDataFromDatabaseAsync();
});
As you can see, for the moment Microsoft decided to not expose any interfaces, so you have to get the concrete implementation in the DI, making unit testing and decoupling trickier. But I suppose (and hope) this will be updated in the future as this feature is pretty new.
Note that the implementation also provides RemoveAsync()
to remove a specific cache entry with key and SetAsync()
to set a cache entry directly, as it was the case for the existing memory and distributed interfaces.
Conclusion
The new HybridCache in .NET is a great addition for developers who want performance and scalability without managing multiple cache layers manually.
It simplifies caching logic and improves overall application performance, especially in cloud and microservice architectures.
If you’re starting new projects or planning to migrate on dotnet 9 or even the new LTS coming this november, keep that new cool feature in mind π
As always, Happy hacking π¨βπ»β€οΈ