Skip to content

[API Proposal]: Specify L1 memory usage in HybridCache #114366

Closed

Description

@bebo-dot-dev

Description

HybridCache and HybridCacheEntryOptions currently has no support for assigning a size to cached items to enable HybridCache to work in harmony with MemoryCacheOptions.SizeLimit.

This means that use of L1 cache with HybridCache FusionHybridCache results in unbounded memory use and this is the issue that we're currently experiencing when using HybridCache FusionHybridCache

In addition HybridCacheEntryOptions is sealed which prevents other implementers of HybridCache (i.e. FusionCache) from extending HybridCacheEntryOptions to support size.

API Proposal (added by @svick)

A new HybridCacheEntryContext class is passed to the factory callback, allowing it to set L1 cache entry size at runtime. This type is shared with #121530 (dynamic expiration / negative cache support).

Just adding this property to HybridCacheEntryOptions would not work well, because the size is often not known before the factory runs.

namespace Microsoft.Extensions.Caching.Hybrid;

public sealed class HybridCacheEntryContext
{
    public HybridCacheEntryContext(HybridCacheEntryOptions currentOptions);

    public HybridCacheEntryOptions CurrentOptions { get; }

    public long? LocalCacheSize { get; set; }

    // Proposed in #121530:
    // public TimeSpan? Expiration { get; set; }
    // public TimeSpan? LocalCacheExpiration { get; set; }
    // public HybridCacheEntryFlags? Flags { get; set; }
}

public partial sealed class HybridCacheEntryOptions
{
    public long? LocalCacheSize { get; init; }

    // Existing:
    // public TimeSpan? Expiration { get; init; }
    // public TimeSpan? LocalCacheExpiration { get; init; }
    // public HybridCacheEntryFlags? Flags { get; init; }
}

The unit of LocalCacheSize is unspecified (similar to what IMemoryCache does). For the default implementation, the unit used by default is bytes of the serialized form of the cache item. The sentinel value of -1 can be used to reset the size back to the default of "determined by HybridCache".

New GetOrCreateAsync overloads on HybridCache accept a factory that receives the context . These mirror the 6 existing overloads (except for abstract → virtual) and are shared with #121530:

namespace Microsoft.Extensions.Caching.Hybrid;

public partial abstract class HybridCache
{
    // New core overload
    public virtual ValueTask<T> GetOrCreateAsync<TState, T>(
        string key, TState state,
        Func<TState, HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory,
        HybridCacheEntryOptions? options = null,
        IEnumerable<string>? tags = null,
        CancellationToken cancellationToken = default);

    // Convenience (no TState)
    public ValueTask<T> GetOrCreateAsync<T>(
        string key,
        Func<HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory,
        HybridCacheEntryOptions? options = null,
        IEnumerable<string>? tags = null,
        CancellationToken cancellationToken = default);

#if NET
    // ReadOnlySpan<char> key variants
    public virtual ValueTask<T> GetOrCreateAsync<TState, T>(
        ReadOnlySpan<char> key, TState state,
        Func<TState, HybridCacheFactoryContext, CancellationToken, ValueTask<T>> factory,
        HybridCacheEntryOptions? options = null,
        IEnumerable<string>? tags = null,
        CancellationToken cancellationToken = default);

    public ValueTask<T> GetOrCreateAsync<T>(
        ReadOnlySpan<char> key,
        Func<HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory,
        HybridCacheEntryOptions? options = null,
        IEnumerable<string>? tags = null,
        CancellationToken cancellationToken = default);

    // DefaultInterpolatedStringHandler key variants
    public ValueTask<T> GetOrCreateAsync<TState, T>(
        ref DefaultInterpolatedStringHandler key, TState state,
        Func<TState, HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory,
        HybridCacheEntryOptions? options = null,
        IEnumerable<string>? tags = null,
        CancellationToken cancellationToken = default);

    public ValueTask<T> GetOrCreateAsync<T>(
        ref DefaultInterpolatedStringHandler key,
        Func<HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory,
        HybridCacheEntryOptions? options = null,
        IEnumerable<string>? tags = null,
        CancellationToken cancellationToken = default);
#endif
}

API Usage (added by @svick)

var user = await cache.GetOrCreateAsync($"users/{id}", async (ctx, ct) =>
{
    var user = await db.GetUserAsync(id, ct);
    ctx.LocalCacheSize = user.ProfileImageBytes.Length + user.Name.Length * 2;
    return user;
});

