extensions icon indicating copy to clipboard operation
extensions copied to clipboard

HybridCache: add expiry to cached tag invalidation timestamps to improve distributed consistency without a backplane

Open LuisM000 opened this issue 8 months ago • 5 comments

Summary

Add a TTL to the in-memory cache of tag invalidation timestamps (_tagInvalidationTimes) so that entries are periodically re-read from L2, improving consistency in distributed deployments without requiring a full backplane.

Background

DefaultHybridCache stores tag invalidation timestamps in a ConcurrentDictionary<string, Task<long>> (_tagInvalidationTimes). Once a tag is seen, its entry is never refreshed:

private void PrefetchTagWithBackendCache(string tag)
{
    if (!_tagInvalidationTimes.TryGetValue(tag, out _))
    {
        _ = _tagInvalidationTimes.TryAdd(tag, SafeReadTagInvalidationAsync(tag));
        // only added once, never updated
    }
}

In a multi-instance deployment (e.g. multiple pods in Kubernetes), if Instance B calls RemoveByTagAsync("my-tag"), Instance A will never learn about it because its _tagInvalidationTimes["my-tag"] is permanently 0 (never invalidated). Even after L1 expires and Instance A re-reads from L2, the tag check always returns "valid".

Proposed fix

Add a configurable TTL to each entry in _tagInvalidationTimes. When the TTL expires, the next access re-reads the invalidation timestamp from L2. This way:

  • Instances periodically re-sync their tag state from L2
  • No backplane or pub/sub mechanism is required
  • The TTL controls the tradeoff between consistency and L2 read cost

A reasonable default could match LocalCacheExpiration, or be independently configurable via HybridCacheOptions.

Why this matters

A full backplane (as proposed in the original distributed invalidation design) is the complete solution, but it requires additional infrastructure. A TTL-based approach is a low-cost intermediate improvement that makes tag invalidation eventually consistent in distributed scenarios using only the existing IDistributedCache backend.

Impact

Without this fix, RemoveByTagAsync in a multi-instance deployment only reliably invalidates the instance that called it. Other instances continue serving stale data indefinitely, which is surprising given the API's intent.

LuisM000 avatar Mar 19 '26 16:03 LuisM000

"Hey, I'd like to take a stab at this. Does the TTL approach still make sense, or is the team leaning another direction?"

reabr avatar Apr 03 '26 19:04 reabr

@reabr Sorry for the delay. I think the TTL approach makes sense, so feel free to work on this, if you're still interested.

svick avatar Jul 28 '26 15:07 svick

When fixing this, don't forget about the global invalidation stored in _globalInvalidateTimestamp.

svick avatar Oct 26 '26 17:10 svick

Confirming this on Microsoft.Extensions.Caching.Hybrid 10.0.0 and 10.11.0 (the latest 10.x on nuget.org on 2026-11-05). The setup is two HybridCache instances in separate DI containers sharing one Redis 7.4.1 (StackExchangeRedis 10.0.0 and 10.0.14), with LocalCacheExpiration 5 s and Expiration 10 min.

  • Tag removal on another node: A calls RemoveByTagAsync("T"). B had read T's invalidation time once, and its _tagInvalidationTimes entry stays 0. After B's local copy expires, B reads K from Redis again and accepts the removed value at +6, +30, +65 and +130 s. Redis MONITOR shows B sending no command on the tag key after its first read.
  • With Expiration = 30 s: B returns the new value only once K has expired in Redis, at +26 s, for an entry created about 6 s before the removal. So today another node's staleness after a tag removal is bounded by the entry's Expiration, not by its LocalCacheExpiration.
  • Removal by key: RemoveAsync(K) on A is seen by B at its first read after its local copy expires.
  • Source: DefaultHybridCache.TagInvalidation.cs is byte-identical at the 10.0.0 commit (fbd3936) and the 10.11.0 commit (25f07af), including lines 111-132 (the one TryAdd) and 255 (the only replacement, from a local RemoveByTagAsync).

MatteoZampariniDev avatar Nov 05 '26 10:11 MatteoZampariniDev

Hi all, just as a high level rationale to clarify the approach.

The technique mentioned here is commonly known as Tiered Expirations, and it consists of having different expirations/durations/TTL (same thing, different name) for each level (tier).

In short, when dealing with coherence issues in a hybrid/multilevel cache, we can look for a:

  • solution: using a backplane or similar, with near realtime distributed notifications
  • mitigation: using the Tiered Expiration approach mentioned here, hich is basically good ol' polling (from L1 to L2)

If you can, you should of course use a backplane, which is the proper solution, in which the incoherence window is reduced to the absolute mininal (usually up to a few ms) and will not increase the load on the L2.

If you cannot or don't want to use a backplane, you can use Tiered Expirations as a mitigation, in which the incoherence window is basically reduced to the L1 expiration.

Of course the balance is that as you decrease the L1 expiration more and more:

  • the incoherence window becomes smaller (good)
  • the L2 reads frequency becomes higher (bad)

Hope this helps.

jodydonetti avatar Nov 06 '26 08:11 jodydonetti