skip to content

In ASP.NET Core's HybridCache, what do tags on GetOrCreateAsync and RemoveByTagAsync do, and why does RemoveByTagAsync not delete any cached values?

level: seniorimportance: should knowfreq 30%

answer

  1. IEnumerable<string>? tags parameter
  2. logical invalidation by timestamp
  3. older entries treated as misses
  4. "*" invalidates everything
  5. no globs; empty and * rejected on entries

basics

~20 s

Tags group entries so one call can invalidate them together. RemoveByTagAsync records an invalidation time for the tag instead of deleting values; later reads treat entries created before it as misses. The reserved wildcard tag, a lone asterisk, invalidates everything.

solid answer

~50 s

`GetOrCreateAsync` and `SetAsync` take an `IEnumerable<string>? tags` argument, stored with the entry. `RemoveByTagAsync(tag)` cannot delete those values, because neither `IMemoryCache` nor `IDistributedCache` can find entries by tag, so it records an invalidation timestamp for the tag, locally and in the distributed store. When a read finds an entry whose creation time is at or before the invalidation time of any of its tags, it treats the entry as a miss and runs the factory; the old values stay in memory and in Redis until they expire. `RemoveByTagAsync("*")` invalidates every entry, tagged or not. Tags on an entry may not be empty, whitespace or `*` (an `ArgumentException`), there is no pattern matching, and an overload takes several tags. Other instances' in-memory copies are not guaranteed to notice, so keep `LocalCacheExpiration` short where tag invalidation must be prompt.

code

csharp · 8 lines
csharp
public sealed class PriceImport(HybridCache cache, CatalogueDb db)
{
    public async Task ApplyAsync(string brand, IReadOnlyList<PriceRow> rows, CancellationToken ct)
    {
        await db.UpdatePricesAsync(rows, ct);
        await cache.RemoveByTagAsync($"brand:{brand}", ct);
    }
}

go deeper

for a junior

Recall that tags group cache entries so RemoveByTagAsync can invalidate them together.

for a middle

Explain logical invalidation: a recorded timestamp makes older entries misses, values stay until expiry, and "*" invalidates everything with no glob matching.

for a senior

Explain why other instances may serve invalidated entries until LocalCacheExpiration, the tag validation rules, the per-read tag cost and ReportTagMetrics' data-exposure risk.

for a principal

Design tag vocabularies around business invalidation events and decide where logical, eventually consistent invalidation is acceptable and where a stronger guarantee is required.

## Tagging entries Every `HybridCache` write can carry tags: ```csharp var card = await cache.GetOrCreateAsync( $"card:{sku}", async ct => await db.LoadCardAsync(sku, ct), tags: ["catalogue", $"brand:{brand}", $"category:{category}"], cancellationToken: ct); ``` The tags are stored alongside the value in both tiers. They exist for one purpose: invalidating a group of entries with one call, such as every card of a brand whose prices just changed, without tracking all their keys. Validation happens when an entry is tagged: a `null`, empty or whitespace tag throws `ArgumentException` ("Tags cannot be empty."), and so does `*`, which is reserved. ## Why RemoveByTagAsync deletes nothing Neither underlying store can enumerate entries by tag: `IMemoryCache` has no tag index, and `IDistributedCache` offers only get, set, refresh and remove by exact key. So `RemoveByTagAsync` uses **logical** invalidation: 1. It takes the current timestamp. 2. It records "tag `brand:trailrun` invalid as of this time" in the instance's own table of tag invalidations. 3. It writes the same record to the distributed store, when one is registered. From then on, whenever an entry is read, its creation timestamp is compared with the invalidation times of its tags: - **Created at or before an invalidation of any of its tags:** treated as a miss; the factory runs and a fresh entry replaces it. - **Created afterwards:** served normally. The stale values are not removed. They stay in `IMemoryCache` and in Redis until their own expiration, using memory but never being served on that instance. ## The wildcard `*` is a reserved tag meaning "everything". `RemoveByTagAsync("*")` sets a global invalidation time that applies to every entry, including entries written with no tags at all. It is useful after a bulk data import or a cache-format change. Like other tags it is logical: nothing is deleted. Glob-style patterns are not supported; `RemoveByTagAsync("brand:*")` invalidates the literal tag `brand:*`, which no entry can carry. Calling `RemoveByTagAsync` with an empty or whitespace tag simply returns without doing anything. ## Across several instances The sports retailer runs four storefront instances. An admin action on instance 2 calls `RemoveByTagAsync("brand:trailrun")`: | Where | Effect | |---|---| | instance 2, L1 | invalidated immediately | | distributed store | invalidation time recorded | | instances 1, 3, 4, L1 | not guaranteed to notice; they can serve the old cards until their local copies expire | An instance reads a tag's invalidation time from the distributed store when it first needs that tag and keeps the value in memory. The ASP.NET Core docs state the guarantee plainly: invalidation by key or tag affects the current server and the out-of-process store, not other servers' in-memory caches. A short `LocalCacheExpiration` on tagged data bounds how long other instances lag. ## Practical guidance - **Choose tags around invalidation events**, such as a brand, a category or a supplier feed, not around how data is displayed. - **Keep the number of tags per entry modest.** Every read checks each tag of the entry, and the docs note that large tag sets can affect performance. - **Do not put personal data in tags if you enable `HybridCacheOptions.ReportTagMetrics`**, which uses tag values as metric dimensions. - **Remember the storage cost.** Invalidated values occupy memory until they expire, so pair tagging with sensible expirations. ## Not to be confused with output caching The output cache has its own tags and `IOutputCacheStore.EvictByTagAsync`, which evicts cached HTTP responses. HybridCache tags apply to data entries and are invalidated logically through `RemoveByTagAsync`; the two mechanisms are separate and do not see each other's tags. ## Tags or keys? | Need | Use | |---|---| | One known entry changed | `RemoveAsync(key)`, which also deletes the distributed copy | | Several known keys changed | `RemoveAsync(IEnumerable<string> keys)` | | An open-ended group changed, such as a whole brand | `RemoveByTagAsync(tag)` | | Everything must be treated as stale | `RemoveByTagAsync` with the wildcard | Key removal frees space in the distributed store at once; tag invalidation never does. Prefer keys when you can name them, and tags when you cannot.

  • Does RemoveByTagAsync("brand:*") invalidate every brand tag?
    No. HybridCache does no pattern matching. Only the exact string `*` is special; `brand:*` is treated as an ordinary tag name, and because no entry carries that literal tag, nothing is invalidated.
  • After RemoveByTagAsync, why does memory usage not drop?
    Invalidation is logical. The entries remain in `IMemoryCache` and the distributed store until their own expiration; reads simply treat them as misses and replace them. Memory is reclaimed only as the old entries expire or are overwritten.

  • RemoveByTagAsync physically deletes every tagged value from Redis
  • RemoveByTagAsync("brand:*") invalidates all tags starting with brand:
  • RemoveByTagAsync("*") only affects entries that were given tags
  • Tagging an entry with "*" makes it easy to clear later
  • HybridCache's RemoveByTagAsync also evicts output-cached responses with the same tag