In-memory caching with IMemoryCache and HybridCache

suggest change

A cache keeps the result of a slow operation, such as a database query or an HTTP call, so the next request can reuse it. Modern .NET has two standard caching APIs, both in the Microsoft.Extensions.Caching.* family that ASP.NET Core uses:

API Package What it is
IMemoryCache / MemoryCache Microsoft.Extensions.Caching.Memory A thread-safe in-process dictionary with expiration, size limits and eviction. Stores object references.
HybridCache Microsoft.Extensions.Caching.Hybrid (.NET 9+) A two-level cache: in-process (L1) plus an optional distributed cache (L2, e.g. Redis). Async get-or-create with stampede protection, tags and serialization.

The older System.Runtime.Caching.MemoryCache from .NET Framework (see MemoryCache) still works, but new code should use one of these two.

The examples are .NET 10 file-based programs: save the code as app.cs and run it with dotnet run app.cs. The #:package lines pull the NuGet packages (Microsoft.Extensions.Caching.Memory 10.0.13, Microsoft.Extensions.Caching.Hybrid 10.11.0). In an ASP.NET Core project Microsoft.Extensions.Caching.Memory is already part of the shared framework. All output comes from real runs.

IMemoryCache basics

MemoryCache implements IMemoryCache. Keys are any object (usually strings) and values are stored as object references, so nothing is copied or serialized:

#:package Microsoft.Extensions.Caching.Memory@10.0.13
using Microsoft.Extensions.Caching.Memory;

using var cache = new MemoryCache(new MemoryCacheOptions());

// Set and read back
cache.Set("greeting", "hello");
if (cache.TryGetValue("greeting", out string? s))
{
    Console.WriteLine($"hit: {s}");
}
Console.WriteLine($"Get<int?>(\"missing\") = {cache.Get<int?>("missing")?.ToString() ?? "null"}");

// Get-or-create: the factory runs only on a miss
for (int i = 0; i < 3; i++)
{
    User u = cache.GetOrCreate("user:42", entry =>
    {
        Console.WriteLine("  loading user 42 from the database");
        entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
        return new User(42, "Ada");
    })!;
    Console.WriteLine(u);
}

cache.Remove("user:42");
Console.WriteLine($"after Remove: {cache.TryGetValue("user:42", out _)}");
Console.WriteLine($"Count = {cache.Count}");

record User(int Id, string Name);
hit: hello
Get<int?>("missing") = null
  loading user 42 from the database
User { Id = 42, Name = Ada }
User { Id = 42, Name = Ada }
User { Id = 42, Name = Ada }
after Remove: False
Count = 1

Set, Get<T>, TryGetValue<T>, GetOrCreate and GetOrCreateAsync are extension methods in CacheExtensions. The entry passed to the factory is an ICacheEntry: set expiration, size, priority and callbacks on it before you return the value.

Because the cache hands out the stored reference, every caller gets the same object. Cache immutable objects (records, strings, frozen collections) or treat cached objects as read-only. If one caller changes a cached List<T>, everyone sees the change.

Using it with dependency injection

In real apps you don't create MemoryCache yourself. AddMemoryCache registers one shared IMemoryCache singleton, and services take it as a constructor parameter (see Dependency injection with Microsoft.Extensions.DependencyInjection):

#:package Microsoft.Extensions.Caching.Memory@10.0.13
#:package Microsoft.Extensions.DependencyInjection@10.0.13
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddMemoryCache(o => o.SizeLimit = 10_000);
services.AddSingleton<CurrencyRates>();
using ServiceProvider sp = services.BuildServiceProvider();

var rates = sp.GetRequiredService<CurrencyRates>();
Console.WriteLine(rates.Get("EUR"));
Console.WriteLine(rates.Get("EUR"));
Console.WriteLine(ReferenceEquals(sp.GetRequiredService<IMemoryCache>(), sp.GetRequiredService<IMemoryCache>()));

