Cached fragments
Cached draws what it wraps once and hands that markup to every later request that would draw the same —
ASP.NET's <cache> tag helper and Blazor's CacheView, for a Rask page. It is for the expensive part of a page
that changes rarely: a dashboard's aggregates, a filter's long option list, a price table.
Cached.Name("sales-summary").For(10.Minutes)[
SalesSummary // its OnMount runs the aggregate query
]
The first request mounts SalesSummary, waits for its data as any first GET does, and stores the markup it drew.
Every request after that, for ten minutes, is handed the markup — SalesSummary is never mounted, so its query never
runs.
Hide and show the report: it is handed the kept markup, never mounted, so its caption still says draw #1. Forget it, then hide and show: it is drawn afresh. In the browser the copy lives in the tab; on a server, in the app's HybridCache or an in-process store, for every later request.
namespace Rask.Site.Features;
/// <summary>
/// A report behind <c>Cached</c>: shown once it is drawn and its markup kept; hidden and shown again it is handed
/// the kept markup, and the report is never mounted — its caption still says draw #1. Forget it and the next show draws
/// it afresh. The buttons sit next to the fragment, never in it: what it keeps is static.
/// </summary>
public sealed partial class CachedReportDemo : Component
{
private readonly ReportDraws _draws = new();
private bool _shown = true;
private int _shows;
protected override Component? Render() =>
Div.Class("space-y-3")[
Div.Class("flex flex-wrap items-center gap-2")[
Ui.Button.Id("cached-toggle").OnClick(Toggle)[_shown ? "Hide the report" : "Show the report"],
Ui.Button.Id("cached-forget").OnClick(Forget)["Forget it"]
],
_shown
// Keyed by the showing, so each show is a fresh fragment that looks its markup up again.
? Cached.Name("demo-report").For(10.Minutes).Key(_shows)[CachedReport.Draws(_draws)]
: P.Class("text-sm text-zinc-500")["Hidden."]
];
private void Toggle()
{
_shown = !_shown;
_shows++;
}
private static async Task Forget() => await CachedFragments.Forget("demo-report");
}| North | 12,400 |
| South | 9,870 |
| East | 15,210 |
What it varies by
A fragment is stored under its name plus everything it varies by. Three things are always in the key:
| Always | Why |
|---|---|
The tenant (the rask:tenant claim) |
No tenant ever sees another's markup — and there is no step that turns this off. |
| The signed-in user | One user's markup is never served to another, unless the fragment says .AcrossUsers(). |
| The culture and UI culture | Numbers, dates and words are formatted in them. |
Everything else is a step:
Cached.Name("orders").VaryByQuery("status", "page")[OrderTable] // ?status=…&page=…
Cached.Name("breadcrumbs").VaryByRoute()[Breadcrumbs] // the path, so every route value
Cached.Name("hero").VaryByHeader("User-Agent")[Hero] // a request header
Cached.Name("product").VaryBy(product.Id)[ProductSpecs] // a value of your own
Cached.Name("filters").AcrossUsers()[VehicleFilter] // one copy per tenant, for every user
.AcrossUsers() is only for markup that says nothing about who is looking — a list of the tenant's vehicles, not
"your vehicles". When a user cannot be told apart (a principal still loading, a signed-in user with no id claim), or a
header or route it varies by cannot be read, the fragment is drawn live and never stored: no key is safer than a key
that could hand one visitor's markup to another.
How long it is kept
Cached.Name("rates").For(1.Hour)[Rates] // absolute: one hour after it was drawn
Cached.Name("rates").For(1.Hour).Sliding(10.Minutes)[Rates] // …or ten minutes unread, whichever is first
Without .For(…) a fragment is kept five minutes (CachedOptions.DefaultLifetime).
Forgetting
After a write that changes what a fragment shows, forget it by name or by tag — for every user, tenant and value it varies by:
Cached.Name("price-list").Tags("catalog")[PriceList]
await CachedFragments.Forget("catalog"); // every fragment tagged catalog
await CachedFragments.Forget("price-list"); // every copy of that fragment
Where it is kept
| Host | Store |
|---|---|
Server, with AddHybridCache() |
The app's HybridCache — shared by every server behind it; Forget is its RemoveByTagAsync. |
| Server, without one | In process, bounded by CachedOptions.SizeLimit (64 MB); least recently read goes first. |
| WebAssembly | In the tab's memory. There are no other users to share with, so it saves re-drawing a page you come back to. |
builder.Services.Configure<CachedOptions>(o =>
{
o.SizeLimit = 128.Megabytes; // the in-process store's bound
o.MaxEntrySize = 2.Megabytes; // a bigger fragment is drawn live every time
o.DefaultLifetime = 10.Minutes;
});
On a server the same three settings come from the Rask:Cached section of appsettings.json (or the environment,
Rask__Cached__SizeLimit), and a Configure<CachedOptions> in code wins over it:
{
"Rask": {
"Cached": { "SizeLimit": 134217728, "MaxEntrySize": 2097152, "DefaultLifetime": "00:10:00" }
}
}
Each must be positive; a zero or negative value stops the host at start, naming Rask:Cached.
A cache that cannot be read or written never takes the page down: the fragment is drawn live.
What it may hold
What it keeps is static markup, served to later visitors where nothing would answer a click. So it refuses, naming the fragment and the attribute it found:
- an event handler —
Button.OnClick(…),Form.OnSubmit(…), aLazy; - a bound input —
Input.Bind(…); - an element reference —
.Ref(…); - a component that contributes to the page's head.
Only the attribute itself counts: a visitor's text or an attribute value that happens to quote data-rask-on-click is
stored like any other markup, so nothing a visitor types can stop a fragment from being kept.
Written straight into the fragment, RASK117 stops the build; inside a component it wraps, the first render that would store it throws:
Cached.Name("cart") holds an event handler (data-rask-on-click). What it keeps is served to later visitors as plain
HTML, where nothing would answer it. Move the interactive part outside Cached.Name("cart")[ … ], next to it, and keep
only static markup inside.
Put the interactive part next to the fragment, not in it:
Div[
Cached.Name("vehicle-options").AcrossUsers()[VehicleOptions], // the long, static list
Ui.Button.OnClick(Apply)["Apply"] // the live part, outside
]
In a live page
The stored markup is one verbatim frame in the page, which the diff leaves alone while it is unchanged — an opaque island. The session that drew a miss keeps what it wraps live; every later one is handed the markup. A live page keeps what it drew until the key changes (a query value it varies by, a sign-in), and then looks again.
A hit mounts nothing, so put the expensive work in a component the fragment wraps. A query written in the page's
own Render, in the markup handed to Cached[…], has already run by the time the fragment is asked.
See also
- Cache —
Cache.Remember(…)for values rather than markup. - Lifecycle — the first
GETwaits forOnMount, which is what a stored fragment captures. - Multi-tenancy — where the
rask:tenantclaim comes from.