HybridCache in .NET: In-Memory + Redis Caching in One API

Say you run the store-hours API for an outdoor retailer with stores across Colorado and Texas. Every request waits on a 400 ms lookup, and your two web servers each keep their own IMemoryCache, so both pay it again.

HybridCache fixes both problems: one GetOrCreateAsync call checks memory first, then a shared L2 such as Redis or SQL Server, and runs the slow lookup once even when 10 requests land together.

Below, I time each step on .NET 10 against a real Minimal API on two local ports.

What Is HybridCache in .NET?

HybridCache is an abstract class from the Microsoft.Extensions.Caching.Hybrid package (GA, 10.11.0 today). AddHybridCache() registers a default implementation that you inject like any other singleton.

It’s a two-level cache behind one API:

  • L1 (primary): a MemoryCache inside your process. Fast, but every server has its own copy.
  • L2 (secondary, optional): whatever IDistributedCache you registered, such as Redis, SQL Server or Postgres.
  • Extras: stampede protection, tag-based invalidation and built-in serialization.

With no L2 registered, you still get the in-process cache and the stampede protection. The package also runs on older targets, down to .NET Framework 4.7.2 and .NET Standard 2.0.

The Sample Store-Hours API We’ll Use

Everything below runs against one .NET 10 file-based app, StoreApi.cs. LoadHoursAsync stands in for the slow database or vendor call: it waits 400 ms and returns a Denver or Austin store.

#:sdk Microsoft.NET.Sdk.Web
#:package Microsoft.Extensions.Caching.Hybrid@10.11.0
#:package Microsoft.Extensions.Caching.SqlServer@10.0.14
#:package System.Security.Cryptography.Pkcs@10.0.14
#:property PublishAot=false
using System.Collections.Concurrent;
using System.Diagnostics;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Caching.Memory;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddMemoryCache();
builder.Services.AddHybridCache(options =>
{
    options.DefaultEntryOptions = new HybridCacheEntryOptions
    {
        Expiration = TimeSpan.FromMinutes(30),          // overall lifetime, sent to the L2
        LocalCacheExpiration = TimeSpan.FromMinutes(5)  // L1, in this process only
    };
});
if (builder.Configuration["L2"] == "sql")             // dotnet run StoreApi.cs -- --L2 sql
{
    builder.Services.AddDistributedSqlServerCache(options =>
    {
        options.ConnectionString = "Server=.;Database=w14_cache;Trusted_Connection=True;TrustServerCertificate=True";
        options.SchemaName = "dbo";
        options.TableName = "HybridL2";
    });
}
var app = builder.Build();
var runs = new ConcurrentDictionary<string, int>();   // how often each factory really ran

// The slow store-hours lookup every request used to pay: 400 ms
static async Task<StoreHours> LoadHoursAsync(int id, CancellationToken ct)
{
    await Task.Delay(400, ct);
    return new StoreHours(id, id % 2 == 1 ? "Denver, CO" : "Austin, TX", "9:00 AM - 9:00 PM");
}

app.MapGet("/stores/{id:int}/hours", async (int id, HybridCache cache, CancellationToken ct) =>
{
    var sw = Stopwatch.StartNew();
    var hours = await cache.GetOrCreateAsync($"store:{id}:hours", async cancel =>
    {
        runs.AddOrUpdate($"hybrid:{id}", 1, (_, n) => n + 1);
        return await LoadHoursAsync(id, cancel);
    }, tags: ["stores"], cancellationToken: ct);
    return new { hours, ms = Math.Round(sw.Elapsed.TotalMilliseconds, 1),
                 factoryRuns = runs.GetValueOrDefault($"hybrid:{id}") };
});

app.MapGet("/memory/stores/{id:int}/hours", async (int id, IMemoryCache cache, CancellationToken ct) =>
{
    var hours = await cache.GetOrCreateAsync($"store:{id}:hours", async entry =>
    {
        runs.AddOrUpdate($"memory:{id}", 1, (_, n) => n + 1);
        entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
        return await LoadHoursAsync(id, ct);
    });
    return new { hours, factoryRuns = runs.GetValueOrDefault($"memory:{id}") };
});

