In an ASP.NET Core MVC view, how does the cache tag helper store a rendered fragment, how long by default, and what varies its entries?
answer
- a fragment, not the whole response
- its own in-process MemoryCache
- 30-second sliding when nothing is set
- vary-by-user, vary-by-route, vary-by-query
- distributed-cache needs a name
basics
~20 sThe cache tag helper renders its content once and keeps the HTML in a private in-memory cache on each server, for a 30-second sliding expiry unless told otherwise. vary-by-* attributes split entries by user, route, query, header, cookie or culture.
solid answer
~40 s`<cache>` wraps part of a view: the first render stores the fragment's HTML and later requests reuse it while the rest of the page renders normally. `CacheTagHelper` keeps entries in its own `MemoryCache` (not your `IMemoryCache`), capped by `CacheTagHelperOptions.SizeLimit` at 100 MB and configured with `AddCacheTagHelperLimits`, so each server has its own copy. With no `expires-after`, `expires-on` or `expires-sliding`, an entry gets a 30-second sliding expiration (`CacheTagHelperBase.DefaultExpiration`); one docs page still says 20 minutes, but the source says 30 seconds. The key is that element's position in the view plus every `vary-by-*` value: `vary-by-user` (the user name), `vary-by-route`, `vary-by-query`, `vary-by-header`, `vary-by-cookie`, `vary-by-culture` and free-form `vary-by`. `<distributed-cache name="...">` stores through `IDistributedCache` instead, keyed by its required `name`.
code
razor · 14 lines@* Shared by everyone, per culture, for 10 minutes *@
<cache expires-after="@TimeSpan.FromMinutes(10)" vary-by-culture="true">
<vc:best-sellers count="6"></vc:best-sellers>
</cache>
@* Per user: without vary-by-user one user's list leaks to everyone *@
<cache vary-by-user="true" expires-sliding="@TimeSpan.FromMinutes(5)">
<vc:recently-viewed></vc:recently-viewed>
</cache>
@* Shared across servers through IDistributedCache *@
<distributed-cache name="seasonal-banner" expires-after="@TimeSpan.FromHours(1)">
<partial name="_SeasonalBanner" />
</distributed-cache>go deeper
Recall that <cache> stores a rendered part of a view and that vary-by attributes control who shares an entry.
Explain the private in-memory store, the expiry attributes and the 30-second sliding default, and when <distributed-cache> applies.
Prevent per-user leaks with vary-by-user, account for per-server copies in a farm, and decide what work actually sits inside the cached block.
Choose the caching layer per page, fragment versus response versus data, and own the invalidation rules that go with each.
## A fragment cache inside the view The **cache tag helper** caches a piece of rendered HTML, not a whole response. On a garden-centre home page, the "best sellers this week" panel needs a query and some formatting, while the header, the basket summary and the rest of the page differ per visitor: ```razor <cache expires-after="@TimeSpan.FromMinutes(10)" vary-by-culture="true"> <partial name="_BestSellers" model="Model.BestSellers" /> </cache> ``` On the first request, Razor renders the content inside `<cache>`, the tag helper stores the HTML, and later requests write the stored HTML instead of rendering the content again. The action and the rest of the view still run on every request, so this saves rendering work inside the view, not the controller's work. If the controller loads the best-seller data for the panel, that load still happens each time; the saving is largest when the expensive work happens inside the cached block, for example in a view component it invokes. ## Where the entries live - `CacheTagHelper` uses a **private `MemoryCache`** created by `CacheTagHelperMemoryCacheFactory`, separate from the `IMemoryCache` your services use. - That cache has a size limit, `CacheTagHelperOptions.SizeLimit`, of **100 MB** by default, changed with `services.AddControllersWithViews().AddCacheTagHelperLimits(o => o.SizeLimit = ...)`. - It is **in-process**: each server in a farm builds and holds its own copy, and an app restart empties it. ## How long an entry lives | Attribute | Meaning | |---|---| | `expires-after` | absolute expiry, a `TimeSpan` from when the entry was stored | | `expires-on` | absolute expiry at a `DateTimeOffset` | | `expires-sliding` | sliding expiry, renewed on every hit | | *(none of the three)* | sliding expiry of **30 seconds** | | `priority` | `CacheItemPriority` used when memory pressure evicts entries | | `enabled="false"` | renders the content without caching it | The 30-second default comes from `CacheTagHelperBase.DefaultExpiration = TimeSpan.FromSeconds(30)`. The cache tag helper docs page states it in one place and says "default 20 minutes" in another; the pinned source is what runs. ## What varies an entry Each `<cache>` element has its own key, built from the element's unique position in the compiled view plus the vary values: - `vary-by-user="true"`: the signed-in user's name, so each user gets their own entry; - `vary-by-route="id"`: route values, comma-separated; - `vary-by-query="sort,page"`: query-string keys; - `vary-by-header="Accept-Language"` and `vary-by-cookie="theme"`; - `vary-by-culture="true"`: the current culture and UI culture; - `vary-by="@Model.CategoryId"`: any string you compute. The most common production bug is a per-user fragment cached **without** `vary-by-user`: the first visitor's name or basket appears for everyone until the entry expires. ## The distributed variant `<distributed-cache name="best-sellers">` has the same vary and expiry attributes but stores the bytes through `IDistributedCache`, so a Redis or SQL Server cache shares one entry across servers and survives restarts. Its key is the required `name` plus the vary values, so two elements using the same name share entries, which is useful on purpose and surprising by accident. MVC's tag helper registration adds an in-memory `IDistributedCache` as a fallback, so without a real distributed cache registered it is still per server. ## Choosing what goes inside 1. Cache output that is **expensive and shared**: a best-seller panel, a category menu, a rendered blog teaser. Cheap markup gains nothing and costs memory. 2. Keep **per-request values** out, or vary on them: anything that depends on the user, culture or query string needs the matching `vary-by-*`. 3. Do not wrap a **form** in `<cache>`: the form tag helper writes a hidden request token that belongs to one visitor, and a cached copy hands that token to everyone else, so their posts fail validation. 4. Decide the expiry from how stale the data may be, and set it explicitly; the 30-second sliding default rarely matches a business rule. ## How it differs from other caches Caching whole HTTP responses through middleware, `[OutputCache]` or `[ResponseCache]` is a different layer. The cache tag helper is the tool when one panel is expensive and the rest of the page must stay dynamic.
- Users report seeing another customer's recently viewed plants in a cached panel. What is the likely cause?The `<cache>` block holds per-user content but does not set `vary-by-user="true"`, so its key is the same for everyone and the first visitor's HTML is reused until the entry expires. Add `vary-by-user` (keyed by the user's name), or leave per-user fragments out of the cache.
- Why might a <cache> fragment look different on two servers behind a load balancer?`CacheTagHelper` stores entries in a private in-process `MemoryCache`, so each server renders and keeps its own copy with its own expiry clock. To share one copy, use `<distributed-cache name="...">` backed by a real `IDistributedCache` such as Redis.
- The cache tag helper stores fragments in the app's registered IMemoryCache
- A <cache> block with no expiry attributes is kept for 20 minutes
- The cache tag helper stops the controller action from running on later requests
- One <cache> entry is automatically per user, since pages are per request
- <distributed-cache> works without a name because the position is the key