cache

Add Cache-Control headers to successful responses. Queries only — mutations cannot be cached (compilation error).

Basic Usage

rust
// Cache for 1 hour on Vercel CDN
#[rpc_query(cache = "1h")]
async fn get_products() -> Vec<Product> { ... }

Duration Shorthand

rust
#[rpc_query(cache = "30s")]   // 30 seconds
#[rpc_query(cache = "5m")]    // 5 minutes
#[rpc_query(cache = "1h")]    // 1 hour
#[rpc_query(cache = "1d")]    // 1 day
SuffixUnitExample
sseconds30s → max-age=30
mminutes5m → max-age=300
hhours1h → max-age=3600
ddays1d → max-age=86400

Public vs Private

By default caches are public (shared on CDN). Prefix with private, for user-specific data that should only be cached in the browser.

rust
// Browser-only cache (no CDN) — user-specific data
#[rpc_query(cache = "private, 10m")]
async fn get_profile() -> Profile { ... }

// Public (default) — shared across all users on CDN
#[rpc_query(cache = "1h")]
async fn get_products() -> Vec<Product> { ... }

Combining Attributes

rust
// Combine with other attributes
#[rpc_query(cache = "1h", timeout = "5s", init = "setup")]
async fn fast_cached(db: &PgPool) -> Stats { ... }

// Compile error — mutations cannot be cached
// #[rpc_mutation(cache = "1h")]
// async fn create_order(input: OrderInput) -> Order { ... }

Try it

Each demo calls a real lambda that returns the server timestamp. When cached, the server time stays the same across refetches while the client time updates.

Public — CDN Cache 30s

Cache-Control: public, max-age=0, s-maxage=30

Private — Browser Cache 1m

Cache-Control: private, max-age=60

visit GitHub to learn more about metaxy