app.MapDelete("/stores/{id:int}/hours", async (int id, HybridCache cache) =>
    await cache.RemoveAsync($"store:{id}:hours"));

app.MapPost("/stores/invalidate", async (HybridCache cache) =>
    await cache.RemoveByTagAsync("stores"));

app.Run();

record StoreHours(int StoreId, string City, string Hours);

Here’s what it exposes:

EndpointWhat it does
GET /stores/{id}/hoursReads through HybridCache, returns the hours, the time spent in GetOrCreateAsync (ms) and how often the factory ran on this server
GET /memory/stores/{id}/hoursThe same lookup through plain IMemoryCache, for comparison
DELETE /stores/{id}/hoursCalls RemoveAsync for one store
POST /stores/invalidateCalls RemoveByTagAsync("stores")

I start it twice, as two servers behind a load balancer would be:

dotnet run StoreApi.cs -- --urls http://localhost:5920
dotnet run StoreApi.cs -- --urls http://localhost:5921

Before each test, I restart both and hit a throwaway store once, so JIT warm-up doesn’t land in the timings.

The Pkcs line is there because Microsoft.Data.SqlClient (pulled in by the SQL Server cache) brought a 9.0.4 build that NuGet flagged with warnings NU1902 and NU1903.

Method 1: Add HybridCache and Call GetOrCreateAsync (Recommended)

This is the method you’ll use 95% of the time. Install the package, call AddHybridCache, and read through GetOrCreateAsync:

dotnet add package Microsoft.Extensions.Caching.Hybrid --version 10.11.0

Same sample app, with no L2 yet. This client asks port 5920 for the Denver store three times in a row:

#!/usr/bin/env dotnet
#:property PublishAot=false
using System.Diagnostics;
using System.Text.Json.Nodes;

using var http = new HttpClient();
for (int call = 1; call <= 3; call++)
{
    string json = await http.GetStringAsync("http://localhost:5920/stores/101/hours");
    var body = JsonNode.Parse(json)!;
    Console.WriteLine($"Call {call}: {body["ms"],5} ms  {body["hours"]!["city"]}  " +
        $"factory runs = {body["factoryRuns"]}");
}

Output:

Call 1: 409.9 ms  Denver, CO  factory runs = 1
Call 2:   0.1 ms  Denver, CO  factory runs = 1
Call 3:     0 ms  Denver, CO  factory runs = 1
HybridCache GetOrCreateAsync in VS Code: ColdWarm.cs calls the store-hours API three times, the first call takes about 400 ms and the next two take under 1 ms with factory runs = 1
First call pays the 400 ms lookup; the next two come straight from the in-memory L1

The first call spent 410 ms in GetOrCreateAsync (the 400 ms lookup plus overhead on a busy machine). Calls 2 and 3 took 0.1 ms and 0.0 ms, and the factory counter never moved past 1.

How does this code work?

GetOrCreateAsync takes a key and a factory. It looks in L1, then L2 if there is one, and only on a double miss does it run your factory and store the result in both levels.

The key $"store:{id}:hours" has a separator, so store 1 + 01 can’t collide with store 10 + 1. Microsoft recommends writing the interpolated string right inside the call. Keys are capped at 1,024 characters by default (MaximumKeyLength).

The factory gets its own CancellationToken, which is canceled only when every waiting caller gives up. My CancellationToken guide explains why you pass it on to the slow call.

Note: there’s also an overload that takes a state argument and a static lambda, to skip closure allocations. Microsoft says most apps don’t need it, and I’d agree.

Method 2: Stop a Cache Stampede with HybridCache

A stampede is what happens when a popular entry expires and many requests miss at the same moment. Each one runs the slow lookup. IMemoryCache.GetOrCreateAsync doesn’t prevent that; HybridCache does.

