brust 2.0.0-alpha.5
Cookbook / Invalidate the cache

Invalidate the cache

Cache a Pokémon page for a minute, then drop it the moment the team changes.

1Cache the route and tag it

A route with cache is stored in the page cache for ttl_seconds. Tags name the data a page shows, so one call can drop every page that shows it.

routes.tsx
{ path: '/pokemon/{name}', Component: PokemonPage, loader: pokemonLoader,
  cache: { ttl_seconds: 60, tags: ['pokemon', 'team'] } },

2Invalidate from an action

cache.invalidate takes tags, paths or keys. It clears this process at once. Call it only after a real change, so a no-op request does not empty the cache.

actions.ts
import { cache } from '@brust/core'
import { brust } from '@brust/core/elysia'
import { Elysia, problem, t } from 'elysia'

const team: number[] = []
const MAX = 6

const app = new Elysia({ adapter: brust() })
  .get('/team', () => ({ team, max: MAX }))
  .post('/team', { body: t.Object({ id: t.Integer({ minimum: 1 }) }) }, ({ body }) => {
    if (team.length >= MAX) return problem(409, { title: 'TeamFull', max: MAX })
    if (!team.includes(body.id)) {
      team.push(body.id)
      cache.invalidate({ tags: ['team'] })
    }
    return { team, max: MAX }
  })

export default app
export type App = typeof app

3Watch it work

The x-brust-cache header shows what happened. The first request renders (MISS), the second is served from the cache (HIT), the action drops the tag, and the next request renders again.

~/my-app
$ curl -si http://127.0.0.1:1337/pokemon/pikachu | grep -i x-brust-cache
x-brust-cache: MISS
$ curl -si http://127.0.0.1:1337/pokemon/pikachu | grep -i x-brust-cache
x-brust-cache: HIT
$ curl -s -X POST http://127.0.0.1:1337/_brust/action/team -H 'content-type: application/json' -d '{"id":25}'
{"team":[25],"max":6}
$ curl -si http://127.0.0.1:1337/pokemon/pikachu | grep -i x-brust-cache
x-brust-cache: MISS
$ curl -si http://127.0.0.1:1337/pokemon/pikachu | grep -i x-brust-cache
x-brust-cache: HIT

4More than one process

cache.invalidate clears the cache of the process that ran it. With several processes, or on Cloudflare Workers where every isolate has its own cache, the others keep serving the old page until its TTL runs out unless you add a cache adapter that broadcasts the invalidation.

Note

See Cache adapters for the shared tier, and Cache on KV and DO for why Workers need it.