sealed class CurrencyRates(IMemoryCache cache)
{
    public decimal Get(string currency) =>
        cache.GetOrCreate($"rate:{currency}", entry =>
        {
            Console.WriteLine($"  fetching {currency} rate");
            entry.SetAbsoluteExpiration(TimeSpan.FromMinutes(15)).SetSize(1);
            return 4.27m;
        });
}
  fetching EUR rate
4.27
4.27
True

In ASP.NET Core it's the same call: builder.Services.AddMemoryCache(). Since the whole app shares one cache, prefix keys with what they hold (rate:, user:) to avoid collisions between features.

Absolute and sliding expiration

An entry can expire in three ways:

#:package Microsoft.Extensions.Caching.Memory@10.0.13
using Microsoft.Extensions.Caching.Memory;

using var cache = new MemoryCache(new MemoryCacheOptions());

// Absolute: gone 300 ms after it was added, no matter how often it's read
cache.Set("absolute", "A", TimeSpan.FromMilliseconds(300));

// Sliding: gone after 300 ms *without reads*; every read restarts the timer
cache.Set("sliding", "S", new MemoryCacheEntryOptions
{
    SlidingExpiration = TimeSpan.FromMilliseconds(300)
});

// Sliding with an absolute cap: kept alive by reads, but never past 700 ms
cache.Set("capped", "C", new MemoryCacheEntryOptions
{
    SlidingExpiration = TimeSpan.FromMilliseconds(300),
    AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(700)
});

for (int t = 200; t <= 1000; t += 200)
{
    Thread.Sleep(200);
    string Show(string key) => cache.TryGetValue(key, out string? v) ? v! : "-";
    Console.WriteLine($"~{t,4} ms  absolute={Show("absolute")}  sliding={Show("sliding")}  capped={Show("capped")}");
}
~ 200 ms  absolute=A  sliding=S  capped=C
~ 400 ms  absolute=-  sliding=S  capped=C
~ 600 ms  absolute=-  sliding=S  capped=C
~ 800 ms  absolute=-  sliding=S  capped=-
~1000 ms  absolute=-  sliding=S  capped=-

The loop reads sliding every 200 ms, so it never expires. That's the danger of sliding expiration on its own: a popular entry is never refreshed and can stay stale forever. Use absolute expiration for data that changes, and add sliding expiration only to drop entries nobody uses earlier.

Expired entries aren't removed by a timer. A read notices that an entry has expired, and a background scan runs at most every ExpirationScanFrequency (default one minute) when the cache is used. Until then expired entries still take memory, but TryGetValue never returns them.

MemoryCacheOptions doesn't accept a TimeProvider. Its Clock option takes the older Microsoft.Extensions.Internal.ISystemClock interface, so tests that depend on expiration either wait or set Clock to a fake implementation of it.

Size limits, priorities and eviction callbacks

By default MemoryCache has no limit. It doesn't know how big your objects are, so if you need a limit you set SizeLimit in your own units (entries, kilobytes, rows) and give every entry a Size:

#:package Microsoft.Extensions.Caching.Memory@10.0.13
using Microsoft.Extensions.Caching.Memory;

using var cache = new MemoryCache(new MemoryCacheOptions
{
    SizeLimit = 100,            // units are whatever you decide, here: KB
    CompactionPercentage = 0.5, // when full, try to free half
    TrackStatistics = true
});

MemoryCacheEntryOptions Options(long sizeKb, CacheItemPriority priority = CacheItemPriority.Normal) =>
    new MemoryCacheEntryOptions { Size = sizeKb, Priority = priority }
        .RegisterPostEvictionCallback((key, value, reason, state) =>
            Console.WriteLine($"  evicted {key} ({reason})"));

cache.Set("logo", new byte[40_000], Options(40, CacheItemPriority.NeverRemove));
cache.Set("report-1", new byte[30_000], Options(30));
cache.Set("report-2", new byte[30_000], Options(30));
Console.WriteLine($"Count={cache.Count}, size={cache.GetCurrentStatistics()!.CurrentEstimatedSize}");