Same sample app again. This client fires 10 simultaneous requests at the IMemoryCache endpoint, then 10 at the HybridCache one:

#!/usr/bin/env dotnet
#:property PublishAot=false
using System.Text.Json.Nodes;

using var http = new HttpClient();
async Task<string> Burst(string path)
{
    // 10 requests for the same store at the same moment
    var calls = Enumerable.Range(0, 10)
        .Select(_ => http.GetStringAsync("http://localhost:5920" + path));
    string[] bodies = await Task.WhenAll(calls);
    int runs = bodies.Max(b => (int)JsonNode.Parse(b)!["factoryRuns"]!);
    return $"10 requests -> factory ran {runs}x";
}
Console.WriteLine("IMemoryCache: " + await Burst("/memory/stores/202/hours"));
Console.WriteLine("HybridCache:  " + await Burst("/stores/303/hours"));

Output:

IMemoryCache: 10 requests -> factory ran 10x
HybridCache:  10 requests -> factory ran 1x
HybridCache stampede protection in VS Code: Stampede.cs sends 10 concurrent requests, IMemoryCache ran the factory 10 times and HybridCache ran it once
Ten concurrent misses: IMemoryCache ran the lookup 10 times, HybridCache once

IMemoryCache ran the 400 ms lookup 10 times for one key. HybridCache ran it once, and the other nine requests waited for that result.

How does this work?

HybridCache tracks in-flight factories per key. The first caller starts the factory; later callers for the same key join that task instead of starting their own. The async/await plumbing makes the waiting cheap: no thread is blocked.

Important: this coordination is per HybridCache instance, so per server. Two servers that miss at the same moment still run the factory once each.

Method 3: Set Expiration and LocalCacheExpiration with HybridCacheEntryOptions

HybridCacheEntryOptions has two clocks. Expiration is the overall lifetime, passed to the L2. LocalCacheExpiration is how long the in-process L1 copy lives.

StoreApi.cs sets both globally through DefaultEntryOptions: 30 minutes and 5 minutes.

You can also pass options per call. To see both clocks fire, I used a small console app with the same SQL Server L2 (set up in Method 5), a 2-second L1 and a 10-second L2. The second run turns the L2 off with HybridCacheEntryFlags.DisableDistributedCache:

#!/usr/bin/env dotnet
#:package Microsoft.Extensions.Caching.Hybrid@10.11.0
#:package Microsoft.Extensions.Caching.SqlServer@10.0.14
#:package System.Security.Cryptography.Pkcs@10.0.14
#:package Microsoft.Extensions.DependencyInjection@10.0.14
#:property PublishAot=false
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddHybridCache();
services.AddDistributedSqlServerCache(o =>
{
    o.ConnectionString = "Server=.;Database=w14_cache;Trusted_Connection=True;TrustServerCertificate=True";
    o.SchemaName = "dbo";
    o.TableName = "HybridL2";
});
var cache = services.BuildServiceProvider().GetRequiredService<HybridCache>();

var options = new HybridCacheEntryOptions
{
    Expiration = TimeSpan.FromSeconds(10),          // L2: SQL Server
    LocalCacheExpiration = TimeSpan.FromSeconds(2)  // L1: this process
};
var l1Only = new HybridCacheEntryOptions
{
    Expiration = TimeSpan.FromSeconds(10),
    LocalCacheExpiration = TimeSpan.FromSeconds(2),
    Flags = HybridCacheEntryFlags.DisableDistributedCache
};

await Reads("L1 + L2", "promo:CO", options);
await Reads("L1 only", "promo:TX", l1Only);

async Task Reads(string label, string key, HybridCacheEntryOptions entryOptions)
{
    int runs = 0, t = 0;
    foreach (int wait in new[] { 0, 1, 3, 8 })          // seconds between reads
    {
        await Task.Delay(TimeSpan.FromSeconds(wait));
        t += wait;
        await cache.GetOrCreateAsync(key,
            ct => { runs++; return ValueTask.FromResult("FREESHIP over $50"); }, entryOptions);
        Console.WriteLine($"{label}: t = {t,2} s  factory runs = {runs}");
    }
}

