HybridCache in ASP.NET Core: Solving Cache Stampede with Layered Caching

HybridCache in ASP.NET Core: Solving Cache Stampede with Layered Caching

When an ASP.NET Core API repeatedly builds the same product list, configuration object, or expensive external-service result, caching is an obvious optimization. However, using only IMemoryCache can produce inconsistent results in a multi-server deployment, while using only IDistributedCache adds network and serialization overhead to every lookup. A more serious issue appears when an entry expires and many requests rebuild it at the same time. This behavior is commonly called cache stampede or thundering herd.

HybridCache, introduced with .NET 9, combines an in-process cache with an optional distributed cache and coordinates concurrent factory calls for the same key. This article uses a product catalog scenario to show how to configure Redis, design cache keys, invalidate entries, and avoid common correctness and security mistakes.

Why a normal cache miss can overload the database

A basic IMemoryCache.GetOrCreateAsync implementation may allow several concurrent requests for the same missing key to execute the factory method. Imagine a product catalog cached for 10 seconds. If 200 requests arrive just after expiration, all 200 requests may execute the same database query independently. The result is unnecessary database CPU, connection-pool pressure, object allocation, and increased request latency.

This is easy to miss on a single development server. In a Kubernetes deployment or an application behind a load balancer, every process has its own local memory. A cache hit on one node does not prevent a cache miss on another. A distributed cache allows nodes to share stored values, but it does not automatically provide a global lock that prevents every node from rebuilding the same value.

How HybridCache is organized

HybridCache uses two cache levels:

  • L1: An in-process memory cache. It is very fast, but each server has a separate copy and the data is lost when the process stops.
  • L2: An out-of-process distributed cache such as Redis. It can be shared by application nodes and can survive individual process restarts.
  • Source: The database or external API used when both cache levels miss.

A request checks L1 first and then L2 when a secondary cache is configured. If the value is absent, the factory method loads it from the source and the result is stored in the cache layers. Calls using the same HybridCache instance are coordinated for a given key, so only one concurrent caller runs the factory while the others wait for its result. This coordination is instance-scoped; it is not a distributed lock across every process in a fleet.

Installing and configuring Redis

Add the HybridCache and Redis provider packages:

dotnet add package Microsoft.Extensions.Caching.Hybrid
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

Register Redis and HybridCache in Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration =
        builder.Configuration.GetConnectionString("Redis");
});

builder.Services.AddHybridCache(options =>
{
    options.MaximumKeyLength = 512;
    options.MaximumPayloadBytes = 1024 * 1024;
    options.DefaultEntryOptions = new HybridCacheEntryOptions
    {
        Expiration = TimeSpan.FromMinutes(10),
        LocalCacheExpiration = TimeSpan.FromSeconds(30)
    };
});

builder.Services.AddScoped<ProductCatalogService>();

Expiration controls the general lifetime of the cache entry, while LocalCacheExpiration controls how long the L1 copy remains valid. For frequently changing data such as prices, a shorter local lifetime can reduce stale values on a busy node. Keep the Redis connection string in secret configuration or environment variables rather than in source control.

A practical product-list example

Assume that the application returns a paged product list from Entity Framework Core:

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

public sealed class ProductCatalogService(
    HybridCache cache,
    AppDbContext db)
{
    public async Task<IReadOnlyList<ProductListItem>> GetPageAsync(
        int page,
        int pageSize,
        CancellationToken cancellationToken)
    {
        page = Math.Max(page, 1);
        pageSize = Math.Clamp(pageSize, 1, 100);

        var key = $"catalog:products:v1:page:{page}:size:{pageSize}";

        return await cache.GetOrCreateAsync(
            key,
            async cancel => await db.Products
                .AsNoTracking()
                .OrderBy(x => x.Id)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .Select(x => new ProductListItem(
                    x.Id,
                    x.Name,
                    x.Price,
                    x.Stock))
                .ToListAsync(cancel),
            cancellationToken: cancellationToken);
    }
}

Every input that affects the result must be represented in the key. If the page number or page size is omitted, different requests can incorrectly share the same result. The v1 segment provides a simple way to invalidate an entire data shape after changing the DTO or query rules. Caching a compact DTO projection is usually safer and cheaper than caching full entity graphs.

Invalidating entries after writes

A time-to-live is not always enough. If a product price changes, the product list may need immediate invalidation. One approach is to remove entries by tag after the database transaction succeeds:

public async Task UpdatePriceAsync(
    int productId,
    decimal price,
    CancellationToken cancellationToken)
{
    var product = await db.Products
        .SingleAsync(x => x.Id == productId, cancellationToken);

    product.Price = price;
    await db.SaveChangesAsync(cancellationToken);

    await cache.RemoveByTagAsync("catalog:products");
}

The entries must be created with the same tag:

var options = new HybridCacheEntryOptions
{
    Expiration = TimeSpan.FromMinutes(10),
    LocalCacheExpiration = TimeSpan.FromSeconds(30),
    Tags = ["catalog:products"]
};

return await cache.GetOrCreateAsync(
    key,
    async cancel => await LoadProductsAsync(page, pageSize, cancel),
    options,
    cancellationToken);

Tag invalidation is a logical operation. The behavior of local copies on other servers depends on the cache topology and provider. For highly sensitive data, combine short L1 lifetimes with versioned keys or an explicit application-wide invalidation mechanism.

Correctness and security rules

  • Never put user-specific data under a shared key that omits the user, tenant, or authorization context.
  • Do not reuse a public catalog key for data whose visibility depends on permissions.
  • Treat the cache as disposable. The application must still produce correct results when every cache entry disappears.
  • Plan serialization compatibility. Increment the key version when the cached DTO contract changes.
  • Limit payload size. Large entries increase serialization time, Redis traffic, and memory pressure.
  • Pass the request cancellation token to the factory and database query so abandoned requests do not continue unnecessary work.

When should you use HybridCache?

IMemoryCache can be sufficient for a small single-server application with inexpensive data loading. HybridCache is a stronger fit when the application has multiple nodes, expensive source operations, or frequent concurrent requests for the same key. It is not automatically beneficial for data that changes every few milliseconds, contains sensitive per-user state, or is cheap to recompute.

Measure the result rather than assuming caching helped. Track cache hit rate, source-query count, factory duration, serialized payload size, and the age of values returned to clients. A successful design should reduce source load, ensure that concurrent misses do not multiply expensive work, and provide a clearly acceptable freshness policy after updates.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published