Skip to content

Caching ​

Fusion Stack gets HTTP caching right by default, so clients and caches in between can skip work without ever serving the wrong data: every successful GET gets an ETag, a Cache-Control header and a Vary header. For expensive endpoints you can also cache responses on the server.

ETags and conditional requests ​

Successful GET and HEAD responses carry a weak ETag, a fingerprint of the response body. A client that already has the response sends it back in If-None-Match, and gets a 304 Not Modified with no body when nothing changed:

sh
curl -i localhost:8000/v1/orders
# ETag: W/"519079444424bdcce6a5417d187b74ca"

curl -i localhost:8000/v1/orders -H 'If-None-Match: W/"519079444424bdcce6a5417d187b74ca"'
# HTTP/1.1 304 Not Modified

Each API version has its own ETags, so a client never gets a 304 for a response shaped for another version. A response that sets its own ETag keeps it. The TypeScript client can keep an ETag cache and revalidate for you.

Cache-Control ​

By default responses get Cache-Control: private, no-cache: clients may keep a copy, but must check it with the ETag before using it, and shared caches such as CDNs must not keep it. Change the default with http_cache.cache_control (Config::cache_control in Rust), or per endpoint:

php
#[CacheControl(maxAge: 30, private: true)]
#[Endpoint('Get an order')]
public function show(OrderQuery $query, string $order): OrderResource { ... }
rust
use fusion_stack::CacheControl;

route
    .get("/orders/{order}", orders_show)
    .middleware(CacheControl::new("private, max-age=30"));
php
// Or for a route or group of routes:
Route::get('products', ...)->middleware('cache-control:public,max-age=60');
rust
// Or for a group of routes:
route.middleware(CacheControl::new("public, max-age=60")).group(|route| {
    route.get("/products", products_index);
});

#[CacheControl] takes maxAge, sMaxAge, private, public, noCache, noStore, mustRevalidate and staleWhileRevalidate; Rust's CacheControl middleware takes the same directives as a Cache-Control string. Only mark a response public when every caller may see it.

Vary ​

Every GET and HEAD response carries Vary: Api-Version, Authorization, Accept (http_cache.vary, or Config::vary in Rust), so a shared cache keeps a separate copy per version, per caller and per format. Api-Version is left out while versioning is off.

Cache keys ​

When you cache something yourself, CacheKey (response_cache::cache_key in Rust) builds a key from what the request asks for: the method, path, pinned version, account and query parameters.

php
Cache::remember((string) CacheKey::for($request), 60, fn () => $this->expensiveReport());
rust
use fusion_stack::response_cache;

// The key, and the parts below that it is made of.
let (key, _parts) = response_cache::cache_key(&request);
let report: Value = laravel::cache::remember(&key, 60.seconds(), || expensive_report()).await?;
json
{
  "method": "GET",
  "path": "/v1/reports",
  "version": "2026-11-30.atlas",
  "account": "api_key:1",
  "query": {
    "include": "customer"
  }
}
  • Query parameters are normalised, so include=a,b and include=b,a share a key, while sort=a,b and sort=b,a do not.
  • The account is the client by default, so data scoped to one client is never served to another. Widen it only for data a wider group may see: CacheKey::for($request)->account("team:{$teamId}"). Rust's cache_key has no way to widen the account, so build your own key for data a group shares.

Response cache ​

For an expensive endpoint, #[CacheResponse] (CacheResponse middleware in Rust) keeps its successful GET responses on the server:

php
// Orders include their customer, so customer changes flush these too.
#[CacheResponse(ttl: 60, tags: ['orders', 'customers'])]
#[Endpoint('List orders')]
public function index(OrderQuery $query): AnonymousResourceCollection { ... }

#[CacheResponse(ttl: 60, tags: ['orders:{order}', 'customers'])]
#[Endpoint('Get an order')]
public function show(OrderQuery $query, string $order): OrderResource { ... }
rust
use fusion_stack::CacheResponse;

// Orders include their customer, so customer changes flush these too.
route
    .get("/orders", orders_index)
    .middleware(CacheResponse::new(60).tags(["orders", "customers"]));

route
    .get("/orders/{order}", orders_show)
    .middleware(CacheResponse::new(60).tags(["orders:{order}", "customers"]));
  • Responses are stored in the latest version's shape, so one entry serves every pinned version: older clients get it through their version changes.
  • Entries are kept per client, using the cache key above. A signed-in user may have no client: in PHP, one from a guard that is not in api.auth.guards, and in Rust, one from Laravel's session guard or Authenticate::via. PHP keeps such a user's entries per user. Rust cannot tell such users apart, so their requests skip the cache: they get no X-Response-Cache header. shared: true (.shared() in Rust) keeps one entry for everyone; use it only for data every caller may see.
  • {order} in a tag is replaced with the route parameter, so orders:{order} becomes orders:42.
  • Responses carry X-Response-Cache: hit or miss.

Nothing is cached until an action opts in, and response_cache.enabled (Config::response_cache(false) in Rust) turns every one off at once. Entries live in the cache store response_cache.store (Config::response_cache_store) names, or the default store.

A cache hit skips the controller, so checks made inside it, such as policies or ApiQuery::scope(), do not run. Authentication, #[RequiresScope] and route middleware such as can: run before the cache, so a hit never skips them. In Rust, authentication runs in the FusionStack middleware, before the cache; list RequiresScope, and Authenticate when the route uses Laravel's own guards, before CacheResponse in a route's middleware so they run first too.

Flushing ​

Models using FlushesResponseCache flush their tags when saved or deleted: their table, such as orders, and the record, such as orders:42. Laravel for Rust has no models to hook into, so in Rust call response_cache::flush with the same tags after each write.

php
final class Order extends Model
{
    use FlushesResponseCache;

    // Optional: also flush the customer's entries when an order changes.
    public function responseCacheTags(): array
    {
        return ['orders', "orders:{$this->id}", "customers:{$this->customer_id}"];
    }
}
rust
use fusion_stack::response_cache;

// After saving or deleting the order. Also flush the customer's entries.
response_cache::flush([
    "orders".to_owned(),
    format!("orders:{}", order.id),
    format!("customers:{}", order.customer_id),
])
.await?;

Tags work on every cache store, including file and database.

Released under the MIT License.