Output:

L1 + L2: t =  0 s  factory runs = 1
L1 + L2: t =  1 s  factory runs = 1
L1 + L2: t =  4 s  factory runs = 1
L1 + L2: t = 12 s  factory runs = 2
L1 only: t =  0 s  factory runs = 1
L1 only: t =  1 s  factory runs = 1
L1 only: t =  4 s  factory runs = 2
L1 only: t = 12 s  factory runs = 3

How does this code work?

With both levels, the read at 4 s missed L1 (expired at 2 s) but found the value in SQL Server, so the factory didn’t run. At 12 s, both had expired and it ran a second time.

With L1 only, the 4 s read already ran the factory again. Same code, same timings: the only difference is the L2. Options you leave null inherit from DefaultEntryOptions, so you only set what changes.

The flags are a bitwise enum. These are the ones I actually reach for:

FlagEffect
DisableLocalCacheSkip L1 reads and writes (for data that must never be stale on a server)
DisableDistributedCacheSkip L2 reads and writes (per-server data)
DisableUnderlyingDataOnly read the cache; never call the factory
DisableCompressionStore this payload uncompressed

If those values come from configuration, bind them with the options pattern in ASP.NET Core instead of hard-coding minutes.

Method 4: Invalidate HybridCache Entries with RemoveAsync and RemoveByTagAsync

When the Denver store changes its holiday hours, you can’t wait 30 minutes. RemoveAsync(key) drops one entry from L1 and L2. RemoveByTagAsync(tag) drops every entry created with that tag; StoreApi.cs tags each store with "stores".

Same Denver store, same server on port 5920:

#!/usr/bin/env dotnet
#:property PublishAot=false
using System.Text.Json.Nodes;

using var http = new HttpClient { BaseAddress = new Uri("http://localhost:5920") };
async Task Get(string label)
{
    var body = JsonNode.Parse(await http.GetStringAsync("/stores/101/hours"))!;
    Console.WriteLine($"{label,-24} {body["ms"],5} ms  factory runs = {body["factoryRuns"]}");
}
await Get("First call");
await Get("Cached");
await http.DeleteAsync("/stores/101/hours");          // RemoveAsync
await Get("After RemoveAsync");
await Get("Cached again");
await http.PostAsync("/stores/invalidate", null);     // RemoveByTagAsync("stores")
await Get("After RemoveByTagAsync");

Output:

First call               415.6 ms  factory runs = 1
Cached                     0.1 ms  factory runs = 1
After RemoveAsync        414.8 ms  factory runs = 2
Cached again               0.1 ms  factory runs = 2
After RemoveByTagAsync   416.2 ms  factory runs = 3
HybridCache RemoveAsync and RemoveByTagAsync output in VS Code: after each removal the next call takes about 400 ms and the factory run count goes from 1 to 2 to 3
Each removal forces exactly one fresh 400 ms lookup; the call after it is cached again

How does this work?

After RemoveAsync, the next read was a miss and the factory count went from 1 to 2. After RemoveByTagAsync, it went to 3. Each removal cost exactly one lookup.

Tag invalidation is logical, not a delete. HybridCache records “ignore anything with this tag created before now”, and old values sit in L1/L2 until they expire.

RemoveByTagAsync("*") invalidates everything, even untagged entries. Globs like "store*" aren’t supported.

Pro Tip: expose these calls from an admin endpoint protected with JWT authentication, and add rate limiting in ASP.NET Core so nobody can flush your cache in a loop.

Method 5: Add a SQL Server L2 Cache So Two Servers Share HybridCache Entries

Back to the two servers from the intro. With L1 only, here’s the same store requested from port 5920, then 5921:

#!/usr/bin/env dotnet
#:property PublishAot=false
using System.Text.Json.Nodes;

