Rustango docs

Cache an expensive query

Problem

A homepage aggregate recomputes on every request even though it changes rarely.

Wrap the computation in get_or_set against the pluggable Cache — the closure only runs on a miss.

use rustango::cache::get_or_set;
use std::time::Duration;

let stats: HomeStats = get_or_set(
    &*cache,
    "home:stats",
    || async { compute_home_stats(&pool).await.unwrap() },
    Some(Duration::from_secs(60)),
).await?;

Backends

InMemoryCache for one process; switch to RedisCache (feature cache-redis) to share the cache across replicas — no code change at the call site.