// Doesn't fit: the entry is rejected and compaction starts in the background
cache.Set("report-3", new byte[30_000], Options(30));
Thread.Sleep(100); // compaction and eviction callbacks run on the thread pool
Console.WriteLine($"report-3 cached: {cache.TryGetValue("report-3", out _)}");
Console.WriteLine($"Count={cache.Count}, size={cache.GetCurrentStatistics()!.CurrentEstimatedSize}");

cache.Set("report-3", new byte[30_000], Options(30));
Console.WriteLine($"retry: report-3 cached: {cache.TryGetValue("report-3", out _)}");

try
{
    cache.Set("no-size", "x");
}
catch (InvalidOperationException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}

MemoryCacheStatistics stats = cache.GetCurrentStatistics()!;
Console.WriteLine($"hits={stats.TotalHits} misses={stats.TotalMisses} entries={stats.CurrentEntryCount}");
Count=3, size=100
  evicted report-3 (Capacity)
  evicted report-2 (Capacity)
  evicted report-1 (Capacity)
report-3 cached: False
Count=1, size=40
retry: report-3 cached: True
InvalidOperationException: Cache entry must specify a value for Size when SizeLimit is set.
hits=1 misses=1 entries=2

What happened:

RegisterPostEvictionCallback runs for every removal, with reasons Removed, Replaced, Expired, TokenExpired and Capacity. Use it for logging or to dispose cached resources, and keep it short. It runs on a thread-pool thread. TrackStatistics = true turns on GetCurrentStatistics(), which reports hits, misses, entry count and estimated size, and is what the built-in cache metrics use.

The cache stampede problem

GetOrCreateAsync checks the cache, runs the factory on a miss, then stores the result. Nothing stops several callers from missing at the same moment and all running the factory:

#:package Microsoft.Extensions.Caching.Memory@10.0.13
using Microsoft.Extensions.Caching.Memory;

using var cache = new MemoryCache(new MemoryCacheOptions());
int calls = 0;

async Task<decimal> GetPriceAsync(string sku) =>
    await cache.GetOrCreateAsync($"price:{sku}", async entry =>
    {
        Interlocked.Increment(ref calls);
        entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1);
        await Task.Delay(200); // slow database query or HTTP call
        return 9.99m;
    });

// 20 requests arrive at the same moment, all for the same uncached key
decimal[] prices = await Task.WhenAll(Enumerable.Range(0, 20).Select(_ => GetPriceAsync("A-100")));
Console.WriteLine($"results: {prices.Length}, factory calls: {calls}");
results: 20, factory calls: 20

This is a cache stampede: a popular entry expires (or the app just started) and every in-flight request hits the database at once, right when it's busy. With a slow query and heavy traffic that can take a service down. IMemoryCache doesn't protect you. You either coordinate the callers yourself or use HybridCache.

Hand-rolled: ConcurrentDictionary and Lazy<Task>

The classic fix is to cache the task, not the value, and wrap it in Lazy<T> so only one factory ever starts per key:

using System.Collections.Concurrent;

var cache = new AsyncCache<string, decimal>();
int calls = 0;

Task<decimal> GetPriceAsync(string sku) =>
    cache.GetOrAddAsync(sku, async key =>
    {
        Interlocked.Increment(ref calls);
        await Task.Delay(200);
        return key == "BAD" ? throw new InvalidOperationException("db down") : 9.99m;
    });

decimal[] prices = await Task.WhenAll(Enumerable.Range(0, 20).Select(_ => GetPriceAsync("A-100")));
Console.WriteLine($"results: {prices.Length}, factory calls: {calls}");

for (int i = 0; i < 2; i++)
{
    try { await GetPriceAsync("BAD"); }
    catch (InvalidOperationException e) { Console.WriteLine($"attempt {i + 1}: {e.Message}"); }
}
Console.WriteLine($"factory calls: {calls}");

