On a festival site whose event listings use ASP.NET Core output caching, how do you evict them by tag when an organiser edits an event, and what changes with three instances?
answer
- Tag("events") on the policy
- IOutputCacheStore.EvictByTagAsync
- default store lives in each process
- AddStackExchangeRedisOutputCache
- not AddStackExchangeRedisCache
basics
~10 sTag the cached listings (Tag("events") or [OutputCache(Tags = ...)]), inject IOutputCacheStore into the edit endpoint and call EvictByTagAsync("events"). The default store is per process, so with three instances register AddStackExchangeRedisOutputCache to share one store.
solid answer
~50 sGive every cached listing a tag, `Tag("events")` in the policy or `[OutputCache(Tags = new[] { "events" })]`, and where one event's page should be evicted alone, add a per-event tag at request time through `IOutputCacheFeature.Context.Tags`. In the organiser's edit endpoint, after saving, inject the singleton `IOutputCacheStore` and `await store.EvictByTagAsync("events", ct)`: every entry stored with that tag is removed and the next request rebuilds it. The default store is in memory inside each process, so with three instances only the one that handled the edit forgets its copies, and the other two keep serving the old listing until their entries expire. In ASP.NET Core 8 and later, the `Microsoft.AspNetCore.OutputCaching.StackExchangeRedis` package's `AddStackExchangeRedisOutputCache` replaces the store with one in Redis that all instances share, tag index included. `AddStackExchangeRedisCache` is the wrong call: it registers `IDistributedCache`, which output caching never uses.
code
csharp · 15 linesbuilder.Services.AddOutputCache(o =>
o.AddPolicy("Listings", b => b.Expire(TimeSpan.FromMinutes(30)).Tag("events")));
builder.Services.AddStackExchangeRedisOutputCache(o =>
{
o.Configuration = builder.Configuration.GetConnectionString("redis");
o.InstanceName = "festival:";
});
app.MapPut("/organiser/events/{id:int}", async (int id, EventEdit edit,
FestivalDb db, IOutputCacheStore cache, CancellationToken ct) =>
{
await Events.ApplyAsync(db, id, edit, ct);
await cache.EvictByTagAsync("events", ct);
return TypedResults.NoContent();
});go deeper
Know that cached responses can carry tags and that IOutputCacheStore.EvictByTagAsync removes every entry with a tag.
Show how to attach a static tag in a policy or attribute and a dynamic one through IOutputCacheFeature, and how to call EvictByTagAsync from the write path.
Explain why per-process stores make eviction partial across instances, how the Redis output cache store fixes it, and why AddStackExchangeRedisCache does not. Cover failure handling around eviction.
Decide between explicit eviction and short lifetimes per resource, weighing staleness tolerance, Redis as a new dependency and how many write paths must remember to evict.
## Tagging cached responses A **tag** is a label stored alongside an output cache entry so a group of entries can be removed together. ASP.NET Core offers three ways to set one: - `OutputCachePolicyBuilder.Tag("events")` in a named, base or endpoint policy; - `[OutputCache(Tags = new[] { "events" })]` on a controller action, Razor Page or handler; - at request time, `HttpContext.Features.Get<IOutputCacheFeature>()?.Context.Tags.Add(...)`, which is how you add a tag that depends on route data. The feature is only present while the output cache middleware is handling a request with a policy, and tags are read when the response is stored, after the handler returns. ```csharp options.AddPolicy("Listings", b => b.Expire(TimeSpan.FromMinutes(30)).Tag("events")); app.MapGet("/events/{id:int}", async (int id, HttpContext http, FestivalDb db) => { http.Features.Get<IOutputCacheFeature>()?.Context.Tags.Add($"event-{id}"); return await db.Events.FindAsync(id) is { } e ? Results.Ok(e) : Results.NotFound(); }).CacheOutput("Listings"); ``` ## Evicting on edit `IOutputCacheStore` is registered as a singleton, so it can be injected anywhere: ```csharp app.MapPut("/organiser/events/{id:int}", async (int id, EventEdit edit, FestivalDb db, IOutputCacheStore cache, CancellationToken ct) => { await Events.ApplyAsync(db, id, edit, ct); await cache.EvictByTagAsync("events", ct); await cache.EvictByTagAsync($"event-{id}", ct); return TypedResults.NoContent(); }).RequireAuthorization("Organiser"); ``` What eviction does, precisely: - removes every entry **in that store** whose tag set contains the tag; - does not touch copies a browser or CDN may hold; those follow whatever `Cache-Control` the endpoint itself sent; - does not refresh anything; the next request for each URL misses and runs the endpoint again. Here a longer `Expire` becomes reasonable, provided every edit evicts; expiry is then a backstop rather than the freshness mechanism. ## Choosing tags Tags are free-form strings, so the design is yours. A workable scheme for the festival site: - a **broad tag** per resource type (`events`) on every list, search and calendar view that shows events; - a **narrow tag** per item (`event-42`) on that event's own page; - a **cross-cutting tag** for shared fragments (`lineup`) when one edit changes several pages. The edit path then evicts the broad tag plus the narrow one for the edited item. Every write path has to remember this: an import job, an admin bulk update or a cancellation webhook that changes events without evicting leaves stale listings until expiry. Centralising the eviction in the service that saves events, rather than in each endpoint, keeps the rule in one place. ## Why three instances break it The default `MemoryOutputCacheStore` keeps entries in a `MemoryCache` and its tag index in a dictionary, both inside one process. Behind a load balancer: 1. instance A serves the organiser's `PUT` and evicts `events` from **its** memory; 2. instances B and C never hear about it; 3. visitors routed to B or C see the old listing until those entries expire, up to 30 minutes here. ## The Redis store ASP.NET Core 8 added a Redis-backed store in its own package, `Microsoft.AspNetCore.OutputCaching.StackExchangeRedis` (the middleware itself ships in the shared framework): ```csharp builder.Services.AddOutputCache(o => o.AddPolicy("Listings", b => b.Tag("events"))); builder.Services.AddStackExchangeRedisOutputCache(o => { o.Configuration = builder.Configuration.GetConnectionString("redis"); o.InstanceName = "festival:"; }); ``` | | In-memory store | Redis store | |---|---|---| | Registered by | `AddOutputCache` | `AddStackExchangeRedisOutputCache` | | Shared by instances | no | yes | | Survives a restart | no | yes, until each entry's lifetime ends | | Eviction reach | one process | every instance | | Capacity setting | `OutputCacheOptions.SizeLimit` | Redis's own memory limits | The Redis store saves each response under a key prefixed with `InstanceName`, with the entry's lifetime as its expiry, and records each tag in a Redis sorted set; `EvictByTagAsync` walks that set and deletes the entries. Do not confuse it with **`AddStackExchangeRedisCache`**: that registers `IDistributedCache`, which output caching does not use, and the docs advise against building an output cache store on `IDistributedCache` because it lacks the atomic operations tagging needs. ## Failure behaviour - A failed lookup is logged (`UnableToQueryOutputCache`) and treated as a miss; a failed write is logged (`UnableToWriteToOutputCache`); the request itself still succeeds. - The Redis store adds tag entries fire-and-forget to save latency, so a tag write error can go unnoticed. - An exception from `EvictByTagAsync` surfaces in your handler; decide whether the edit should still report success, keeping expiry as the fallback.
- Does the order of AddOutputCache and AddStackExchangeRedisOutputCache matter?No. `AddOutputCache` registers its in-memory store with `TryAddSingleton`, so it backs off if a store already exists, while `AddStackExchangeRedisOutputCache` uses `AddSingleton`, so the Redis store is resolved even when it is registered second. You still need `AddOutputCache` for the options and `UseOutputCache` for the middleware.
- Why not simply shorten the expiration to a few seconds instead of evicting by tag?Short lifetimes bound staleness but throw away most of the benefit: every popular listing is rebuilt every few seconds whether or not anything changed. Tag eviction lets entries live long and disappear the moment an organiser edits, with expiry kept only as a safety net.
- Can the edit endpoint evict a single event's page without dropping all listings?Yes, if that page was stored with its own tag. Add a tag such as `event-42` at request time through `IOutputCacheFeature.Context.Tags`, or from a custom policy reading the route value, then call `EvictByTagAsync("event-42")` for that page and keep the broader `events` tag for lists.
- EvictByTagAsync on one instance clears the in-memory caches of all instances.
- AddStackExchangeRedisCache makes the output cache use Redis.
- Tag("event-" + id) inside the policy builder gives each request its own tag.
- Evicting a tag also purges copies cached by browsers and CDNs.
- IOutputCacheStore is scoped, so it cannot be injected into a singleton.
Assumes ASP.NET Core 10; output caching arrived in ASP.NET Core 7 and the Redis output cache store package in ASP.NET Core 8, which 10.0.12 builds against StackExchange.Redis 2.7.27.