Introducing HybridCache in .NET 9

This blog is presented as a part of C# Advent 2024. Follow the link to check out the rest of the excellent C# and .NET content coming out in 2 blogs per day between December 1 - 25.

Caching plays a crucial role in performance in web applications by reducing strain on backend systems. The new HybridCache library, available in preview in .NET 9, simplifies caching and addresses some limitations of previous approaches, making it easier for developers to implement efficient, reliable caching solutions.

Why a New Cache Library?

Existing caching options, like IMemoryCache and IDistributedCache, serve different purposes but come with challenges. IMemoryCache is fast but limited to in-process memory, which can lead to issues like cache inconsistency or data loss on application restarts. IDistributedCache solves these issues with external storage solutions like Redis, but it adds latency, serialization complexity, and dependency on external systems.

HybridCache combines the strengths of both approaches, providing:

  • Seamless in-process and distributed caching.
  • Automatic serialization and deserialization.
  • Stampede protection to handle multiple simultaneous requests for the same data.

Getting Started with HybridCache

Here’s are the steps to integrate HybridCache into your .NET 9 ASP.NET Core projects:

1. Add the Package

Include the Microsoft.Extensions.Caching.Hybrid NuGet package. NOTE: Once released, you will be able to add the package without the –prerelease flag.

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

2. Configure the Cache

Register HybridCache in Program.cs with the AddHybridCache method, where you can also set options like default expiration.

builder.Services.AddHybridCache();

3. Use the Cache

Replace existing caching logic with a HybridCache call:

var data = await hybridCache.GetOrCreateAsync(key, async () => 
{
    return await FetchExpensiveDataAsync();
});

Instead of managing separate Get and Set calls, you use the GetOrCreateAsync method, which checks for cached data and executes a provided callback to populate the cache if needed.

Features of Hybrid Cache

Unified API

HybridCache simplifies caching by providing a single API that works seamlessly for both in-process and out-of-process scenarios. It’s designed to replace IDistributedCache and IMemoryCache without requiring major changes to your code, making it easy to integrate or upgrade your caching strategy.

When an IDistributedCache implementation is configured, HybridCache leverages it as a secondary cache layer, giving you the best of both worlds: the speed of in-memory caching combined with the reliability and persistence of distributed caching.

Stampede Protection

One of the challenges with traditional caching is the risk of a “cache stampede,” where multiple requests hit the system simultaneously when a cached item expires or is missing. This can overwhelm your backend, as each request triggers the same expensive operation to regenerate the data.

HybridCache addresses this by coordinating requests. Only the first caller executes the factory method to repopulate the cache, while others simply wait for the result. This approach reduces unnecessary load and keeps your system running smoothly, even under heavy traffic.

Configurable Serialization

When you register the HybridCache service during startup, you can customize serialization, including type-specific or generalized serializers, such as protobuf or XML. By default, the library handles string and byte[] internally, and uses System.Text.Json for everything else.

builder.Services.AddHybridCache(options =>
    {
        options.DefaultEntryOptions = new HybridCacheEntryOptions
        {
            Expiration = TimeSpan.FromSeconds(10),
            LocalCacheExpiration = TimeSpan.FromSeconds(5)
        };
    }).AddSerializer<SomeProtobufMessage, 
        GoogleProtobufSerializer<SomeProtobufMessage>>();

Looking Ahead

HybridCache is in preview as part of the .NET 9 release, with general availability expected in future minor release soon.

Contact Trailhead to get started implementing HybridCache or to improve the caching in your .NET applications. Our experience in implementing efficient, scalable caching solutions ensures your applications will perform optimally, saving you time and effort while avoiding the most common pitfalls.

Picture of Piotr Kolodziej

Piotr Kolodziej

Born and raised in Poland, Piotr did his first programming on Atari 800XL. He covered his first dial-up modem with a duve, so his mom wouldn’t hear it and freak over the internet bills. He graduated with a degree in Telecommunication and Business Application Programming. Piotr is a certified .NET and Azure Developer, and is passionate about excellent software architecture.

Free Consultation

Sign up for a FREE consultation with one of Trailhead's experts.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Sentiment Analysis in C#: Azure AI Language or LLMs

Explore how C# developers can leverage both Azure AI Language and Azure OpenAI for sentiment analysis. This post compares traditional NLP services with LLM-based approaches using real-world code from an exit interview system, helping you choose the right tool for your specific use case.

Read More

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.