// One Lazy<Task<T>> per key: many callers may race to add it, but only the
// Lazy that wins is stored, and only its factory ever runs.
sealed class AsyncCache<TKey, TValue> where TKey : notnull
{
    private readonly ConcurrentDictionary<TKey, Lazy<Task<TValue>>> _items = new();

    public async Task<TValue> GetOrAddAsync(TKey key, Func<TKey, Task<TValue>> factory)
    {
        Lazy<Task<TValue>> lazy = _items.GetOrAdd(key,
            k => new Lazy<Task<TValue>>(() => factory(k)));
        try
        {
            return await lazy.Value;
        }
        catch
        {
            // Don't cache failures: remove this exact Lazy so the next caller retries
            _items.TryRemove(new KeyValuePair<TKey, Lazy<Task<TValue>>>(key, lazy));
            throw;
        }
    }

    public void Remove(TKey key) => _items.TryRemove(key, out _);
}
results: 20, factory calls: 1
attempt 1: db down
attempt 2: db down
factory calls: 3

Why each piece is there:

This is fine for a small, fixed set of keys (configuration, a few lookup tables). It has no expiration, no size limit and no cancellation, though. You can store Lazy<Task<T>> inside IMemoryCache to get expiration, but then you're building HybridCache by hand.

HybridCache: get-or-create with stampede protection

HybridCache (package Microsoft.Extensions.Caching.Hybrid, released with .NET 9; the package also targets .NET 8, .NET Standard 2.0 and .NET Framework 4.6.2) is an abstract class you get from DI after calling AddHybridCache. Its main method is GetOrCreateAsync, and concurrent calls for the same key share a single factory call:

#:package Microsoft.Extensions.Caching.Hybrid@10.11.0
#:package Microsoft.Extensions.DependencyInjection@10.0.13
#:property PublishAot=false
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddHybridCache(o =>
{
    o.DefaultEntryOptions = new HybridCacheEntryOptions
    {
        Expiration = TimeSpan.FromMinutes(10),         // overall lifetime (L2)
        LocalCacheExpiration = TimeSpan.FromMinutes(2) // in-process copy (L1)
    };
});
services.AddSingleton<ProductService>();
using ServiceProvider sp = services.BuildServiceProvider();

var products = sp.GetRequiredService<ProductService>();

// 20 concurrent requests for the same uncached key
Product[] results = await Task.WhenAll(
    Enumerable.Range(0, 20).Select(_ => products.GetAsync(7).AsTask()));
Console.WriteLine($"results: {results.Length}, database calls: {products.DbCalls}");
Console.WriteLine(results[0]);

// Later requests are served from the cache
await products.GetAsync(7);
Console.WriteLine($"database calls: {products.DbCalls}");

sealed class ProductService(HybridCache cache)
{
    private int _dbCalls;
    public int DbCalls => _dbCalls;

    public ValueTask<Product> GetAsync(int id, CancellationToken ct = default) =>
        cache.GetOrCreateAsync(
            $"product:{id}",
            async cancel => await LoadFromDbAsync(id, cancel),
            cancellationToken: ct);

    private async Task<Product> LoadFromDbAsync(int id, CancellationToken ct)
    {
        Interlocked.Increment(ref _dbCalls);
        await Task.Delay(200, ct);
        return new Product(id, "Mechanical keyboard", 129.00m);
    }
}

public record Product(int Id, string Name, decimal Price);
results: 20, database calls: 1
Product { Id = 7, Name = Mechanical keyboard, Price = 129.00 }
database calls: 1

Things to know:

In ASP.NET Core you call builder.Services.AddHybridCache() and inject HybridCache the same way.

Tags, removal and write-through

Entries can carry tags, and RemoveByTagAsync invalidates every entry with a tag. RemoveAsync removes single keys and SetAsync stores a value without a factory:

