Interactive Learning Platform Nuxt layer

Isolated learning atmosphere · v4.x

← Back to writing
Step 3 of 9defineCachedHandler + SWR

Cache the Board: Two Seconds, One Honest Header

Wrap the depot snapshot in defineCachedHandler, add stale-while-revalidate, keep tariffs on a one-hour clock, and read x-cache in the UI so the lesson never lies about what it served.

A depot board is read far more often than it changes. Stage 3 puts a short, honest cache in front of it: two seconds of freshness, ten seconds of stale tolerance, and an x-cache header the UI can show.

ampyard / preview / 3
Live stage Open app ↗
Ampyard · live stageStage 3 / 9

What it is#

Nitro's cache layer has three entry points:

  • defineCachedHandler caches the full response of an event handler.
  • defineCachedFunction caches the result of any function and lets you invalidate it later.
  • Route rules turn caching on for a path pattern without touching handler code.

Ampyard uses defineCachedHandler for the board and the tariff table. The board is hot and short-lived. The tariffs are cold and long-lived.

server/api/depot.get.ts
export default defineCachedHandler(async () => buildSnapshot(), {
  name: "depot-snapshot",
  maxAge: 2,
  swr: true,
  staleMaxAge: 10,
  shouldBypassCache: (event) =>
    event.req.headers.get("x-ampyard-refresh") === "1",
});

maxAge: 2 means an entry is fresh for two seconds. With swr: true, an expired entry is served immediately while a fresh one is built in the background. staleMaxAge: 10 bounds how long a stale entry may be served. Nitro also synthesizes a cache-control lifetime and an x-cache status, so the response is honest about what it served.

The tariffs get a different bargain:

server/api/tariffs.get.ts
export default defineCachedHandler(async () => currentTariffs(), {
  name: "depot-tariffs",
  maxAge: 60 * 60,
  swr: true,
  staleMaxAge: 60 * 60 * 24,
});

Why you'd care#

The board is the most expensive read in the app. One snapshot touches D1 for the live bay state, today's totals, the last events, and the queue. Without a cache, ten thousand readers become ten thousand database round trips.

The cache also gives you a vocabulary for freshness:

  • Two seconds is short enough that a driver does not notice, long enough that a burst of page loads shares one snapshot.
  • Stale-while-revalidate keeps response times flat when the two seconds expire. The first reader after expiry gets the old board and triggers the rebuild.
  • x-cache tells the UI whether it is looking at a HIT, MISS, STALE, or REVALIDATED response. That is how the lesson stays honest.

What we're building#

  • A cached board route with a two-second fresh window and a ten-second stale window.
  • A cached tariff route with a one-hour fresh window.
  • A cache badge in the board header.
  • A UI that never assumes a refresh means a miss.

Before#

The stage 2 board calls buildSnapshot() on every request:

ts
export default defineHandler(async () => buildSnapshot());

Two readers in the same second pay for two full snapshots.

After#

The stage 3 board shares one snapshot across a burst:

ts
export default defineCachedHandler(async () => buildSnapshot(), {
  name: "depot-snapshot",
  maxAge: 2,
  swr: true,
  staleMaxAge: 10,
  shouldBypassCache: (event) =>
    event.req.headers.get("x-ampyard-refresh") === "1",
});

The client reads the cache status from the response headers:

app/composables/useDepot.ts
const response = await fetch("/api/depot", {
  headers: { accept: "application/json" },
});
cacheStatus.value = response.headers.get("x-cache") ?? "";
snapshot.value = (await response.json()) as DepotSnapshot;

The board header shows it:

app/pages/DepotPage.vue
<span v-if="stage >= 3" class="pill">cache {{ cacheStatus || "MISS" }}</span>

Refresh the page twice. The first request is a MISS; the second, inside two seconds, is a HIT. If the entry is stale and the refresh happens in the background, you see STALE or REVALIDATED.

The cache key#

The generated key includes the request origin, path, and method. For the board that is enough: every reader asks for the same /api/depot.

A cached handler also narrows the request before calling your handler. By default:

  • Request headers are stripped unless listed in varies.
  • Query parameters are stripped unless listed in allowQuery.
  • Cookies are stripped unless listed in allowCookies.
  • authorization is stripped unless allowAuthorization is true.

That is a security feature, not an inconvenience. A handler cannot accidentally render per-user data under a shared key if it never sees the user. If the board ever grows a personalised view, it needs a separate key, not a bigger cache.

Do it yourself#

Start the app and watch the header:

bash
pnpm --filter ampyard dev

First request:

bash
curl -si http://localhost:4321/api/depot | grep -i x-cache
# x-cache: MISS

Second request within two seconds:

bash
curl -si http://localhost:4321/api/depot | grep -i x-cache
# x-cache: HIT

Wait three seconds and try again. You may see STALE while the fresh snapshot is built. A later request sees REVALIDATED or HIT.

The tariff route is easier to observe:

bash
curl -si http://localhost:4321/api/tariffs | grep -i x-cache

Because it is cached for an hour, the first request is a miss and every request after it is a hit until the process restarts or the entry is invalidated.

The live stage#

The preview above is /preview/3. The board now shows a cache badge next to the live/refresh controls. The tariff strip appears below the queue area. At stage 3 there are still no holds and no ledger; the cache is the only new moving part.

Gotchas#

  • maxAge defaults to one second. Always set it explicitly. A missing maxAge is not "cache forever"; it is "barely cache".
  • A write needs a fresh read. The board sends x-ampyard-refresh: 1 after a hold or queue action, and shouldBypassCache skips the cached entry. Without it, the first refresh can serve the pre-write snapshot for the whole stale window.
  • A cached response advertises its lifetime. Nitro synthesizes cache-control and x-cache. With maxAge: 2, a CDN may hold the board for two seconds. That is fine for a public depot board; it is not fine for a per-user view. Use no-store or a bypass when the response must not be shared.
  • Cached handlers only cache GET and HEAD. POST, PUT, DELETE, and Range requests bypass the cache.
  • A cached handler sees a narrowed request. If you need a query string or a cookie in the handler, opt it in with allowQuery or allowCookies.
  • Cache entries are JSON. Do not return a class instance, a stream, or a Map from a cached function and expect it to survive.
  • Invalidation needs a function. defineCachedHandler returns a plain handler, so it cannot be invalidated on demand. Move the expensive work into a defineCachedFunction and call .invalidate() when the underlying data changes.

Recap#

The board now has a short, honest cache: two seconds fresh, ten seconds stale, one x-cache header, and a UI that shows it. The tariff table is cached for an hour because prices do not move with traffic.

Stage 4 gives the board a memory: D1 holds, a live queue, and the first writes.

Next: D1 Holds and the Queue.