How to Use HybridCache in C# and .NET for L1/L2 Caching and Stampede Protection

For years, .NET teams building high-traffic APIs faced an awkward choice between IMemoryCache (fast in-process RAM, not shared across pods) and IDistributedCache (shared across pods via Redis, yet requires manual JSON serialization and network hops on every read). Worse, neither API prevents a cache stampede: when a hot key expires under load, 50 concurrent requests miss at once and all 50 query your database simultaneously. HybridCache unifies L1 in-memory caching, L2 distributed caching, and built-in stampede protection behind a single GetOrCreateAsync call.

Editorial illustration of HybridCache two-level L1/L2 caching and stampede protection in .NET

Editorial illustration: HybridCache checks fast L1 memory first, falls back to L2 distributed cache, and coalesces concurrent misses per instance.

Summary

  • HybridCache (in Microsoft.Extensions.Caching.Hybrid, introduced alongside .NET 9 and supporting runtimes down to .NET Framework 4.7.2 / .NET Standard 2.0) provides a unified two-level caching API (L1 in-memory + optional L2 IDistributedCache).
  • Stampede protection: Concurrent GetOrCreateAsync calls for the same key on the same HybridCache instance share a single factory execution instead of hammering your database—note per Microsoft Learn’s caching overview that coordination applies per HybridCache instance, not across separate server nodes.
  • Serialization & tags: Handles string and byte[] natively, defaults to System.Text.Json for objects (configurable with custom serializers like Protobuf), and supports tag-based invalidation via RemoveByTagAsync.
  • Return immutable objects (or avoid mutating returned cached objects in-place) because L1 in-memory hits share object references across callers unless configured otherwise.

Prerequisites: NuGet Library & .NET Runtime

  • Package (Microsoft.Extensions.Caching.Hybrid): Add the official Microsoft.Extensions.Caching.Hybrid NuGet package in .NET 8, .NET 9, .NET 10, or .NET 11 projects (ASP.NET Core Web APIs, Blazor, or Worker Services).
  • L2 Distributed Cache (Optional): Register AddStackExchangeRedisCache(...) or another IDistributedCache implementation—if none is registered, HybridCache still works cleanly using L1 in-process caching and stampede protection.
  • IDE: Visual Studio 2022/2026 or VS Code with the .NET SDK.

Practical example: Registering and using HybridCache

First, register HybridCache in Program.cs (optionally alongside Redis for L2):

using Microsoft.Extensions.Caching.Hybrid;

var builder = WebApplication.CreateBuilder(args);

// Optional L2 distributed cache (e.g., Redis)
// builder.Services.AddStackExchangeRedisCache(o => o.Configuration = "localhost:6379");

builder.Services.AddHybridCache(options =>
{
    options.MaximumPayloadBytes = 1024 * 1024; // 1 MB guard
    options.DefaultEntryOptions = new HybridCacheEntryOptions
    {
        Expiration = TimeSpan.FromMinutes(10),
        LocalCacheExpiration = TimeSpan.FromMinutes(2),
    };
});

Notice the two expirations:

  • LocalCacheExpiration (L1): How long each server instance keeps the entry in local RAM (kept shorter, e.g., 2 minutes, so pods refresh from L2/Redis periodically).
  • Expiration (L2): How long the distributed cache keeps the entry.

Now inject HybridCache into a service or Minimal API endpoint and call GetOrCreateAsync:

public sealed record ProductSummary(int Id, string Name, decimal Price);

public sealed class CatalogService(HybridCache cache, IProductRepository repo)
{
    public ValueTask<ProductSummary> GetProductAsync(int id, CancellationToken ct)
    {
        return cache.GetOrCreateAsync(
            key: $"product:{id}",
            state: (repo, id),
            factory: static async (state, token) =>
                await state.repo.LoadSummaryAsync(state.id, token),
            tags: [$"product:{id}", "catalog"],
            cancellationToken: ct);
    }

    public ValueTask InvalidateProductAsync(int id, CancellationToken ct)
        => cache.RemoveByTagAsync($"product:{id}", ct);
}

Passing (repo, id) into the state parameter with a static lambda avoids closure allocations on cache hits—a nice zero-allocation habit when combined with System.Text.Json source generation and Keyed Services DI.

Important trade-offs and limitations

  1. Stampede protection is per-instance: If you run five Kubernetes pods and a key expires, each pod coalesces concurrent requests within that pod, meaning at most 5 factory calls hit your database instead of 500—not strictly 1 globally unless you add distributed locking.
  2. Tag invalidation scope: RemoveByTagAsync invalidates matching entries cleanly, though you should monitor L1 LocalCacheExpiration if multiple pods need quick cross-node invalidation.
  3. Reference sharing on L1 hits: As Microsoft Learn’s in-memory caching docs warn, mutating an object returned from in-memory cache mutates it for every other caller reading that L1 entry—use sealed record or immutable DTOs.

For more .NET configuration and caching patterns, see choosing between IOptions<T>, IOptionsSnapshot<T>, and IOptionsMonitor<T>.

Common mistakes

  • Mutating a cached List<T> or class property after GetOrCreateAsync returns it. Keep cached types immutable (record, IReadOnlyList<T>) so one request never corrupts another request’s cached data.
  • Capturing this or scoped services inside a non-static factory lambda unnecessarily. Passing explicit state into the static GetOrCreateAsync overload eliminates closure allocations on the hot path.
  • Setting LocalCacheExpiration longer than Expiration across multi-pod deployments. If L2 expires or gets purged by another pod, a long L1 TTL keeps serving stale local RAM copies on other pods.
  • Caching massive multi-megabyte blobs without tuning MaximumPayloadBytes. Keep cached entries focused on compact DTOs rather than huge unpaginated collections.

Why this matters

Replacing custom IMemoryCache + IDistributedCache + SemaphoreSlim stampede-lock boilerplate with HybridCache removes subtle concurrency and serialization bugs while cutting both latency (L1) and database spikes (stampede protection).

My Take

If you are building any new ASP.NET Core API in .NET 8, .NET 9, or .NET 10 that caches database or external HTTP results, adopt HybridCache immediately—even if you only use L1 in-process caching today. You get stampede protection and RemoveByTagAsync out of the box, and adding Redis L2 later is a single registration line without rewriting your services.

Conclusion

Install Microsoft.Extensions.Caching.Hybrid, configure short LocalCacheExpiration alongside Expiration, use the static GetOrCreateAsync overload with immutable DTOs and tags, and pair it with IDistributedCache when scaling across multiple server instances.

Sources