using var http = new HttpClient();
foreach (int port in new[] { 5920, 5921 })
{
    string json = await http.GetStringAsync($"http://localhost:{port}/stores/404/hours");
    var body = JsonNode.Parse(json)!;
    Console.WriteLine($"Server :{port}  {body["ms"],5} ms  " +
        $"factory runs on this server = {body["factoryRuns"]}");
}

Output (L1 only):

Server :5920  410.9 ms  factory runs on this server = 1
Server :5921  408.7 ms  factory runs on this server = 1

Both servers paid the full lookup. To share entries, register an out-of-process IDistributedCache. I don’t run Redis on this machine, so I used SQL Server, which HybridCache treats the same way.

First, the cache table. dnx (new in the .NET 10 SDK) runs the dotnet-sql-cache tool without a global install:

dnx dotnet-sql-cache@10.0.14 --yes create "Server=.;Database=w14_cache;Trusted_Connection=True;TrustServerCertificate=True" dbo HybridL2
Table and index were created successfully.

Then the package and the registration, which StoreApi.cs already has behind --L2 sql:

dotnet add package Microsoft.Extensions.Caching.SqlServer --version 10.0.14
builder.Services.AddDistributedSqlServerCache(options =>
{
    options.ConnectionString = "Server=.;Database=w14_cache;Trusted_Connection=True;TrustServerCertificate=True";
    options.SchemaName = "dbo";
    options.TableName = "HybridL2";
});

Same TwoServers.cs, with both servers restarted with the SQL Server L2:

Server :5920  416.1 ms  factory runs on this server = 1
Server :5921   25.9 ms  factory runs on this server = 0
HybridCache with a SQL Server L2 cache in VS Code: TwoServers.cs reads store 404 from port 5920, which runs the factory, then from port 5921, which gets it from SQL Server with factory runs = 0
Port 5921 never ran the lookup: it found the entry port 5920 wrote to SQL Server

Port 5921 ran the factory zero times. It missed its own L1, found the entry in SQL Server and copied it into L1.

Its 25.9 ms is a SQL round trip on a busy dev machine; the factory count is the real proof. The row is in the table:

sqlcmd -S . -E -C -d w14_cache -W -Q "SELECT Id, DATALENGTH(Value) AS Bytes FROM dbo.HybridL2"
Id Bytes
-- -----
store:404:hours 108

How does this work?

AddHybridCache looks for a registered IDistributedCache and uses it as the L2. There’s no extra HybridCache setting. One catch from Learn: AddDistributedMemoryCache is ignored as an L2, because it lives in the same process.

Now the gotcha. Removal clears the current server’s L1 and the L2, but not another server’s L1. Same two servers, both holding store 404:

#!/usr/bin/env dotnet
#:property PublishAot=false
using System.Text.Json.Nodes;

using var http = new HttpClient();
async Task Get(int port)
{
    var body = JsonNode.Parse(await http.GetStringAsync($"http://localhost:{port}/stores/404/hours"))!;
    Console.WriteLine($"  :{port}  {body["ms"],5} ms  factory runs = {body["factoryRuns"]}");
}
await Get(5920);
await Task.Delay(1000);
await Get(5921);                                    // both servers have store 404 in L1 now
await http.DeleteAsync("http://localhost:5920/stores/404/hours");
Console.WriteLine("RemoveAsync on :5920, then read both again:");
await Get(5921); await Get(5920);

Output:

  :5920  416.3 ms  factory runs = 1
  :5921   11.5 ms  factory runs = 0
RemoveAsync on :5920, then read both again:
  :5921    0.1 ms  factory runs = 0
  :5920  415.3 ms  factory runs = 2

After RemoveAsync on port 5920, port 5921 still served its L1 copy with no factory run, while 5920 reloaded. Keep LocalCacheExpiration short for data that changes, since it’s your staleness window on other servers.

How to Use Redis as the HybridCache L2

In production, Redis (or Azure Managed Redis) is the usual L2. The wiring is two calls. To be clear, I compiled this against Microsoft.Extensions.Caching.StackExchangeRedis 10.0.14 but didn’t run it: there’s no Redis server on this machine.

dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis --version 10.0.14
#:sdk Microsoft.NET.Sdk.Web
#:package Microsoft.Extensions.Caching.Hybrid@10.11.0
#:package Microsoft.Extensions.Caching.StackExchangeRedis@10.0.14
#:property PublishAot=false
using Microsoft.Extensions.Caching.Hybrid;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("Redis");
    options.InstanceName = "store-api:";
});
builder.Services.AddHybridCache();       // finds the Redis IDistributedCache and uses it as L2
var app = builder.Build();

Keep the Redis connection string in user secrets locally and in Key Vault or app settings in Azure, as in appsettings per environment in ASP.NET Core. Your GetOrCreateAsync code doesn’t change at all.

How HybridCache Serializes Cached Objects

L1 keeps objects, but L2 needs bytes. HybridCache handles string and byte[] itself and uses System.Text.Json for everything else, so our StoreHours record needed no setup. Its SQL row was 108 bytes.

For protobuf or another format, chain AddSerializer<T, TSerializer>() or AddSerializerFactory<T>() after AddHybridCache.

By default, every L1 hit is deserialized again, so each caller gets its own instance. If your type is immutable, mark it sealed and add [ImmutableObject(true)], and HybridCache can hand out the same instance.

ASP.NET Core Memory Cache vs Redis vs HybridCache

Which cache should you use? Here’s how the three APIs compared on the same store-hours requests:

IMemoryCacheIDistributedCache (Redis, SQL Server)HybridCache
Where data livesThis processShared serverThis process (L1) + optional shared L2
Survives a restart / shared by serversNoYesYes, through the L2
Stampede protectionNo (10 factory runs for 10 requests)NoYes (1 run for 10 requests)
SerializationNone (stores objects)You convert to byte[]Built in (System.Text.Json)
Invalidate a groupNo tagsNo tagsTags + RemoveByTagAsync
Pick it whenOne server, tiny lookupsLegacy code already on itNew code on .NET 8, 9 or 10

My rule: new code goes to HybridCache, even on a single server, because adding Redis later is one registration. For whole HTTP responses rather than data, look at output caching, and register services with the right DI lifetimes in ASP.NET Core.

Things to Keep in Mind

  • Invalidation is per server for L1. Other servers keep their L1 copy until LocalCacheExpiration; keep it short for data that changes.
  • Don’t build keys from raw user input. Use IDs you control, with a separator, or you risk key floods and collisions.
  • Watch the 1 MB payload limit. Bigger values (MaximumPayloadBytes) are logged and simply not cached, so make sure logging in ASP.NET Core is on in production.
  • Native AOT needs source-generated JSON. Reflection serialization isn’t available, so register a JsonSerializerContext for cached types.
  • Check NuGet warnings after adding an L2 package. Mine pulled in a flagged Pkcs build; a direct package reference fixed it.

If you’re building out this same API, these are good next reads:

Frequently Asked Questions

Is HybridCache available in .NET 8?

Yes. Microsoft.Extensions.Caching.Hybrid is a NuGet package, not part of a single .NET release, and it supports targets down to .NET Framework 4.7.2 and .NET Standard 2.0. I ran it on .NET 10.

Does HybridCache need Redis?

No. Without an L2, it caches in process and still protects against stampedes. Add Redis, SQL Server or Postgres through IDistributedCache when several servers should share entries.

What’s the difference between Expiration and LocalCacheExpiration?

Expiration is the overall lifetime and goes to the L2. LocalCacheExpiration is how long the in-memory L1 copy lives. When a value comes back from the L2, its L1 copy never outlives the remaining overall lifetime.

Does RemoveByTagAsync delete the data?

No. It’s a logical invalidation: entries with that tag created earlier are treated as misses, and the old values expire normally. See the HybridCache library docs on Microsoft Learn.

Should I replace IDistributedCache with HybridCache?

For new code, yes. HybridCache reads and writes through your existing IDistributedCache, so the stored data stays where it is, and you drop the manual serialization.