Skip to content

[API Proposal]: HybridCache: Setting expiration based on value in cache entry factory #121530

Closed

Description

@siby-george

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 Flags are effective: DisableLocalCacheWrite, DisableDistributedCacheWrite, and DisableCompression. 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 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.
  • 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 an ArgumentException when the implementation detects read-related flags on the context or when the property is being set. The issue with throwing is that flags like DisableLocalCache = DisableLocalCacheRead | DisableLocalCacheWrite exist and it's unclear whether we want e.g. ctx.Flags = HybridCacheEntryFlags.DisableLocalCache to throw. Another option would be to use a separate enum type.

Risks

No response

Activity

  1. added
    api-suggestion
    on Nov 11, 2025
  2. added
    untriaged
    on Nov 11, 2025
  3. dotnet-policy-service commented on Nov 11, 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. EnricoMassone commented on Nov 14, 2025

    @EnricoMassone

    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.

  5. Webreaper commented on Dec 9, 2025

    @Webreaper

    Nice. I was just about to link that question to here, after finding this issue. :)

  6. added this to the Future milestone on Feb 12, 2026
  7. removed
    untriaged
    on Feb 12, 2026
  8. rosebyte commented on Mar 11, 2026

    @rosebyte
    Member

    Triage: we may consider implementing it.

  9. svick commented on Mar 11, 2026

    @svick
    Member

    When looking at this, consider also looking at #121530 at the same time (since both would probably use the same CacheEntryOptions/CacheContext).

  10. self-assigned this
    on Apr 22, 2026
  11. changed the title [-][API Proposal]: Negative cache support for Hybrid Cache[/-] [+][API Proposal]: HybridCache: Setting expiration based on value in cache entry factory[/+] on Apr 23, 2026
  12. svick commented on Apr 23, 2026

    @svick
    Member

    @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.

  13. 5 remaining items

  14. added
    api-approved
    and removed
    api-ready-for-review
    on May 12, 2026
  15. jodydonetti commented on Jun 22, 2026

    @jodydonetti
    Contributor

    Hi all, sorry for the delay, pretty busy lately.

    Video

    • Rather than introduce a copy of HybridCacheEntryOptions just to change get/init to get/set, let's just change HybridCacheEntryOptions to get/set.

    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:

    "Question: so we have the entry options already and with both proposals the API shape of the entry options vs the entry context is going to be basically the same. Is there a reason we are not just reusing the options that people might assume it's readonly because it's currently immutable effectively or is there more to that?"

    So the context:

    • is not just a mutable version of the entry options
    • instead it contains entry options + more (like tags, and from first hand experience I can already say maybe more in the future)

    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.

    • It feels like GetOrCreateAsync with a non-null HybridCacheEntryOptions can maybe not clone that options value. Or maybe cloning is good.

    Two things about going down this road:

    • I think I grasped from the video you are already on this, but watch out to not allow mutating DefaultEntryOptions passed internally, in place of a user call with null
    • if the entry options will in fact become mutable, remember to change this which caches the inner DistributedCacheEntryOptions, otherwise it will be internally freezed at the first access. The 2 options I can see are (imho) to keep doing this but reset to null on the private field at every Revision change (so, in the props setters), or to just stop storing it internally.
    • Added Revision to HybridCacheEntryOptions so implementations can identify if the options changed in the callback.

    Not crucial here, but start thinking (and maybe add notes about it) for how the Revision will change when entry options are cloned:

    • do they reset to 0?
    • do they start from where they were?

    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 Size for the memory cache": not true, it does.
    Also "if you set a SizeLimit on the memory cache you cannot use FusionCache via the abstraction": not true, at least not 100% true, since you can just set a default Size in the DefaultEntryOptions (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.

  16. svick commented on Jul 3, 2026

    @svick
    Member

    @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; }
    }
    namespace Microsoft.Extensions.Caching.Hybrid;
    
    public sealed class HybridCacheEntryContext
    {
        public TimeSpan? Expiration { get; set; }
        public TimeSpan? LocalCacheExpiration { get; set; }
        public HybridCacheEntryFlags? Flags { get; set; }
        public long? LocalSize { get; set; }
        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 HybridCacheEntryContext passed to the factory has the currently effective values set).

  17. added
    api-ready-for-review
    and removed
    api-approved
    on Jul 3, 2026
  18. bartonjs commented on Jul 7, 2026

    @bartonjs
    Member

    Video

    • Added the internal HybridCacheEntryContext ctor that was missing (to indicate non-instantiable)
    namespace Microsoft.Extensions.Caching.Hybrid;
    
    public sealed class HybridCacheEntryContext
    {
        internal HybridCacheEntryContext();
    
        public TimeSpan? Expiration { get; set; }
        public TimeSpan? LocalCacheExpiration { get; set; }
        public HybridCacheEntryFlags? Flags { get; set; }
        public long? LocalSize { get; set; }
        public int Revision { get; }
    }
    
    public partial abstract class HybridCache
    {
        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);
    
        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
        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);
    
        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
    }
  19. added
    api-approved
    and removed
    api-ready-for-review
    on Jul 7, 2026
  20. svick commented on Jul 30, 2026

    @svick
    Member

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

  21. 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-Caching

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions