Server caching, jobs, and actions
For each server-rendered route, decide whether its page is public and reusable, public but periodically refreshed, or private to one session. Fission makes that choice explicit through route modes, cache settings, jobs, and signed actions.
1. Choose what may be reused
First decide whether the complete HTML response is safe to share between users.
Use ServerPrivate for pages that contain a cart, account panel, preferences, permissions, or any other session-specific data:
.route_widget_with_state::<StoreState, _, _>(
"/",
"Pokemon Card Store",
Some("A server-rendered storefront.".to_string()),
WebRouteMode::ServerPrivate(ServerPrivatePolicy::default()),
StoreHomePage,
|ctx| Ok(StoreState::for_session(ctx.session.id())),
)
The session ID is opaque. Use it as a key into your cart service, database session table, or cache entry. Don’t put user data inside it.
Use Revalidated when the full page is public and can be reused for a period:
WebRouteMode::Revalidated(
RevalidationPolicy::new(Duration::from_secs(300))
.stale_while_revalidate(Duration::from_secs(60))
.tag("catalog")
.vary("accept-language"),
)
The revalidated page cache key includes the normalized query string, app identity, locale, theme fingerprint, build ID, and declared vary headers. Fission doesn’t vary on every cookie or header; doing so can explode the cache. If a header changes a public page, declare it with vary. If a cookie changes the page, make the route private.
The default is an in-process Moka cache. It works for local development, single-process services, and simple deployments.
[server.cache]
provider = "moka"
max_capacity = 10000
ttl = "5m"
stale_while_revalidate = "1m"
For multiple server processes, use Redis or a cache pipeline. Keep the Redis URL in an environment variable, not fission.toml.
[server.cache]
provider = "pipeline"
[[server.cache.layers]]
name = "hot"
provider = "moka"
policy = "hot-only"
max_capacity = 2048
[[server.cache.layers]]
name = "shared"
provider = "redis"
policy = "write-through"
url_env = "REDIS_URL"
prefix = "pokemon-store"
Enable Redis through the facade feature in the server app's Cargo.toml:
[dependencies]
fission = { version = "0.16.0", features = ["server", "server-redis"] }
Invalidate cached pages after writes
Route tags connect your app data to the page cache. If changing a post should refresh the blog landing page, its detail page, and a topic page, tag those routes with values such as posts, post:<id>, and topic:<slug>.
Application-owned services can use the cache handle directly when they already own the invalidation policy:
renderer
.cache()
.invalidate_tags(&[CacheTag::new("posts"), CacheTag::new("post:hello-world")])?;
Admin and publishing workflows can call the renderer helpers instead:
renderer.invalidate_cache_tags(["posts", "post:hello-world"])?;
Both paths return an InvalidationReport with the number of affected cache keys, tag indexes, and cache layers.
An external publisher can use a protected invalidation endpoint:
let app = FissionServerApp::new("Docs")
.cache_invalidation_endpoint(
"/admin/cache/invalidate",
std::env::var("CACHE_INVALIDATION_TOKEN")?,
)
.route_widget::<DocsState, _>(
"/posts/:slug",
"Post",
None,
WebRouteMode::Revalidated(
RevalidationPolicy::new(Duration::from_secs(300))
.tags(["posts", "post:hello-world"]),
),
PostPage,
);
Then the publishing workflow can invalidate related entries without knowing whether the active provider is Moka, Redis, or a cache pipeline:
curl -X POST https://example.com/admin/cache/invalidate \
-H "Authorization: Bearer $CACHE_INVALIDATION_TOKEN" \
-H "Content-Type: application/json" \
--data '{"tags":["posts","post:hello-world"]}'
Use explicit cache keys when the workflow already knows the exact key:
{"tags":["posts"],"keys":["page:/posts/?#app:Docs#..."]}
ServerPrivate routes use a cookie-backed session ID. In production over HTTPS, sign the cookie value and mark it secure.
[server.sessions]
cookie_name = "shop_session"
signing_key_env = "SHOP_SESSION_SECRET"
secure = true
same_site = "lax"
signing_key_env names the environment variable holding the secret. If someone tampers with the cookie, Fission rejects it and creates a new session. Cookies are always HttpOnly; same_site = "none" requires secure = true.
4. Drain jobs before returning HTML
Jobs are server-owned work that prepares route data. The Pokémon store registers a catalog job:
ServerJobRegistry::new().register_job(CATALOG_JOB, |_request, _ctx| {
Ok(catalog_response())
})
A widget declares the job resource during build. It does not execute the job
inside component conversion:
// Inside the catalog component's view setup block.
let loaded = cx.bind(CatalogLoaded, reduce!(on_catalog_loaded));
let failed = cx.bind(CatalogFailed, reduce!(on_catalog_failed));
cx.with_resources(|resources| {
resources.job(
JobResource::new(
ResourceKey::new("store.catalog"),
CATALOG_JOB,
CatalogRequest { generation: 1 },
)
.on_ok(loaded)
.on_err(failed),
);
});
CATALOG_JOB, its request and completion reducers are app-owned. The
reducers replace the catalog snapshot from cx.input.job_ok(CATALOG_JOB) or
job_err(CATALOG_JOB); the view renders pending, data, empty, and error states
from that snapshot. See the catalog recipe
for the typed job and Compose boundary. FutureBuilder can express the same
resource, but its final constructor argument must be an async-widget builder
callback, not an already-built widget. During rendering, Fission drains blocking jobs, dispatches the configured success or error reducer, and renders again until the page settles or reaches render_pass_limit. A missing job fails the render instead of producing an empty page.
5. Use signed action dispatch for mutations
Server actions dispatch reducers from an HTTP request. They’re signed because the server is accepting an external request that changes application state.
The flow is:
render a button or form with a typed Fission action;
let the server renderer emit a signed action token scoped to the route, target node, payload, expiry, and nonce;
accept the HTTP request only if the body size, origin policy, signature, expiry, and replay checks pass;
run the reducer on the server;
return either a post/redirect/get response for normal forms or an HTML response for explicit JSON/fetch enhancement.
A cart mutation also needs outside work. Keep the reducer synchronous and
send owned request data to the app's typed cart job:
#[fission_reducer(AddToCart)]
pub fn on_add_to_cart(
state: &mut StoreState,
slug: String,
ctx: &mut ReducerContext<StoreState>,
) {
if state.updating_cart { return; }
let updated = ctx.effects.bind(CartUpdated, reduce!(cart_updated));
let failed = ctx.effects.bind(CartFailed, reduce!(cart_failed));
state.updating_cart = true;
state.cart_error = None;
ctx.effects.job(ADD_CART_ITEM, AddCartItemRequest {
session_id: state.session_id.clone(),
slug,
}).on_ok(updated).on_err(failed);
}
This is an orchestration excerpt, not a complete cart. The application defines
ADD_CART_ITEM, its request, both completion reducers, and the state fields
shown here. The job authenticates the session, authorises the mutation, checks
current product/stock rules, and returns the authoritative cart. Both
completions clear updating_cart; only success replaces the cart. Do not hide
a blocking database or network call inside cart_service().add_item(...)
in a reducer and call that an effect.
Don’t expose arbitrary Rust functions as HTTP actions. Keep actions narrow and typed: the action describes what happened, and the reducer updates state or requests follow-up work through a job or service.
When the action needs values entered after rendering, give its controls and
submit button one logical form id, then register an explicit typed schema on the
server app:
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
struct SearchSubmitted {
query: String,
archived: bool,
#[serde(default)]
tag: Vec<String>,
}
impl Action for SearchSubmitted {
fn static_id() -> ActionId {
ActionId::from_name("store::SearchSubmitted")
}
}
let schema = ServerFormSchema::new("catalog-search")
.field(ServerFormField::text("query").required().max_length(200))
.field(ServerFormField::boolean("archived"))
.field(ServerFormField::repeated("tag"));
FissionServerApp::new("Store")
.form_action::<SearchSubmitted, SearchSubmitted, _>(schema, |form| form)
// Add routes after registering the form action.
Set name and form_id on each TextInput, and call
.name("archived").form_id("catalog-search") on a Boolean Checkbox.
Repeated checkbox options share a name and supply distinct values, for example
.name("tag").form_id("catalog-search").form_value(tag.slug.clone()). A
retained Select participates in the same form by setting its name,
form_id, and current machine form_value; its localized selected_label
remains presentation only. Associate the submit button with
.form_id("catalog-search"). Fission keeps the route,
target node, action type, expiry, nonce, and form schema inside the signed
token; submitted controls can only populate the already-authorized action type.
Unknown fields, duplicate scalar values, invalid booleans, malformed UTF-8 or
percent encoding, schema violations, oversized bodies, wrong origins, and
replayed tokens are rejected. Use ServerFormField::repeated only where the
typed action deliberately accepts a sequence.
The signed token also preserves the query values from the request that rendered
the form. During the action request, Fission restores those verified values to
ctx.request.query; query text supplied on the POST cannot replace them. This
keeps request context such as OAuth state, PKCE parameters, and a sign-in
return_to value available without copying it into an editable hidden input.
If the action itself already carries trusted context, merge the validated form
fields into that signed action with form_action_with_context:
#[derive(serde::Deserialize)]
struct SearchFields {
query: String,
archived: bool,
}
FissionServerApp::new("Store")
.form_action_with_context::<SearchFields, SearchSubmitted, _>(
schema,
|mut signed_action, fields| {
signed_action.query = fields.query;
signed_action.archived = fields.archived;
signed_action
},
)
The callback receives the verified action payload created during rendering and
the separately validated browser fields. It must return the same action type;
the signed action identity, route, target, form schema, and original query
remain framework-controlled.
6. Keep cached pages and actions separate
Don’t cache a full page containing signed server action forms. The token is short-lived and request-specific. A public cache could replay it for another user or serve an expired control, so Fission rejects this combination.
If a catalogue page needs public revalidation and cart controls, use one of these shapes:
| |
|---|
Keep the page ServerPrivate | The page is simple and the cart summary is part of the main response. |
| The catalogue is public and the cart lives on a private route or drawer endpoint. |
| The main catalogue is reusable and a small Fission WASM island owns cart interaction. |
7. Test the threat model
Test more than the happy path:
| |
|---|
| Fresh entries are reused, stale entries can be reconverted, and invalidation tags clear the right routes. |
| Query order is normalized and declared vary headers create distinct entries. |
| Missing jobs fail clearly and registered jobs produce the expected page data. |
| Unsigned, expired, tampered, oversized, wrong-origin, and replayed requests are rejected. |
| User-specific data is not cached under a public key. |
| Worker and island artifact declarations produce the expected output paths and are served by the server. |
The server shell tests the protocol pieces. Your app should also test its data, reducers, and service calls.