Repository navigation
Description
Background and motivation
We need a way for the GetOrCreateAsync factory to control the lifetime of the cached value based on the result of the fetch.
Use cases:
- If the dependent service returns 404, cache the negative result for 5s to reduce thundering herds.
- If the service returns 200, cache the payload for 30m.
- For certain hot paths, disable caching (e.g., transient backend anomalies) and return null rather than throwing, to keep the call path allocation‑ and exception‑free.
API Proposal (modified by @svick)
A new HybridCacheEntryContext class is passed to the factory callback, allowing it to dynamically adjust cache entry options based on the fetch result. This type is shared with #114366 (L1 cache size support).
namespace Microsoft.Extensions.Caching.Hybrid;
public sealed class HybridCacheEntryContext
{
public HybridCacheEntryContext(HybridCacheEntryOptions currentOptions);
public HybridCacheEntryOptions CurrentOptions { get; }
public TimeSpan? Expiration { get; set; }
public TimeSpan? LocalCacheExpiration { get; set; }
public HybridCacheEntryFlags? Flags { get; set; }
// Proposed in #114366
// public long? LocalCacheSize { get; set; }
}
// Existing:
// public sealed class HybridCacheEntryOptions
// {
// public TimeSpan? Expiration { get; init; }
// public TimeSpan? LocalCacheExpiration { get; init; }
// public HybridCacheEntryFlags? Flags { get; init; }
// }All properties are null by default, meaning the value from the HybridCacheEntryOptions specified on the call (or the global default) is used. Setting a property to a non-null value overrides the corresponding option for this cache entry.
Note: Because the factory executes after cache reads have already been attempted, only write-related flags in
Flagsare effective:DisableLocalCacheWrite,DisableDistributedCacheWrite, andDisableCompression. Read-related flags (DisableLocalCacheRead,DisableDistributedCacheRead,DisableUnderlyingData) set on the context are ignored.
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, HybridCacheEntryContext, 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 (modified by @svick)
Negative cache with short TTL
var result = await cache.GetOrCreateAsync($"items/{id}", async (ctx, ct) =>
{
var response = await upstream.GetAsync(id, ct);
if (response.StatusCode == 404)
{
ctx.Expiration = TimeSpan.FromSeconds(5);
return null;
}
return response.Value;
}, options: new() { Expiration = TimeSpan.FromMinutes(30) });Skip caching entirely on transient errors
var result = await cache.GetOrCreateAsync($"items/{id}", async (ctx, ct) =>
{
var response = await upstream.GetAsync(id, ct);
if (response.IsTransientError)
{
ctx.Flags = HybridCacheEntryFlags.DisableLocalCacheWrite
| HybridCacheEntryFlags.DisableDistributedCacheWrite;
return default;
}
return response.Value;
});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.
- Read-related flags: The current proposal silently ignores read-related flags (
DisableLocalCacheRead,DisableDistributedCacheRead,DisableUnderlyingData) set on the context, since the factory runs after reads have already been attempted. An alternative is to throw anArgumentExceptionwhen the implementation detects read-related flags on the context or when the property is being set. The issue with throwing is that flags likeDisableLocalCache = DisableLocalCacheRead | DisableLocalCacheWriteexist and it's unclear whether we want e.g.ctx.Flags = HybridCacheEntryFlags.DisableLocalCacheto throw. Another option would be to use a separate enum type.
Risks
No response
Activity
dotnet-policy-service commentedon Nov 11, 2025
Tagging subscribers to this area: @dotnet/area-extensions-caching
See info in area-owners.md if you want to be subscribed.
EnricoMassone commentedon Nov 14, 2025
The disable caching proposal can be useful to solve the use case described here. Another common use case is when you don't want to cache null values produced by the factory method.
Webreaper commentedon Dec 9, 2025
Nice. I was just about to link that question to here, after finding this issue. :)
rosebyte commentedon Mar 11, 2026
Triage: we may consider implementing it.
svick commentedon Mar 11, 2026
When looking at this, consider also looking at #121530 at the same time (since both would probably use the same
CacheEntryOptions/CacheContext).[-][API Proposal]: Negative cache support for Hybrid Cache[/-][+][API Proposal]: HybridCache: Setting expiration based on value in cache entry factory[/+]svick commentedon Apr 23, 2026
@siby-george I have turned this into a proper API proposal (see the top comment) and plan to bring it to API review (along with #114366). Any comments are welcome.
5 remaining items
Rename HybridCacheFactoryContext to HybridCacheEntryContext; add Curr…
jodydonetti commentedon Jun 22, 2026
Hi all, sorry for the delay, pretty busy lately.
I hope it does not sound harsh (not my intention) but in short I think this decision is "wrong", let me explain why.
Long story short: the existence of a context is quite needed, because not everything is in the
HybridCacheEntryOptions: case in point the tags, which is something that people would very much like to adapt in the factory too.And, in fact, they are already asking this, so a question would be: how would you approach changing the tags inside the factory with this new approach that has been approved for now?
This would also be an answer to a question made in the video:
So the context:
So if you now proceed by adding all those extra overloads (I count 5 of them), when you will end up adding support to also adapt the tags inside the factory you will end up adding at least another 5 overloads to do basically the same thing, plus a little bit more (the tags).
This really feels the right moment to add the factory context to avoid doing this step now and adding the context nonetheless in the near future, and also be ready for whatever else will come in the future knowing it will be possible to add it in the context (and it will not be possible to add to the entry options).
FWIW, I'm saying this as I've already been there & done that, that's why I'm so positive about it (and I'd like to avoid the extra pain on your side + end users + 3rd party implementers).
Additional clarification: I'm not for creating the context object with all the entry options' props duplicated.
What I am for is to create the context object with the entry options exposed there as an inner property (fwiw: that is what I've done in FusionCache) with some careful thinking about what is already there when the factory is called and what can be changed.
To be even more clear: if the entry options becomes mutable, it can still appear inside of a context object since the 2 things are not mutually exclusive.
My 2 cents.
Two things about going down this road:
DefaultEntryOptionspassed internally, in place of a user call withnullDistributedCacheEntryOptions, otherwise it will be internally freezed at the first access. The 2 options I can see are (imho) to keep doing this but reset tonullon the private field at everyRevisionchange (so, in the props setters), or to just stop storing it internally.Not crucial here, but start thinking (and maybe add notes about it) for how the
Revisionwill change when entry options are cloned:0?Also: will the cloning capability be exposed publicly via a public method?
Another note from the video: it has been stated that the default HC impl always serializes (true, probably: I'm not sure about immutable types though, I'd need to check the source) and it always set the
Size(true).But it has been also stated that with the FusionCache impl "does not set the
Sizefor the memory cache": not true, it does.Also "if you set a
SizeLimiton the memory cache you cannot use FusionCache via the abstraction": not true, at least not 100% true, since you can just set a defaultSizein theDefaultEntryOptions(what is currently missing is to set it dynamically, which the proposed change would fix).Probably nitpicking, but still wanted to clarify.
Thanks all and sorry for the delay, hope this helps.
svick commentedon Jul 3, 2026
@jodydonetti Our team thinks you have a point, so I have turned computed tags (#129842) into a proper API proposal and we want to reevaluate the approved API for this proposal. Though having a context just to hold a single property seems unnecessary. So, the new API would be (diff against the API approved here and in #114366):
namespace Microsoft.Extensions.Caching.Hybrid; public partial class HybridCacheEntryOptions { - public TimeSpan? Expiration { get; set; } + public TimeSpan? Expiration { get; init; } - public TimeSpan? LocalCacheExpiration { get; set; } + public TimeSpan? LocalCacheExpiration { get; init; } - public HybridCacheEntryFlags? Flags { get; set; } + public HybridCacheEntryFlags? Flags { get; init; } - public long? LocalSize { get; set; } + public long? LocalSize { get; init; } - public int Revision { get; } }Change HybridCacheEntryOptions to HybridCacheEntryContext in overloads of HybridCache.GetOrCreateAsync
namespace Microsoft.Extensions.Caching.Hybrid; public partial abstract class HybridCache { public virtual ValueTask<T> GetOrCreateAsync<TState, T>( string key, TState state, - Func<TState, HybridCacheEntryOptions, CancellationToken, ValueTask<T>> factory, + Func<TState, HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default); public ValueTask<T> GetOrCreateAsync<T>( string key, - Func<HybridCacheEntryOptions, CancellationToken, ValueTask<T>> factory, + Func<HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default); #if NET public virtual ValueTask<T> GetOrCreateAsync<TState, T>( ReadOnlySpan<char> key, TState state, - Func<TState, HybridCacheEntryOptions, CancellationToken, ValueTask<T>> factory, + Func<TState, HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default); public ValueTask<T> GetOrCreateAsync<T>( ReadOnlySpan<char> key, - Func<HybridCacheEntryOptions, CancellationToken, ValueTask<T>> factory, + Func<HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default); public ValueTask<T> GetOrCreateAsync<TState, T>( ref DefaultInterpolatedStringHandler key, TState state, - Func<TState, HybridCacheEntryOptions, CancellationToken, ValueTask<T>> factory, + 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<HybridCacheEntryOptions, CancellationToken, ValueTask<T>> factory, + Func<HybridCacheEntryContext, CancellationToken, ValueTask<T>> factory, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default); #endif }The behavior would otherwise stay the same (i.e. the
HybridCacheEntryContextpassed to the factory has the currently effective values set).bartonjs commentedon Jul 7, 2026
Video
Rework factory options API to HybridCacheEntryContext
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.