Alternative Designs (added by @svick)

  • Should HybridCacheEntryContext and HybridCacheEntryOptions be the same class? Should they have some inheritance relationship? Doing that would be awkward, because HybridCacheEntryOptions is effectively immutable, while HybridCacheEntryContext has to be mutable.
  • Should LocalCacheSize have a different name, since it could be understood as the size of the entire local cache, not the size in the local cache (of the current entry). It was chosen to follow HybridCacheEntryOptions.LocalCacheExpiration.
  • Since knowing the size of a cache item is comparable to serializing it, should there be IHybridCacheSizeProvider<T>/IHybridCacheSizeProviderFactory, mirroring IHybridCacheSerializer<T>/IHybridCacheSerializerFactory instead or in addition to HybridCacheEntryContext.LocalCacheSize?

Risks (added by @svick)

  • LocalCacheSize units are implementation-defined (matching Microsoft.Extensions.Caching.Memory.ICacheEntry.Size), which may cause confusion.
  • The default virtual implementation ignores the context for backward compatibility — existing HybridCache subclasses must override the new overload to honor LocalCacheSize.

Activity

  1. added
    tenet-performance
    on Apr 8, 2025
  2. added
    untriaged
    on Apr 8, 2025
  3. dotnet-policy-service commented on Apr 8, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-extensions-caching
    See info in area-owners.md if you want to be subscribed.

  4. mgravell commented on Apr 9, 2025

    @mgravell
    Contributor

    On size: the dotnet/extensions version of HybridCache uses the serialized payload size to assign a value for size; it should already "just work"; could you perhaps expand on what you're seeing?

  5. self-assigned this
    on Apr 9, 2025
  6. bebo-dot-dev commented on Apr 9, 2025

    @bebo-dot-dev
    Author

    On size: the dotnet/extensions version of HybridCache uses the serialized payload size to assign a value for size; it should already "just work; could you perhaps expand on what you're seeing?"

    Using FusionCache as HybridCache is where we had an issue with unbounded MemoryCache memory usage because there's currently no way to specify Size through HybridCacheEntryOptions and the FusionCache flavour of HybridCache doesn't perform any automatic determination of cache item size.

    What you said about the .NET HybridCache using serialized payload size for cache item Size is interesting because FusionCache doesn't do this. On the the face it, FusionHybridCache has different behaviour to how the .NET HybridCache behaves around cache item Size.

    However having said that automatic calculation/determination of Size for L1 cache items seems to go against the MemoryCache docs which say:

    The cache size limit doesn't have a defined unit of measure because the cache has no mechanism to measure the size of entries.

    and also

    SizeLimit doesn't have units. Cached entries must specify size in whatever units they consider most appropriate if the cache size limit has been set. All users of a cache instance should use the same unit system.

    To put this another way the docs suggest that once a SizeLimit of arbitrary units has been assigned to a MemoryCache via MemoryCacheOptions, the onus is on the caller when adding an item to the cache to set Size on a cache item to an appropriate size of arbitrary units. I suppose the arbitrary unit system in use could mean / be equal to the serialized cache item size in bytes or I guess it could be something else entirely.

    It might be ideal if both SizeLimit and Size could be trusted to be bytes and considered to always be bytes because automatic determination/calculation of Size would then work. This isn't what the MemoryCache docs say today however so there seems to be a gap in the HybridCache API surface because there's no way to pass Size through HybridCacheOptions.

    So perhaps this really is a problem or possibly the the MemoryCache docs are wrong, the HybridCacheOptions code contract is fine as it stands and FusionCache needs to trust that SizeLimit and Size are bytes and determine Size at runtime based on the size of a cache item in bytes?

  7. mgravell commented on Apr 9, 2025

    @mgravell
    Contributor

    It is perhaps something we should explore. Putting the size on the options is awkward because it isn't necessarily try that you know the size in advance - it could be hugely contextual (when I was at Stack Overflow, we called this the "Jon Skeet problem" - some data could be heavily skewed based on the inputs) If anything, I wonder whether this ties into some other topics like setting the expiration based on the payload. Kind of like:

    var blah = cache.GetOrCreateAsync($"foos/{region}/{id}", async ctx => {
        // blah await blah
        ctx.Size = 42; // if not done, uses existing approach
        ctx.CacheDuration = TimeSpan.FromMinutes(10); // defaults to time via options
    
        return someValue;
    });

    The problem is how to squeeze this into the existing API without causing ambiguity; we already have overloads that take Func<CancellationToken, ValueTask<T>> and Func<TState, CancellationToken, ValueTask<T>>, so to avoid lambda ambiguity, we'd need to use a triplet arg - something like:

    var blah = cache.GetOrCreateAsync($"foos/{region}/{id}", (region, id), async (ctx, state, ct) => {
        // blah await blah
        ctx.Size = 42; // if not done, uses existing approach
        ctx.CacheDuration = TimeSpan.FromMinutes(10); // defaults to time via options
    
        return someValue;
    });

    Where ctx here is some CacheContext type.


    Another approach might be to have an IHybridCacheItem interface that the result T could optionally implement, allowing the existing API to pass some values back out, for example:

    [ImmutableObject(true)] // enables L1 object reuse, i.e. don't deserialize repeatedly
    sealed class CustomerCacheItem(int id, string name, ...) : IHybridCacheItem
    {
        int? IHybridCacheItem.Size => 100 * orders.Length;
        TimeSpan IHybridCacheItem.CacheDuration => IsVIP ? TimeSpan.FromMinutes(1) : TimeSpan.FromMinutes(10);
    }

    with the library type-testing for IHybridCacheItem and applying things on the way out.


    I'm just thinking aloud here; all input welcome.

  8. mgravell commented on Apr 9, 2025

    @mgravell
    Contributor

    I also tried some things with [OverloadResolutionPriority], which works-ish, but is a pain because we can't use partial naming in the lambda; we can get (CacheContext ctx) => ... to be preferred, but we can't do (TState state, CacheContext ctx) without explicitly naming the TState, which is usually inconvenient and sometimes impossible; of course, we could just use a different name:

    using Microsoft.Extensions.Caching.Hybrid;
    
    var obj = new Foo();
    int id = 42;
    string name = "abc";
    var x = await obj.GetOrCreateAsync($"foos/{id}/{name}", async ct => await GetAsync(id, ct));
    var y = await obj.GetOrCreateAsync($"foos/{id}/{name}", (id, name), static async (state, ct) => await GetAsync(state.id, ct));
    var z = await obj.GetOrCreateAsync2($"foos/{id}/{name}", (id, name), static async (state, ctx) =>
    {
        var value = await GetAsync(42, ctx.CancellationToken);
        ctx.Size = 100 * value.Length;
        ctx.CacheDuration = TimeSpan.FromSeconds(10);
        return value;
    });
    
    
    static ValueTask<string> GetAsync(int i, CancellationToken cancellationToken = default) => default;
    class Foo
    {
    
        public ValueTask<T> GetOrCreateAsync<T>(string key, Func<CancellationToken, ValueTask<T>> factory,
            HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default)
            => default;
        public ValueTask<T> GetOrCreateAsync<T, TState>(string key, TState state, Func<TState, CancellationToken, ValueTask<T>> factory,
            HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default)
            => default;
    
        public ValueTask<T> GetOrCreateAsync2<T, TState>(string key, TState state, Func<TState, CacheContext, ValueTask<T>> factory,
            HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default)
            => default;
    }
    public class CacheContext(CancellationToken cancellationToken, TimeSpan cacheDuration)
    {
        public int? Size { get; set; }
        public TimeSpan CacheDuration { get; set; } = cacheDuration;
        public CancellationToken CancellationToken => cancellationToken; 
    }
  9. jodydonetti commented on Apr 9, 2025

    @jodydonetti
    Contributor

    Hi @bebo-dot-dev

    Using FusionCache as HybridCache is where we had an issue with unbounded MemoryCache memory usage because there's currently no way to specify Size through HybridCacheEntryOptions and the FusionCache flavour of HybridCache doesn't perform any automatic determination of cache item size.

    What you said about the .NET HybridCache using serialized payload size for cache item Size is interesting because FusionCache doesn't do this.

    That's because... I didn't know about such behaviour 😅

    @mgravell is it documented somewhere, just to be sure I can implement it in the right way? It's "just" the "length in bytes"?

    Also, that's because serialization may not happen without L2: I know HC serialize always, even with just L1, to avoid returning a "live instance", but what if that is disabled? Btw: I remember it being a possibility, I mean to disable the auto cloning, is this still a thing in the GA version?

    On the the face it, FusionHybridCache has different behaviour to how the .NET HybridCache behaves around cache item Size.

    If desired and if there's a "spec" or similar I can of course align the impl, more than happy to have the same behaviour as much as possible!

    However having said that automatic calculation/determination of Size for L1 cache items seems to go against the MemoryCache docs which say:
    [...]
    To put this another way the docs suggest that once a SizeLimit of arbitrary units has been assigned to a MemoryCache via MemoryCacheOptions, the onus is on the caller when adding an item to the cache to set Size on a cache item to an appropriate size of arbitrary units. I suppose the arbitrary unit system in use could mean / be equal to the serialized cache item size in bytes or I guess it could be something else entirely.

    Yeah I guess (my 2 cents) it can be a defined behaviour, something like "when using HC the Size is calculated this way, that's it".
    Or, at least, it can be the default in case it's something that Marc & the team want to change this.

    It might be ideal if both SizeLimit and Size could be trusted to be bytes and considered to always be bytes because automatic determination/calculation of Size would then work. This isn't what the MemoryCache docs say today however so there seems to be a gap in the HybridCache API surface because there's no way to pass Size through HybridCacheOptions.

    Because as of today the underlying MemoryCache is taken from the DI container as-is, so it can't change it after getting it and/or it's there (during DI setup) where you may configure it.

    Thoughts?

  10. jodydonetti commented on Apr 9, 2025

    @jodydonetti
    Contributor

    It is perhaps something we should explore. Putting the size on the options is awkward because it isn't necessarily try that you know the size in advance - it could be hugely contextual (when I was at Stack Overflow, we called this the "Jon Skeet problem" - some data could be heavily skewed based on the inputs) If anything, I wonder whether this ties into some other topics like setting the expiration based on the payload. Kind of like:

    var blah = cache.GetOrCreateAsync($"foos/{region}/{id}", async ctx => {
    // blah await blah
    ctx.Size = 42; // if not done, uses existing approach
    ctx.CacheDuration = TimeSpan.FromMinutes(10); // defaults to time via options

    return someValue;
    

    });
    The problem is how to squeeze this into the existing API without causing ambiguity; we already have overloads that take Func<CancellationToken, ValueTask<T>> and Func<TState, CancellationToken, ValueTask<T>>, so to avoid lambda ambiguity, we'd need to use a triplet arg - something like:

    var blah = cache.GetOrCreateAsync($"foos/{region}/{id}", (region, id), async (ctx, state, ct) => {
    // blah await blah
    ctx.Size = 42; // if not done, uses existing approach
    ctx.CacheDuration = TimeSpan.FromMinutes(10); // defaults to time via options

    return someValue;
    

    });
    Where ctx here is some CacheContext type.

    FWIW that's what I did in FusionCache (see Adaptive Caching), anche the community likes that a lot.

    Another approach might be to have an IHybridCacheItem interface that the result T could optionally implement, allowing the existing API to pass some values back out, for example:

    [ImmutableObject(true)] // enables L1 object reuse, i.e. don't deserialize repeatedly
    sealed class CustomerCacheItem(int id, string name, ...) : IHybridCacheItem
    {
    int? IHybridCacheItem.Size => 100 * orders.Length;
    TimeSpan IHybridCacheItem.CacheDuration => IsVIP ? TimeSpan.FromMinutes(1) : TimeSpan.FromMinutes(10);
    }
    with the library type-testing for IHybridCacheItem and applying things on the way out.

    I'm just thinking aloud here; all input welcome.

    Correct, that's another approach, but this limits it to types "owned" but the caller, and a lot of times the adaptability is not based on the type but on usage, meaning that I may want that with a cache entry of type int, string, etc, not necessarily my own Person class.

    My 2 cents.

  11. jodydonetti commented on Apr 9, 2025

    @jodydonetti
    Contributor

    However having said that automatic calculation/determination of Size for L1 cache items seems to go against the MemoryCache docs which say:
    [...]
    It might be ideal if both SizeLimit and Size could be trusted to be bytes and considered to always be bytes because automatic determination/calculation of Size would then work. This isn't what the MemoryCache docs say today however so there seems to be a gap in the HybridCache API surface because there's no way to pass Size through HybridCacheOptions.

    So perhaps this really is a problem or possibly the the MemoryCache docs are wrong, the HybridCacheOptions code contract is fine as it stands and FusionCache needs to trust that SizeLimit and Size are bytes and determine Size at runtime based on the size of a cache item in bytes?

    Anyway this is, in fact, quite delicate: deciding on something specific may reduce flexibility quite a bit, in case that's then needed... some brainstorming needed here...

  12. bebo-dot-dev commented on Apr 9, 2025

    @bebo-dot-dev
    Author

    Having read more docs, my takeaway is that the .NET HybridCache docs confirm that the .NET HybridCache uses the same MemoryCache for L1 that FusionCache also uses.

    At the same time the .NET HybridCache manages to satisfy the rules of the MemoryCache docs and assume that the serialized payload size of a cache item is a valid value for Size for an item stored in L1 cache.

    What is interesting is that there's no mention in the .NET HybridCache docs how / where the L1 MemoryCache SizeLimit is set or where the responsibility for doing this lies so it's not 100% clear what MemoryCache "arbitrary units" means to the .NET HybridCache. However since it's able to work in bytes and use the serialized payload size of a cache item, I assume that it in it's own view, SizeLimit and Size are trusted to be bytes and considered to always be bytes and it's this which enables it to work the way that it does around sizing cache items in L1.

    I think I'm with you @jodydonetti, there may be a "spec" somewhere or perhaps codified rules baked into the .NET HybridCache that explain how it manages to work the way that it does with MemoryCache.

  13. jodydonetti commented on Apr 9, 2025

    @jodydonetti
    Contributor

    Having read more docs, my takeaway is that the .NET HybridCache docs confirm that the .NET HybridCache uses the same MemoryCache for L1 that FusionCache also uses.

    Yup, can confirm.

    Or, to be more precise (nitpicking corner here): both HybridCache and (current) FusionCache both use IMemoryCache as the L1, not necessarily the same instance if you use them both together for whatever reasons.

    HybridCache (currently) always uses the IMemoryCache instance returned via DI, while FusionCache can use that, or can accept a different instance provided by the user or via a builder, etc (see here).

    Just wanted to point out it's not "the same" instance.

    What is interesting is that there's no mention in the .NET HybridCache docs how / where the L1 MemoryCache SizeLimit is set or where the responsibility for doing this lies so it's not 100% clear what MemoryCache "arbitrary units" means to the .NET HybridCache. However since it's able to work in bytes and use the serialized payload size of a cache item, I assume that it in it's own view, SizeLimit and Size are trusted to be bytes and considered to always be bytes and it's this which enables it to work the way that it does around sizing cache items in L1.

    @mgravell can correct me if I'm wrong, but I think that he set the Size in each cache entry so that, IF a user has set a SizeLimit on the DI-provided IMemoryCache, HybridCache would not start throwing exceptions (that is what happens with MemoryCache when you set a SizeLimit but fail to provide a Size for even 1 cache entry.

    Meaning: if, as is the default, a SizeLimit is not configured -> nothing happens anyway.

    On my hand instead (FusionCache), you can specify an IMemoryCache instance, and maybe set a SizeLimit: if you do so, you then MUST set some Size, otherwise you'd be asking to set a limit without providing a way to check that limit.

    I think I'm with you @jodydonetti, there may be a "spec" somewhere or perhaps codified rules baked into the .NET HybridCache that explain how it manages to work the way that it does with MemoryCache.

    Yes that would be nice.

    Anyway, and maybe not the best place here (but it may be interesting for future 3rd party HC impls), when using the FC-HC adapter, the initial setup is the FC one (meaning: more control over which L1 to use etc), so my question is: would it make sense to add support for automatically calculating the Size based on the binary payload size in bytes or not? With FC you can avoid the forced serialization, and therefore there would be no bytes to count... so?

    Any thoughts may be helpful on both sides, and future 3rd party implementers.

  14. bebo-dot-dev commented on Apr 9, 2025

    @bebo-dot-dev
    Author

    Meaning: if, as is the default, a SizeLimit is not configured -> nothing happens anyway.

    Many things are not known to me but there is one thing that I know for certain; if something doesn't set a SizeLimit on MemoryCache it is a surefire way to using all available memory. I found this out the hard way just a few days ago 😊

  15. 25 remaining items

  16. added this to the 11.0.0 milestone on Apr 23, 2026
  17. jodydonetti commented on Apr 25, 2026

    @jodydonetti
    Contributor

    Hi @svick , I'll try to take some time to read this in the next few days.

  18. jodydonetti commented on May 4, 2026

    @jodydonetti
    Contributor

    Hi @svick , sorry for the delay: comments below.

    I also try to provide a bit of background about how I approached things in FusionCache (FC), how I solved/planned to solve the current limitations and how things may play out with the HybridCache (HC) adapter along with some docs links you may find useful.

    Description

    HybridCache and HybridCacheEntryOptions currently has no support for assigning a size to cached items to enable HybridCache to work in harmony with MemoryCacheOptions.SizeLimit.

    This means that use of L1 cache with FusionHybridCache results in unbounded memory use and this is the issue that we're currently experiencing when using HybridCache FusionHybridCache

    Background: in FC I have FusionCacheEntryOptions (basically the same as HybridCacheEntryOptions) and that contains a Size option.

    This, coupled with the DefaultEntryOptions & related inheritance mechanism, allows users to at least set a default Size for each entry, even when using FC as a HC implementation via the adapter.

    Also, 2 things:

    • the overall ability to adapt entry options based on the factory result is known in FC as adaptive caching
    • entry options in FC are not immutable, so keep that in mind

    People asked me to add support for changing the Size via adaptive caching even when using the HC adapter: on one hand I waited to see if the abstraction would've been evolved (basically: this thread) and on the other I planned a contingency plan to allow users to specify a lambda when setting up the adapter: since it would have been a "global" thing, it probably would have had a signature based on object to make it work with any cached value type, but... potential boxing, not-so-good ergonomics, etc and I waited to do it for now.

    In addition HybridCacheEntryOptions is sealed which prevents other implementers of HybridCache (i.e. FusionCache) from extending HybridCacheEntryOptions to support size.

    API Proposal (added by @svick)

    A new HybridCacheEntryContext class is passed to the factory callback, allowing it to set L1 cache entry size at runtime. This type is shared with #121530 (dynamic expiration / negative cache support).

    This would be similar to my approach, where to support adaptive caching I added a FusionCacheFactoryExecutionContext<TValue> type.

    My approach used generics because I also wanted to support accessing the existing stale value (if any) because of fail-safe, factory timeouts & friends: since I don't think HC will go in that direction, you are probably ok in just using a non-generic class and call it a day (but I may be wrong).

    Adding this property to HybridCacheEntryOptions would not work well, because the size is often not known before the factory runs.

    Yes and no, meaning: yes, more frequently the Size will be calculated in the factory, but also no, sometimes that can happen.

    But I see your plan is to add it in both places (entry options + context) so I guess this is just an old comment.

    New GetOrCreateAsync overloads on HybridCache accept a factory that receives the context . These mirror the 6 existing overloads (except for abstract → virtual) and are shared with #121530:

    namespace Microsoft.Extensions.Caching.Hybrid;

    public partial abstract class HybridCache
    {
    // New core overload
    public virtual ValueTask GetOrCreateAsync<TState, T>(
    string key, TState state,
    Func<TState, HybridCacheEntryContext, CancellationToken, ValueTask> factory,
    HybridCacheEntryOptions? options = null,
    IEnumerable? tags = null,
    CancellationToken cancellationToken = default);

    // Convenience (no TState)
    public ValueTask<T> GetOrCreateAsync<T>(
        string key,
        Func<HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory,
        HybridCacheEntryOptions? options = null,
        IEnumerable<string>? tags = null,
        CancellationToken cancellationToken = default);
    

    #if NET
    // ReadOnlySpan key variants
    public virtual ValueTask GetOrCreateAsync<TState, T>(
    ReadOnlySpan key, TState state,
    Func<TState, HybridCacheFactoryContext, CancellationToken, ValueTask> factory,
    HybridCacheEntryOptions? options = null,
    IEnumerable? tags = null,
    CancellationToken cancellationToken = default);

    public ValueTask<T> GetOrCreateAsync<T>(
        ReadOnlySpan<char> key,
        Func<HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory,
        HybridCacheEntryOptions? options = null,
        IEnumerable<string>? tags = null,
        CancellationToken cancellationToken = default);
    
    // DefaultInterpolatedStringHandler key variants
    public ValueTask<T> GetOrCreateAsync<TState, T>(
        ref DefaultInterpolatedStringHandler key, TState state,
        Func<TState, HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory,
        HybridCacheEntryOptions? options = null,
        IEnumerable<string>? tags = null,
        CancellationToken cancellationToken = default);
    
    public ValueTask<T> GetOrCreateAsync<T>(
        ref DefaultInterpolatedStringHandler key,
        Func<HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory,
        HybridCacheEntryOptions? options = null,
        IEnumerable<string>? tags = null,
        CancellationToken cancellationToken = default);
    

    #endif
    }

    Looks reasonable to me.

    I can see the overloads number is already starting to explode and... yeah, I've been there too: welcome to the club 🥲
    In case you are wondering, there's not much you can do about it.

    API Usage (added by @svick)

    var user = await cache.GetOrCreateAsync($"users/{id}", async (ctx, ct) =>
    {
    var user = await db.GetUserAsync(id, ct);
    ctx.LocalCacheSize = user.ProfileImageBytes.Length + user.Name.Length * 2;
    return user;
    });

    Looks good too 👍

    Alternative Designs (added by @svick)

    • Should HybridCacheEntryContext and HybridCacheEntryOptions be the same class? Should they have some inheritance relationship?
      Doing that would be awkward, because HybridCacheEntryOptions is effectively immutable, while HybridCacheEntryContext has to be mutable.

    To me: no, absolutely not.

    They may "smell the same" (and fwiw I initially explored the same design, and then scrapped it) but they are really not the same.

    In short: "It's a trap" (cit).

    FWIW in the case of FC I have an entire FusionCacheEntryOptions property inside the context, to allow the user to change what they want freely and avoid having to create a new property on the context object for every new entry option added in the future (but HybridCacheEntryOptions being immutable makes this basically a no-go).

    Something to look out for is more future needs for adaptivity, meaning being able to not just change the Size but also expiration etc, but I see you also added that in relation to this other issue, so you are already planning for it.

    One thing I did not see explicitly described is how you are planning to make it work.
    What I mean is, for example, what would will be the initial values of the Size/Expiration/LocalCacheExpiration properties in the context object.

    I think there are 2 possible approaches here:

    • since they are all nullable, they can be all set to null with the idea that any non-null value will be "applied" to the resulting entry options
    • initialize each property with the corresponding value from the "outer" entry options (the one passed to the GetOrCreateAsync() method call)

    The first is a trap, because you would not be able to differentiate between "the value is null because the user did not touch it" and "the value is null because the user want it to be null". This is also true for the whole current DefaultEntryOptions flow, but that is another (but related) topic.

    So, fwiw, I would go with the second approach: initialize each prop with the corresponding prop from the outer entry options, and at the end of the factory create a new one based on those props.
    This would also allow users to read those values inside the factory and make decisions based on them, which is an extra benefit I think may be beneficial.

    If I may, a small but interesting optimization may be to detect calls to the setters in the context object's props and set an internal "dirty flag": in this way, at the end of the factory execution, you'll be able to know if the user "touched" them or not, and if not you can avoid creating a new HybridCacheEntryOptions object with the adapted values, since that would not be necessary.

    My 2 cents.

    Also, if you follow this path please add to the context a prop like a bool IsDirty { get; } or bool AreOptionsChanged { get; } or else (naming is hard etc) to allow other implementers (like me) to do the same check/logic too.

    • Should LocalCacheSize have a different name, since it could be understood as the size of the entire local cache, not the size in the local cache (of the current entry). It was chosen to follow HybridCacheEntryOptions.LocalCacheExpiration.

    Eh, yeah "naming is hard" etc.
    I would go with uniformity + xml comments/docs in general.
    Also, the "size of the entire local cache" is already known as SizeLimit, so I think you'll be fine.

    Risks (added by @svick)

    • LocalCacheSize units are implementation-defined (matching Microsoft.Extensions.Caching.Memory.ICacheEntry.Size), which may cause confusion.

    True, but I think there's no way around it: it is what it is, and if people want to use it they are reasonably expected to know how it works, imho (plus, as always, xml comments+docs).

    • The default virtual implementation ignores the context for backward compatibility — existing HybridCache subclasses must override the new overload to honor LocalCacheSize.

    Makes sense.

    One last thing: the current behavior of the default HC implementation for getting an entry's Size is (if I remember correctly) to use the length in bytes of the serialized payload, or anyway there's a default logic to set it.

    Related to that:

    • are you planning to keep it this way or to change this behavior?
    • how will this behavior work with the new entry option? Will it se it automatically when the Size of the outer entry option is null or will it always overwrite it?

    Hope this helps, good luck with the API review.

    PS: if you know in advance when the API review for this will be let me know, I'd be interested in following it.

  19. svick commented on May 5, 2026

    @svick
    Member

    @jodydonetti Thanks for your thorough review.

    My approach used generics because I also wanted to support accessing the existing stale value

    That is a good point. But we don't need it right now and a generic version of HybridCacheEntryContext could be added later (even if it would make calling the method a bit awkward), so I agree it's fine to keep it non-generic.

    The first is a trap, because you would not be able to differentiate between "the value is null because the user did not touch it" and "the value is null because the user want it to be null". This is also true for the whole current DefaultEntryOptions flow, but that is another (but related) topic.

    The design of HybridCacheEntryOptions is that null means that the user did not touch it, it's not a meaningful value by itself. I'm not convinced that it makes sense to use a different approach for HybridCacheEntryContext.

    Though it does mean using a sentinel value (-1) for LocalCacheSize if the user wants to set a concrete value in HybridCacheEntryOptions but then unset it in HybridCacheEntryContext.

    That also means there is no need to have IsDirty.

    One last thing: the current behavior of the default HC implementation for getting an entry's Size is (if I remember correctly) to use the length in bytes of the serialized payload, or anyway there's a default logic to set it.

    Related to that:

    • are you planning to keep it this way or to change this behavior?

    I'm not planning to change the existing behavior of DefaultHybridCache.

    • how will this behavior work with the new entry option? Will it se it automatically when the Size of the outer entry option is null or will it always overwrite it?

    If both HybridCacheEntryOptions.LocalCacheSize and HybridCacheEntryContext.LocalCacheSize are not set by the user (i.e. both are null), then the L1 Size will be the size of the serialized payload in bytes, just like it was until now.

    Though I'm not quite sure if I've understood this question, so feel free to clarify, if I didn't.

    PS: if you know in advance when the API review for this will be let me know, I'd be interested in following it.

    The current list of APIs to review is at https://apireview.net/backlog. This API should be discussed next week (12th).

  20. jodydonetti commented on May 7, 2026

    @jodydonetti
    Contributor

    That is a good point. But we don't need it right now and a generic version of HybridCacheEntryContext could be added later (even if it would make calling the method a bit awkward), so I agree it's fine to keep it non-generic.

    Understood, but just to be extra cautious, watch out: I understand the urge to do this and move on, but if you plan on potentially adding it later keep in mind that you'll probably end up having to deal with 2 potential issues:

    • you'll need to add a whole new set of overloads for the generic variant
    • overload resolution issues, because the existing calling code not using generics explicitly (but implicitly) may stop working
      Just some second order thinking to reason about before moving forward.

    The design of HybridCacheEntryOptions is that null means that the user did not touch it, it's not a meaningful value by itself.
    I'm not convinced that it makes sense to use a different approach for HybridCacheEntryContext.

    Eh, not really: for some entry options, null means "look at the main value in the same HybridCacheEntryOptions instance".

    For example, look here:

    // If LocalCacheExpiration is not specified, then use option's Expiration, to keep in sync by default.
    // ...

    Basically the logic is "if the user did not specify a LocalCacheExpiration, we'll use the "normal" Expiration" (of the same HybridCacheEntryOptions instance).

    Basically there are 2 different mechanisms related to entry options "inheritance":

    • vertical inheritance (global inheritance): from a specific HybridCacheEntryOptions instance to the DefaultEntryOptions instance
    • horizontal inheritance (local inheritance): from a specific option (e.g.: LocalCacheExpiration) to a more generic option (e.g.: Expiration) on the same HybridCacheEntryOptions instance

    This is how it currently is already, so watch out for changing this behavior in the new part.

    Concrete example: inside the factory I want to set the LocalCacheExpiration to null to specify "just use the normal Expiration", which is something I can already do with a normal HybridCacheEntryOptions on a normal GetOrCreateAsync() method call.
    But if now I can change the value inside the factory, but cannot set it to null (a valid value with an existing and specific meaning), as a user I would be baffled, and limited.

    Hope I've been able to explain myself: if not, let me know.

    Though it does mean using a sentinel value (-1) for LocalCacheSize if the user wants to set a concrete value in HybridCacheEntryOptions but then unset it in HybridCacheEntryContext.

    Initializing each option in the context to the "outer" entry options and allowing null to have a meaning (instead of just using it as "not touched by the user") would solve this too, on top of allowing the factory to know the current values for each option, which can be useful.

    My 2 cents.

    I'm not planning to change the existing behavior of DefaultHybridCache.
    [...]
    If both HybridCacheEntryOptions.LocalCacheSize and HybridCacheEntryContext.LocalCacheSize are not set by the user (i.e. both are null), then the L1 Size will be the size of the serialized payload in bytes, just like it was until now.

    Got it, so to recap:

    • the default value for this new option will be null, which implies HybridCache will calculate it itself (current behavior)
    • if instead the user will set a specific non-null value, that value will be used as-is

    Nitpicking: this removes the possibility for an entry to not have a Size specified (currently possible with the underlying MemoryCache), but imho I don't think this is an issue.

    The current list of APIs to review is at https://apireview.net/backlog. This API should be discussed next week (12th).

    Ok thanks. If it will be on the 12th I'll be at Techorama Belgium, but I'll keep an eye on it and see what I can do.

    Thanks!

  21. svick commented on May 12, 2026

    @svick
    Member

    overload resolution issues, because the existing calling code not using generics explicitly (but implicitly) may stop working
    Just some second order thinking to reason about before moving forward.

    It's quite subtle (because it depends on minute details of the C# spec), but if we had an overload for HybridCacheEntryContext and added one for HybridCacheEntryContext<T>, then a lambda like (ctx, ct) => ... will pick the non-generic overload. To call the generic overload, you would need to write (HybridCacheEntryContext<SomeT> ctx, CancellationToken ct) => .... That's what I meant by "a bit awkward". But existing code will continue working.

    inside the factory I want to set the LocalCacheExpiration to null to specify "just use the normal Expiration"

    To me, null means "use inheritance", it doesn't mean just "use horizontal inheritance". So I still prefer to keep the design as-is.

    allowing the factory to know the current values for each option, which can be useful

    That's a good point. I have added a read-only property CurrentOptions to the context for that purpose.

  22. bartonjs commented on May 12, 2026

    @bartonjs
    Member

    Video

    • We shortened LocalCacheSize to LocalSize to avoid ambiguous parsing from the common compound CacheSize
    namespace Microsoft.Extensions.Caching.Hybrid;
    
    public partial class HybridCacheEntryOptions
    {
        public long? LocalSize { get; set; }
    }
  23. added
    api-approved
    and removed
    api-ready-for-review
    on May 12, 2026
  24. jodydonetti commented on Jun 22, 2026

    @jodydonetti
    Contributor

    Hi all, I left some notes in the other issue after the API Review video.

    Hope this helps.

  25. svick commented on Jul 30, 2026

    @svick
    Member

    Closing, #129048 is merged and implementing this in DefaultHybridCache is now tracked in dotnet/extensions#7669.

  26. locked and limited conversation to collaborators on Aug 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-Extensions-Cachingtenet-performance

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions