Repository navigation
Description
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 HybridCacheFusionHybridCache results in unbounded memory use and this is the issue that we're currently experiencing when using HybridCacheFusionHybridCache
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
HybridCacheEntryContextandHybridCacheEntryOptionsbe the same class? Should they have some inheritance relationship? Doing that would be awkward, becauseHybridCacheEntryOptionsis effectively immutable, whileHybridCacheEntryContexthas to be mutable. - Should
LocalCacheSizehave 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 followHybridCacheEntryOptions.LocalCacheExpiration. - Since knowing the size of a cache item is comparable to serializing it, should there be
IHybridCacheSizeProvider<T>/IHybridCacheSizeProviderFactory, mirroringIHybridCacheSerializer<T>/IHybridCacheSerializerFactoryinstead or in addition toHybridCacheEntryContext.LocalCacheSize?
Risks (added by @svick)
LocalCacheSizeunits are implementation-defined (matchingMicrosoft.Extensions.Caching.Memory.ICacheEntry.Size), which may cause confusion.- The default virtual implementation ignores the context for backward compatibility — existing
HybridCachesubclasses must override the new overload to honorLocalCacheSize.
Activity
dotnet-policy-service commentedon Apr 8, 2025
Tagging subscribers to this area: @dotnet/area-extensions-caching
See info in area-owners.md if you want to be subscribed.
mgravell commentedon Apr 9, 2025
On size: the dotnet/extensions version of
HybridCacheuses the serialized payload size to assign a value for size; it should already "just work"; could you perhaps expand on what you're seeing?bebo-dot-dev commentedon Apr 9, 2025
Using
FusionCacheasHybridCacheis where we had an issue with unboundedMemoryCachememory usage because there's currently no way to specifySizethroughHybridCacheEntryOptionsand the FusionCache flavour ofHybridCachedoesn'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:
and also
To put this another way the docs suggest that once a
SizeLimitof arbitrary units has been assigned to aMemoryCacheviaMemoryCacheOptions, the onus is on the caller when adding an item to the cache to setSizeon 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
SizeLimitandSizecould be trusted to be bytes and considered to always be bytes because automatic determination/calculation ofSizewould then work. This isn't what theMemoryCachedocs say today however so there seems to be a gap in theHybridCacheAPI surface because there's no way to passSizethroughHybridCacheOptions.So perhaps this really is a problem or possibly the the MemoryCache docs are wrong, the
HybridCacheOptionscode contract is fine as it stands andFusionCacheneeds to trust thatSizeLimitandSizeare bytes and determineSizeat runtime based on the size of a cache item in bytes?mgravell commentedon Apr 9, 2025
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:
The problem is how to squeeze this into the existing API without causing ambiguity; we already have overloads that take
Func<CancellationToken, ValueTask<T>>andFunc<TState, CancellationToken, ValueTask<T>>, so to avoid lambda ambiguity, we'd need to use a triplet arg - something like:Where
ctxhere is someCacheContexttype.Another approach might be to have an
IHybridCacheIteminterface that the resultTcould optionally implement, allowing the existing API to pass some values back out, for example:with the library type-testing for
IHybridCacheItemand applying things on the way out.I'm just thinking aloud here; all input welcome.
mgravell commentedon Apr 9, 2025
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 theTState, which is usually inconvenient and sometimes impossible; of course, we could just use a different name:jodydonetti commentedon Apr 9, 2025
Hi @bebo-dot-dev
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?
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!
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.
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?
jodydonetti commentedon Apr 9, 2025
FWIW that's what I did in FusionCache (see Adaptive Caching), anche the community likes that a lot.
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
Personclass.My 2 cents.
jodydonetti commentedon Apr 9, 2025
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...
bebo-dot-dev commentedon Apr 9, 2025
Having read more docs, my takeaway is that the .NET HybridCache docs confirm that the .NET HybridCache uses the same
MemoryCachefor L1 thatFusionCachealso 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
Sizefor 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
SizeLimitis 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,SizeLimitandSizeare 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.jodydonetti commentedon Apr 9, 2025
Yup, can confirm.
Or, to be more precise (nitpicking corner here): both HybridCache and (current) FusionCache both use
IMemoryCacheas the L1, not necessarily the same instance if you use them both together for whatever reasons.HybridCache (currently) always uses the
IMemoryCacheinstance 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.
@mgravell can correct me if I'm wrong, but I think that he set the
Sizein each cache entry so that, IF a user has set aSizeLimiton the DI-providedIMemoryCache, HybridCache would not start throwing exceptions (that is what happens withMemoryCachewhen you set aSizeLimitbut fail to provide aSizefor even 1 cache entry.Meaning: if, as is the default, a
SizeLimitis not configured -> nothing happens anyway.On my hand instead (FusionCache), you can specify an
IMemoryCacheinstance, and maybe set aSizeLimit: if you do so, you then MUST set someSize, otherwise you'd be asking to set a limit without providing a way to check that limit.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
Sizebased 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.
bebo-dot-dev commentedon Apr 9, 2025
Many things are not known to me but there is one thing that I know for certain; if something doesn't set a
SizeLimitonMemoryCacheit is a surefire way to using all available memory. I found this out the hard way just a few days ago 😊25 remaining items
jodydonetti commentedon Apr 25, 2026
Hi @svick , I'll try to take some time to read this in the next few days.
jodydonetti commentedon May 4, 2026
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.
Background: in FC I have
FusionCacheEntryOptions(basically the same asHybridCacheEntryOptions) and that contains aSizeoption.This, coupled with the
DefaultEntryOptions& related inheritance mechanism, allows users to at least set a defaultSizefor each entry, even when using FC as a HC implementation via the adapter.Also, 2 things:
People asked me to add support for changing the
Sizevia 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 onobjectto make it work with any cached value type, but... potential boxing, not-so-good ergonomics, etc and I waited to do it for now.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).
Yes and no, meaning: yes, more frequently the
Sizewill 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.
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.
Looks good too 👍
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
FusionCacheEntryOptionsproperty 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 (butHybridCacheEntryOptionsbeing 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
Sizebut 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/LocalCacheExpirationproperties in the context object.I think there are 2 possible approaches here:
nullwith the idea that any non-nullvalue will be "applied" to the resulting entry optionsGetOrCreateAsync()method call)The first is a trap, because you would not be able to differentiate between "the value is
nullbecause the user did not touch it" and "the value isnullbecause the user want it to benull". This is also true for the whole currentDefaultEntryOptionsflow, 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
HybridCacheEntryOptionsobject 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; }orbool AreOptionsChanged { get; }or else (naming is hard etc) to allow other implementers (like me) to do the same check/logic too.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.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).
Makes sense.
One last thing: the current behavior of the default HC implementation for getting an entry's
Sizeis (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:
Sizeof the outer entry option isnullor 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.
svick commentedon May 5, 2026
@jodydonetti Thanks for your thorough review.
That is a good point. But we don't need it right now and a generic version of
HybridCacheEntryContextcould 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 design of
HybridCacheEntryOptionsis thatnullmeans 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 forHybridCacheEntryContext.Though it does mean using a sentinel value (
-1) forLocalCacheSizeif the user wants to set a concrete value inHybridCacheEntryOptionsbut then unset it inHybridCacheEntryContext.That also means there is no need to have
IsDirty.I'm not planning to change the existing behavior of
DefaultHybridCache.If both
HybridCacheEntryOptions.LocalCacheSizeandHybridCacheEntryContext.LocalCacheSizeare not set by the user (i.e. both arenull), then the L1Sizewill 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.
The current list of APIs to review is at https://apireview.net/backlog. This API should be discussed next week (12th).
jodydonetti commentedon May 7, 2026
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:
Just some second order thinking to reason about before moving forward.
Eh, not really: for some entry options,
nullmeans "look at the main value in the sameHybridCacheEntryOptionsinstance".For example, look here:
Basically the logic is "if the user did not specify a
LocalCacheExpiration, we'll use the "normal"Expiration" (of the sameHybridCacheEntryOptionsinstance).Basically there are 2 different mechanisms related to entry options "inheritance":
HybridCacheEntryOptionsinstance to theDefaultEntryOptionsinstanceLocalCacheExpiration) to a more generic option (e.g.:Expiration) on the sameHybridCacheEntryOptionsinstanceThis 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
LocalCacheExpirationtonullto specify "just use the normal Expiration", which is something I can already do with a normalHybridCacheEntryOptionson a normalGetOrCreateAsync()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.
Initializing each option in the context to the "outer" entry options and allowing
nullto 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.
Got it, so to recap:
null, which implies HybridCache will calculate it itself (current behavior)nullvalue, that value will be used as-isNitpicking: this removes the possibility for an entry to not have a
Sizespecified (currently possible with the underlyingMemoryCache), but imho I don't think this is an issue.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!
svick commentedon May 12, 2026
It's quite subtle (because it depends on minute details of the C# spec), but if we had an overload for
HybridCacheEntryContextand added one forHybridCacheEntryContext<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.To me,
nullmeans "use inheritance", it doesn't mean just "use horizontal inheritance". So I still prefer to keep the design as-is.That's a good point. I have added a read-only property
CurrentOptionsto the context for that purpose.bartonjs commentedon May 12, 2026
Video
LocalCacheSizetoLocalSizeto avoid ambiguous parsing from the common compoundCacheSizeRename HybridCacheFactoryContext to HybridCacheEntryContext; add Curr…
jodydonetti commentedon Jun 22, 2026
Hi all, I left some notes in the other issue after the API Review video.
Hope this helps.
Add HybridCache.GetOrCreateAsync overloads for dynamic setting of opt…
svick commentedon Jul 30, 2026
Closing, #129048 is merged and implementing this in
DefaultHybridCacheis now tracked in dotnet/extensions#7669.