#:package Microsoft.Extensions.Caching.Hybrid@10.11.0
#:package Microsoft.Extensions.DependencyInjection@10.0.13
#:property PublishAot=false
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddHybridCache();
using ServiceProvider sp = services.BuildServiceProvider();
HybridCache cache = sp.GetRequiredService<HybridCache>();

var db = new FakeDb();
var shortLived = new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(1) };

// The state overload passes (db, id) to a static lambda: no closure allocation
ValueTask<Order> GetOrderAsync(int customerId, int orderId) =>
    cache.GetOrCreateAsync(
        $"order:{orderId}",
        (db, orderId),
        static (state, ct) => state.db.LoadOrderAsync(state.orderId, ct),
        shortLived,
        tags: [$"customer:{customerId}", "orders"]);

await GetOrderAsync(1, 100);
await GetOrderAsync(1, 101);
await GetOrderAsync(2, 200);
Console.WriteLine($"loads so far: {db.Loads}");

await GetOrderAsync(1, 100);
await GetOrderAsync(2, 200);
Console.WriteLine($"after cached reads: {db.Loads}");

// Customer 1 changed: drop everything tagged with it
await cache.RemoveByTagAsync("customer:1");
await GetOrderAsync(1, 100);   // reload
await GetOrderAsync(1, 101);   // reload
await GetOrderAsync(2, 200);   // still cached
Console.WriteLine($"after RemoveByTagAsync(customer:1): {db.Loads}");

// One key
await cache.RemoveAsync("order:200");
await GetOrderAsync(2, 200);
Console.WriteLine($"after RemoveAsync(order:200): {db.Loads}");

// Write-through: put a fresh value without running a factory
await cache.SetAsync("order:200", new Order(200, "shipped"), shortLived, tags: ["customer:2", "orders"]);
Console.WriteLine(await GetOrderAsync(2, 200));

// "*" matches every entry in the cache
await cache.RemoveByTagAsync("*");
await GetOrderAsync(2, 200);
Console.WriteLine($"after RemoveByTagAsync(*): {db.Loads}");

// Values are serialized, so each caller gets its own copy
Order a = await GetOrderAsync(1, 100);
a.Status = "hacked";
Order b = await GetOrderAsync(1, 100);
Console.WriteLine($"a.Status={a.Status}, b.Status={b.Status}, same object: {ReferenceEquals(a, b)}");

sealed class FakeDb
{
    public int Loads;
    public async ValueTask<Order> LoadOrderAsync(int id, CancellationToken ct)
    {
        Loads++;
        await Task.Delay(10, ct);
        return new Order(id, "new");
    }
}

public class Order(int id, string status)
{
    public int Id { get; set; } = id;
    public string Status { get; set; } = status;
    public override string ToString() => $"Order {Id}: {Status}";
}
loads so far: 3
after cached reads: 3
after RemoveByTagAsync(customer:1): 5
after RemoveAsync(order:200): 6
Order 200: shipped
after RemoveByTagAsync(*): 7
a.Status=hacked, b.Status=new, same object: False

Tag removal doesn't scan the cache. HybridCache records an invalidation timestamp for the tag, and on each read it treats entries created before that timestamp as misses. That keeps RemoveByTagAsync cheap even with many entries. With an L2 configured, the timestamp is also written there so other servers see it, which you'll see in the next example.

The last lines show a difference from IMemoryCache: HybridCache keeps the serialized bytes and deserializes a new object for each caller, so mutating a returned object can't corrupt the cache. That costs a deserialization per hit. If your type is immutable, mark it sealed and [ImmutableObject(true)] (from System.ComponentModel), and the L1 cache reuses one instance:

#:package Microsoft.Extensions.Caching.Hybrid@10.11.0
#:package Microsoft.Extensions.DependencyInjection@10.0.13
#:property PublishAot=false
using System.ComponentModel;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddHybridCache();
using ServiceProvider sp = services.BuildServiceProvider();
HybridCache cache = sp.GetRequiredService<HybridCache>();

