How to use HybridCache in ASP.NET Core

By FoxLearn 12/31/2024 3:23:23 AM   131
Caching is a key strategy for improving application performance and scalability.

.NET Core and its predecessor, ASP.NET, have provided caching mechanisms for quite some time, offering in-memory and distributed caching options.

HybridCache is a new API in .NET 9 that enhances caching in ASP.NET Core by offering additional features, benefits, and improved ease of use.

What is HybridCache?

HybridCache is a new library built on the Microsoft.Extensions.Caching.Distributed.IDistributedCache library. It enhances existing ASP.NET Core caching mechanisms and adds several useful features.

Key Features of HybridCache

  1. Stampede Protection: This feature prevents multiple requests for the same data from being processed simultaneously, thereby minimizing unnecessary load on the system.
  2. Multi-Tier Caching: It supports both in-process (L1) and out-of-process (L2) caching. While L1 is fast and limited to memory, L2 can handle larger datasets, typically stored in distributed systems like Redis or SQL Server.
  3. Configurable Serialization: HybridCache offers flexible serialization options, allowing developers to define how cached data is saved and retrieved.
  4. Tag-Based Eviction: Cache entries can be evicted based on tags, making it easier to manage cache entries with shared characteristics.

How HybridCache Works

HybridCache simplifies caching by abstracting two cache levels. When a cache entry is requested, HybridCache first checks the L1 (in-memory) cache for the data. If the data isn’t found, it falls back to the L2 (out-of-process) cache, if configured. Upon a cache miss in both, the data is fetched from the source and stored in both caches for future requests.

Implementing HybridCache in Your Application

To use the HybridCache library, install the HybridCache NuGet package in your project.

In Visual Studio, right-click the project in the Solution Explorer, then choose "Manage NuGet Packages" to install the package.

In the NuGet Package Manager window, search for the Microsoft.Extensions.Caching.Hybrid package and install it. Be sure to check the "Include prerelease" checkbox.

Alternatively, you can install the package using the NuGet Package Manager console by running the following command:

dotnet add package Microsoft.Extensions.Caching.Hybrid --prerelease

After installing HybridCache in your project, register it as a service in the dependency injection container by adding the appropriate code in the Program.cs file.

builder.Services.AddHybridCache(options =>
{
    options.MaximumPayloadBytes = 1024 * 1024; // 1MB max payload
    options.MaximumKeyLength = 1024;
    options.DefaultEntryOptions = new HybridCacheEntryOptions
    {
        Expiration = TimeSpan.FromMinutes(3),
        LocalCacheExpiration = TimeSpan.FromMinutes(3)
    };
});

Create the CustomHybridCache service in ASP.NET Core

Create an interface called ICustomHybridCacheService in a file named ICustomHybridCacheService.cs.

public interface ICustomHybridCacheService
{
    public Task<string> GetCachedDataAsync(string key, CancellationToken token = default);
}

Create a class named CustomHybridCacheService that implements the ICustomHybridCacheService interface.

public class CustomHybridCacheService : ICustomHybridCacheService
{
    private readonly HybridCache _cache;
    public CustomHybridCacheService(HybridCache cache) => _cache = cache;

    public async Task<string> GetCachedDataAsync(string key, CancellationToken token = default)
    {
        return await _cache.GetOrCreateAsync(
            $"{key}",
            async cancel => await GetDataAsync(key, cancel),
            token: token
        );
    }

    private async Task<string> GetDataAsync(string key, CancellationToken token)
    {
        return $"Data for cache entry with key: {key}";
    }
}

The GetCachedDataAsync method retrieves data from the cache using a key. If the data is not found in the cache, it uses a fallback strategy to fetch the data from a secondary source.

In the Program.cs file, ensure to add your service and configure it for dependency injection:

builder.Services.AddSingleton<ICustomHybridCacheService, CustomHybridCacheService>();

Once everything is set up, you can run your application. If the requested data is not found in the cache, it will be fetched and stored in both the in-memory (L1) and out-of-process (L2) caches.

Benefits of HybridCache

  • Improved Performance: By combining L1 and L2 caches, HybridCache ensures fast data retrieval while offering a scalable solution for large datasets.
  • Reduced Cache Stampede Risk: Stampede protection significantly reduces unnecessary database hits and application overload.
  • Flexibility: The configurable serialization and eviction options provide more control over cached data, ensuring it meets specific application needs.

HybridCache in .NET 9 brings powerful caching capabilities to ASP.NET Core applications. By combining the best features of in-memory and distributed caching, it offers enhanced scalability, reduced overhead, and greater flexibility. Developers can take full advantage of these improvements by integrating HybridCache into their projects to optimize caching strategies for modern web applications.