var p1 = await cache.GetOrCreateAsync("p", _ => ValueTask.FromResult(new Price("A-100", 9.99m)));
var p2 = await cache.GetOrCreateAsync("p", _ => ValueTask.FromResult(new Price("A-100", 0m)));
Console.WriteLine($"Price: same object: {ReferenceEquals(p1, p2)}");

var f1 = await cache.GetOrCreateAsync("f", _ => ValueTask.FromResult(new FrozenPrice("A-100", 9.99m)));
var f2 = await cache.GetOrCreateAsync("f", _ => ValueTask.FromResult(new FrozenPrice("A-100", 0m)));
Console.WriteLine($"FrozenPrice: same object: {ReferenceEquals(f1, f2)}");

public record Price(string Sku, decimal Amount);

[ImmutableObject(true)]
public sealed record FrozenPrice(string Sku, decimal Amount);
Price: same object: False
FrozenPrice: same object: True

string and primitive values are always reused.

Failures and read-only lookups

An exception thrown by the factory goes to every waiting caller and is not cached, so the next call tries again. HybridCacheEntryFlags switch off parts of the pipeline per call. DisableUnderlyingData turns GetOrCreateAsync into a lookup that never runs the factory:

#:package Microsoft.Extensions.Caching.Hybrid@10.11.0
#:package Microsoft.Extensions.DependencyInjection@10.0.13
#:property PublishAot=false
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddHybridCache();
using ServiceProvider sp = services.BuildServiceProvider();
HybridCache cache = sp.GetRequiredService<HybridCache>();

int calls = 0;
for (int i = 1; i <= 2; i++)
{
    try
    {
        string w = await cache.GetOrCreateAsync("weather:krakow", async ct =>
        {
            calls++;
            await Task.Delay(10, ct);
            if (calls == 1) throw new HttpRequestException("503 Service Unavailable");
            return "sunny";
        });
        Console.WriteLine($"attempt {i}: {w}");
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine($"attempt {i}: {e.Message}");
    }
}

// Read-only lookup: never run the factory, return default(T) on a miss
var peek = new HybridCacheEntryOptions { Flags = HybridCacheEntryFlags.DisableUnderlyingData };
string? hit = await cache.GetOrCreateAsync("weather:krakow", _ => ValueTask.FromResult<string?>(null), peek);
string? miss = await cache.GetOrCreateAsync("weather:oslo", _ => ValueTask.FromResult<string?>(null), peek);
Console.WriteLine($"krakow: {hit ?? "(not cached)"}, oslo: {miss ?? "(not cached)"}");
attempt 1: 503 Service Unavailable
attempt 2: sunny
krakow: sunny, oslo: (not cached)

Other flags are DisableLocalCache (always go to L2, useful for values that must be consistent across servers), DisableDistributedCache (in-process only for this entry) and DisableCompression.

Adding an L2 distributed cache

If an IDistributedCache is registered in DI, HybridCache uses it as the second level automatically. A read checks L1, then L2, and only then runs the factory. New values are written to both levels. With several servers, one server's factory result is reused by the others through L2, and a restarted server starts with a warm cache.

In production L2 is usually Redis (not run here, since it needs a Redis server; see Redis for a run with a real server):

// package Microsoft.Extensions.Caching.StackExchangeRedis
builder.Services.AddStackExchangeRedisCache(o => o.Configuration = "localhost:6379");
builder.Services.AddHybridCache();

To watch what happens without a server, the next example uses an in-process substitute. Two HybridCache instances play two servers and share one IDistributedCache. That cache is a MemoryDistributedCache wrapped in a decorator that logs every L2 call. The wrapper also matters for another reason: HybridCache deliberately ignores a plain MemoryDistributedCache (from AddDistributedMemoryCache), because an in-memory L2 in the same process would add nothing.

#:package Microsoft.Extensions.Caching.Hybrid@10.11.0
#:package Microsoft.Extensions.Caching.Memory@10.0.13
#:package Microsoft.Extensions.DependencyInjection@10.0.13
#:property PublishAot=false
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

// Stands in for Redis: one store shared by both "servers"
var sharedL2 = new LoggingDistributedCache(
    new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())));

HybridCache NewServer()
{
    var services = new ServiceCollection();
    services.AddSingleton<IDistributedCache>(sharedL2); // HybridCache picks this up as L2
    services.AddHybridCache(o => o.DefaultEntryOptions = new HybridCacheEntryOptions
    {
        Expiration = TimeSpan.FromMinutes(10),
        LocalCacheExpiration = TimeSpan.FromSeconds(30)
    });
    return services.BuildServiceProvider().GetRequiredService<HybridCache>();
}

HybridCache serverA = NewServer(), serverB = NewServer();

async Task<string> Get(HybridCache server, string name) =>
    await server.GetOrCreateAsync("config:theme", async ct =>
    {
        Console.WriteLine($"  [{name}] factory runs (database query)");
        await Task.Delay(50, ct);
        return "dark";
    });

Console.WriteLine("A, first call:");
Console.WriteLine($"  -> {await Get(serverA, "A")}");
Console.WriteLine("A, second call:");
Console.WriteLine($"  -> {await Get(serverA, "A")}");
Console.WriteLine("B, first call:");
Console.WriteLine($"  -> {await Get(serverB, "B")}");

Console.WriteLine("A removes the key:");
await serverA.RemoveAsync("config:theme");
Console.WriteLine("B, after A's remove:");
Console.WriteLine($"  -> {await Get(serverB, "B")}");

sealed class LoggingDistributedCache(IDistributedCache inner) : IDistributedCache
{
    static void Log(string op, string key, byte[]? data = null) =>
        Console.WriteLine($"  L2 {op} {key}{(data is null ? "" : $" ({data.Length} bytes)")}");

    public byte[]? Get(string key) => GetAsync(key).GetAwaiter().GetResult();
    public async Task<byte[]?> GetAsync(string key, CancellationToken token = default)
    {
        byte[]? data = await inner.GetAsync(key, token);
        Log(data is null ? "miss" : "hit ", key, data);
        return data;
    }
    public void Set(string key, byte[] value, DistributedCacheEntryOptions options) =>
        SetAsync(key, value, options).GetAwaiter().GetResult();
    public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default)
    {
        Log("set ", key, value);
        return inner.SetAsync(key, value, options, token);
    }
    public void Refresh(string key) => inner.Refresh(key);
    public Task RefreshAsync(string key, CancellationToken token = default) => inner.RefreshAsync(key, token);
    public void Remove(string key) => RemoveAsync(key).GetAwaiter().GetResult();
    public Task RemoveAsync(string key, CancellationToken token = default)
    {
        Log("del ", key);
        return inner.RemoveAsync(key, token);
    }
}
  L2 miss __MSFT_HCT__*
  L2 miss __MSFT_HCT__*
A, first call:
  L2 miss config:theme
  [A] factory runs (database query)
  L2 set  config:theme (39 bytes)
  -> dark
A, second call:
  -> dark
B, first call:
  L2 hit  config:theme (39 bytes)
  -> dark
A removes the key:
  L2 del  config:theme
B, after A's remove:
  -> dark

Reading the log:

Which one to use

Need Use
Cache objects in one process, synchronous code, full control over size and eviction IMemoryCache
Async loads where many requests miss the same key (stampede protection) HybridCache
Invalidate groups of entries (per user, per tenant, everything) HybridCache tags
Share cached values between servers or survive restarts HybridCache + IDistributedCache (Redis, SQL Server, ...)
Callers must not be able to mutate the cached value HybridCache (copies), or immutable types with either
A handful of fixed keys loaded once, no expiration ConcurrentDictionary<TKey, Lazy<Task<T>>>

Whichever you pick, give every entry an absolute expiration, include everything that affects the result in the key (product:{id}:{culture}), and don't cache per-user data under a shared key.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents