# Caching and ISR

This page is the guide through Hamur's caches: which tool to take, how to name what you cached with tags, how to drop it again, what `isr` does on each preset, and how several instances share one cache. The option tables, error messages and edge cases are in [Storage and cache](/storage-and-cache), [Route rules and prerender](/route-rules), [Deploy](/deploy) and the [server reference](/api-reference/server); each section below links to them.

## Choosing a tool

| You want to                                             | Use                                                                                                                                                       |
| ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| keep a page or a `GET` route for a while                | a route rule: `swr`, `cache` or `isr` ([Route rules](/api-reference/storage-details#route-rules), [ISR](#isr))                                            |
| keep what a `GET` handler answers, by its input         | `cache` on the handler ([Cache](/api-reference/storage-details#cache))                                                                                    |
| keep what a function returns                            | `defineCachedFunction`                                                                                                                                    |
| keep what a raw server route answers (a feed, an image) | a route rule's `cache` or `swr` on its path ([Route rules](/api-reference/storage-details#route-rules))                                                   |
| keep the answer of an upstream API                      | `$fetch` with `serverCache` ([Fetch cache](/api-reference/storage-details#fetch-cache))                                                                   |
| run a read once per request                             | nothing to write for `GET` handler calls and `ctx.fetch`; `memo` for the rest ([Request memoization](/api-reference/storage-details#request-memoization)) |
| drop entries when your data changes                     | `revalidateTag`, `revalidatePath`, or the [endpoint](#from-outside-the-app)                                                                               |
| render a page once at build time                        | `prerender` ([Prerender](/route-rules#prerender))                                                                                                         |

There is one engine under all of them. Entries live in storage mounts, so the same options, keys and tags work for each ([Where entries live](/api-reference/storage-details#where-entries-live)).

## Tags

A tag names entries so that one call drops them all. Three things add tags to an entry:

- the `tags` option of `defineCachedFunction`, a `GET` handler's `cache` and a rule's `cache`;
- `cacheTag(event, ...tags)` called while the entry is being computed, in a `load`, a handler or code on the cache fork;
- Hamur itself, with no code from you: `path:<pathname>` on every cached answer, `route:<route name>` on a page a rule caches, and `layout:<prefix>` for each prefix of the path (`/blog/a` gives `layout:/`, `layout:/blog` and `layout:/blog/a`).

A cache read while another entry is computed gives its tags to that entry, so revalidating the tag of a cached function also drops the page that used it.

````ts [caching/posts.ts]
import { cacheTag, defineHandler, noStore } from "hamur/server"

interface Post {
  slug: string
  title: string
  author: string
  draft: boolean
}

declare const db: {
  posts: { list(): Promise<Post[]>; get(slug: string): Promise<Post> }
}

export const listPosts = defineHandler({
  route: "/api/posts",
  method: "GET",
  cache: { maxAge: 3600, tags: ["posts"] },
  handler: () => db.posts.list(),
})

export const getPost = defineHandler({
  route: "/api/post",
  method: "GET",
  cache: { maxAge: 3600 },
  async handler(input: { slug: string }, { event }) {
    const post = await db.posts.get(input.slug)
    cacheTag(event, "posts", `author:${post.author}`)
    if (post.draft) noStore(event)
    return post
  },
})
````

`getPost` is cached for an hour. Each answer carries `posts` and its author's tag, and a draft is not stored. Tags are 1 to 256 printable ASCII characters without spaces or commas, and `path:`, `route:` and `layout:` are Hamur's own: pass them to `revalidateTag`, never to `tags` or `cacheTag`. See [`cacheTag` and `revalidateTag`](/api-reference/server#cachetag-revalidatetag).

## Revalidating

`revalidateTag(tags, { mode })` needs no event and resolves when the tag index is written.

- `"expire"` (the default): the next read of every entry with the tag misses and waits for a new value.
- `"stale"`: the next read gets the stored value at once and starts one refresh in the background, also without `swr` and past `staleMaxAge`. The answer carries `x-hamur-cache: STALE`.

`revalidatePath(path, type?)` revalidates through the tags Hamur adds. A concrete path (`/blog/a`) drops that pathname for every host and query. `"page"` takes the page's file path (`/blog/[slug]`) and drops every URL of that page. `"layout"` takes a prefix (`/blog`) and drops every page and server route at or under it. `invalidateRouteCache(url)` is the exact-URL form and uses no tags.

````ts [caching/publish.ts]
import { defineHandler, revalidatePath, revalidateTag } from "hamur/server"

declare const db: {
  posts: { publish(slug: string): Promise<{ author: string }> }
}

export const publishPost = defineHandler({
  async handler(input: { slug: string }) {
    const post = await db.posts.publish(input.slug)
    await revalidateTag(`author:${post.author}`)
    await revalidateTag("posts", { mode: "stale" })
    await revalidatePath(`/blog/${input.slug}`)
    await revalidatePath("/blog/[slug]", "page")
    await revalidatePath("/blog", "layout")
  },
})
````

The two calls on the entries of one cache, `invalidate(...args)` and `expire(...args)`, remove or expire a single key; see [Expiring and bypassing](/api-reference/server#definecachedfunction-cachedfunctionoptions-cacheoptions-cacheentry).

### From outside the app

A CMS or a deploy script revalidates over HTTP. Turn the endpoint on with `server.revalidate` ([On-demand revalidation](/api-reference/storage-details#on-demand-revalidation) has the token rules, the statuses and the limit of 1000 tags and paths per request):

````sh [caching/revalidate-request.sh]
curl -X POST https://example.com/_hamur/revalidate \
  -H "Authorization: Bearer $HAMUR_REVALIDATE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "tags": ["posts"], "paths": ["/blog/a", { "path": "/blog", "type": "layout" }] }'
````

The body is checked as a whole before anything is revalidated, so a bad tag leaves every other tag alone.

## Lifetimes, profiles and defaults

A route rule or an option sets the lifetime; code running inside the cache can shorten it for one answer with `cacheLife(event, profile)`. A profile is a named `{ maxAge, staleMaxAge?, clientMaxAge? }`. The built-ins are `seconds`, `minutes`, `hours`, `days`, `weeks` and `max`; `server.cache.profiles` adds names or replaces them, and `server.cache.defaults` is merged under every cache. Lowest first, a lifetime comes from the defaults, the profile, the fields of the call or rule, and last what the fill calls (`cacheLife`, `cacheTag`, `noStore`).

````ts [caching/profiles-config.ts]
import { defineConfig } from "hamur"

export default defineConfig({
  framework: "react",
  server: {
    cache: {
      profiles: { blog: { maxAge: 600, staleMaxAge: 86400, clientMaxAge: 60 } },
      defaults: { maxResolveTime: 10, staleIfError: 3600 },
    },
  },
  routeRules: {
    "/blog/**": { cache: "blog" },
    "/prices": { swr: "minutes" },
  },
})
````

````ts [caching/profile-handler.ts]
import { cacheLife, defineHandler } from "hamur/server"

declare const market: { price(): Promise<{ value: number; halted: boolean }> }

export const quote = defineHandler({
  route: "/api/quote",
  method: "GET",
  cache: { maxAge: 3600 },
  async handler(_input: undefined, { event }) {
    const price = await market.price()
    cacheLife(event, price.halted ? "seconds" : "hours")
    return price
  },
})
````

Several `cacheLife` calls keep the shortest `maxAge`. A cache read inside another keeps its own lifetime and does not shorten the outer entry. `noStore(event)` cancels the cache for one request instead: the answer is `private, no-store` and nothing is stored ([Opting a request out](/api-reference/server#nostore)). See [`cacheLife`](/api-reference/server#cachelife-cacheprofile) and [`noStore`](/api-reference/server#nostore).

## ISR

`isr` is a route rule. `isr: 60` caches a page or a `GET` server route for 60 seconds, then serves the old copy once and renders the page again in the background, as `swr: 60` does. `isr: true` keeps the copy until the next deploy or a revalidation, and `isr: false` lifts a broader `isr`. There is no `static` rule: a page written at build time is `prerender`, and a prerendered path with `isr` gives the build's page as the first copy (last column below).

````ts [caching/isr-config.ts]
import { defineConfig, env } from "hamur"

export default defineConfig({
  framework: "react",
  preset: "vercel",
  routeRules: {
    "/news": { prerender: true, isr: 60 },
    "/blog/**": { isr: true, cache: { tags: ["posts"] } },
    "/blog/drafts/**": { isr: false },
  },
  server: {
    revalidate: { token: env("REVALIDATE_TOKEN") },
    cdnPurge: { vercel: { projectId: "prj_example", token: env("VERCEL_PURGE_TOKEN") } },
  },
})
````

What the preset does with the rule is the difference between hosts. The rule itself, its errors and the `bun` and `node` seed are in [ISR routes](/route-rules#isr-routes).

| Preset        | What `isr` does                                                                                             | Where the copy lives                                                              | A prerendered `isr` path                                                                                              |
| ------------- | ----------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `bun`, `node` | the server's own page cache, `swr` with the rule's lifetime                                                 | the `cache:pages` mount, else `cache`; memory by default, so one copy per process | written to `.output/server/isr/` and taken as the stored page, as old as the build, on the first request of each host |
| `vercel`      | one Vercel ISR function per pattern, with its `prerender-config.json` and bypass token                      | Vercel's cache; the function keeps none                                           | the function's `fallback` for a pattern without wildcards, until the first render                                     |
| `netlify`     | `Netlify-CDN-Cache-Control` with `durable`                                                                  | Netlify's durable cache; the function keeps none                                  | not written to `dist/`; the function renders it once and the durable cache keeps it                                   |
| `cloudflare`  | the Worker's `swr` cache                                                                                    | the cache mount you configure; memory by default                                  | rendered by the Worker                                                                                                |
| `static`      | none: the path is a file, and the build warns `isr needs a server preset; /news is served as a static file` | the file                                                                          | the file                                                                                                              |

`isr` with `allowCookies`, or with `varies` naming `cookie`, is a build error on `vercel` and `netlify`, whose CDN keeps the page and ignores `Vary`. A draft request never reads or writes an `isr` copy.

### Revalidation by preset

What `revalidateTag`, `revalidatePath` and the endpoint reach depends on where the copy lives.

| Preset        | `revalidateTag`, `revalidatePath` reach                                                                                                                                       | CDN                                                                                                         | The endpoint |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------ |
| `bun`, `node` | every entry on the mounts, through the tag index; shared with other processes when `cache` is a shared driver                                                                 | no tag header; put a CDN in front and it follows `s-maxage`                                                 | yes          |
| `vercel`      | the function's own caches. For Vercel's ISR copy only a concrete path, through a `HEAD` request with `x-prerender-revalidate`; a tag, `"page"` and `"layout"` do not reach it | `cdnPurge.vercel` purges the tags of cached answers that are not ISR; an `isr` answer carries no tag header | yes          |
| `netlify`     | the function's own caches, and the durable copy through `cdnPurge.netlify` (or the function's `SITE_ID` and `NETLIFY_PURGE_API_TOKEN`)                                        | the answer carries `Netlify-Cache-Tag`, the `isr` answer too, with the implicit tags and every `cacheTag`   | yes          |
| `cloudflare`  | the entries on the mounts you configure; the default memory is one copy per instance                                                                                          | no tag header; `cdnPurge.cloudflare` reaches only what the zone's cache holds under those tags              | yes          |
| `static`      | nothing at run time: there is no server                                                                                                                                       | none                                                                                                        | no           |

On `vercel`, `netlify` and `cloudflare` mount a shared driver as `cache`, or each instance keeps its own entries and its own tag counters and a revalidation reaches only the instance that ran it. See [Running several instances](#running-several-instances) and the driver table in [Storage](/api-reference/storage-details#drivers).

The token, the bypass setup and Deployment Protection for Vercel are in [ISR on Vercel](/deploy/presets/vercel#isr-on-vercel). CDN tag headers, their limits (Vercel 128 tags, Netlify 500) and the purge credentials are in [CDN tags and purge](/api-reference/storage-details#cdn-tags-and-purge). A purge that fails is logged and never fails the revalidation.

## Draft and preview mode

An editor who enables draft mode with `useDraftMode(event).enable()` gets every cache skipped for that browser, an answer of `private, no-store`, and a prerendered page rendered on demand on `bun` and `node`. Hamur adds no route that turns it on; your route checks its own secret. On `netlify`, `cloudflare` and a prerendered page on `vercel` without `isr`, the platform serves the file before your function, so draft mode reaches only pages that are not prerendered. In the browser `usePreviewMode()` makes `useAsyncData` and `useFetch` fetch again. The full route, the cookie and the Vercel bypass cookie are in [Draft and preview mode](/api-reference/server#usedraftmode-draftmode-draftmodeoptions).

## ETags and 304

An answer a cache stores gets a weak `etag` and a `last-modified`, and a matching `If-None-Match` or `If-Modified-Since` gets `304` with no body (`x-hamur-cache: REVALIDATED`). An answer that carries its own `etag` or `last-modified` gets the `304` too, cached or not. `server.etag` adds a validator to small string, bytes or JSON answers, and `handleCacheHeaders` sets one from what your handler knows before it works. There is no option to answer only the headers: the `304` is the whole mechanism. See [ETags and 304](/api-reference/storage-details#etags-and-304) and [Your own validators](/api-reference/storage-details#your-own-validators).

`x-hamur-cache` shows what a cache did, with `HIT`, `STALE`, `MISS`, `REVALIDATED` or `BYPASS`. It is on in `hamur dev` and off in a build unless `server.cache.statusHeader` says otherwise ([Cache status](/api-reference/storage-details#cache-status)).

## Keys

A key holds the build id, the host, the path and the whole query, and the values of the headers in `varies`. No cookie reaches a cached render unless `varies` names it. `allowQuery: ["page"]` keys on those query names only, and `allowCookies: ["theme"]` lets those cookies reach the render and the key, with `Vary: Cookie`. Both are options of a rule's `cache` and of a `GET` handler's `cache` ([Query and cookie allowlists](/api-reference/storage-details#query-and-cookie-allowlists)).

## Within one request

Reads asked twice in a request run once: `GET` calls of a handler, `GET` and `HEAD` calls of the request-bound fetch and `memo(fn)`. Nothing is shared between requests ([Request memoization](/api-reference/storage-details#request-memoization)). To keep an upstream answer across requests, give a `$fetch` call `serverCache` ([Fetch cache](/api-reference/storage-details#fetch-cache)).

## Compression and early hints

The `bun` and `node` servers compress dynamic answers (`server.compress`), after the cache, which is why the cache's `etag` is weak; a strong `ETag` of a compressed answer gets `-<coding>` ([Compression](/deploy/presets/node#compression)). `server.earlyHints: true` sends the page's stylesheets and module chunks as a `103` and a `Link` header, and adds nothing to an answer that comes from a cache ([Early hints](/deploy/presets/node#early-hints)).

## Incremental prerender and `hamur warm`

With `prerender.cache: true` a build reuses a page it wrote before while the page's `cacheKey` and the server bundle are unchanged, so a content site does not render every page on each deploy ([Incremental prerender](/route-rules#incremental-prerender)).

After a deploy the caches of a server preset are empty. `hamur warm` requests the paths that `.output/hamur.json` lists under `prerendered`, `isr` and `cached`, or the lines of a file:

````sh [caching/warm.sh]
hamur build
hamur warm https://example.com --concurrency 4
hamur warm https://example.com --routes warm-routes.txt
````

It sends `GET` with `accept: text/html` and prints one line per path. It exits 1 when an answer is 5xx or a request fails or passes 30 seconds ([CLI](/cli#hamur-warm)). A request fills the cache of the instance that answers it, so with several instances it warms the shared `cache` only if they share one. The header `x-hamur-warm: 1` marks the request in your logs; Hamur does not act on it.

## Running several instances

Several processes or functions can serve one app. What they share is what the storage mount shares.

**Share the mount.** The default `cache` mount is memory, one per process. Put a driver every instance reaches under `cache`, or under the mounts of the kinds you want shared ([Where entries live](/api-reference/storage-details#where-entries-live)):

````ts [caching/shared-cache-config.ts]
import { defineConfig, env } from "hamur"
import { redis } from "hamur/storage"

export default defineConfig({
  framework: "react",
  preset: "node",
  storage: {
    cache: redis({ url: env("REDIS_URL") }),
  },
  routeRules: {
    "/blog/**": { isr: 600, cache: { tags: ["posts"] } },
  },
})
````

Everything Hamur keeps then lives there: the entries of pages, handlers and functions, the tag counters, and the marker of a seeded `isr` page. Entries are keyed by the build id (pages) and a hash of the function's source (functions), so instances of different builds do not read one another's entries during a rolling deploy. With `base` as a list, the first mount can stay per instance, a small memory tier in front of the shared one ([Tiers and versions](/api-reference/storage-details#tiers-and-versions)).

**What stays per instance.**

- The call in flight. Callers that miss on one key share one fill inside a process. Two instances that miss at once each run the function. Run `hamur warm` after a deploy, or keep a longer `maxAge`, where that is costly.
- The pause after a failed refresh (10 seconds per key), the request memoization, and a memory first tier.
- The record of a revalidation made in this process, which keeps a fill that started before it from storing.

**How a tag reaches every instance.** `revalidateTag` writes two counters per tag, `tags:<sha256 of the tag>` and `tags:<sha256 of the tag>:stale`, to the `cache:tags` mount, else `cache`, never to a tier in `base`. An entry stores the counters it was written under. Each read compares them, one read of the counters for an entry with tags, and an entry whose counter differs is a miss or stale. Nothing is broadcast: once `revalidateTag` resolves, the next read on any instance that shares the tag index sees it. A counter the store lost reads as a miss, never as a wrong hit. Counters move atomically on `memory`, `sqlite`, `redis`, `db` and `planetscale`; on another driver `increment` runs under a lock of one process and logs `increment on <driver> is not atomic across instances`, so two instances that revalidate the same tag at the same moment can write one increment.

A revalidation on another instance while a fill is running is caught only for the tags the fill knew before it started. A tag the fill added while it ran (with `cacheTag`, or from a nested cache) that moves on another instance in that window is not caught, and the entry is stored once with the older value. Revalidate again, or keep the lifetime short.

**Drain.** The `bun` and `node` servers stop accepting connections on `SIGTERM` or `SIGINT`, give requests in flight up to 10 seconds, run the `close` hook and dispose every storage driver, so a Redis connection is closed. Entries and counters are already in the shared store, so a stopping instance loses only the fills it was running; a background refresh it had started is not waited for, and the stale entry is refreshed by the next request on any instance ([Deploy](/deploy/presets/bun#shutdown)).

````ts [caching/instances.ts]
import { defineCachedFunction, revalidateTag } from "hamur/server"

export function createInstance(load: (slug: string) => Promise<string>) {
  const getTitle = defineCachedFunction(async (slug: string) => load(slug), {
    maxAge: 300,
    getKey: (slug) => slug,
    tags: ["posts"],
  })
  return { getTitle, publish: () => revalidateTag("posts") }
}
````

The sample builds two instances of one cached function on one mount. `apps/web/samples.test.ts` runs it: the second instance reads the entry the first one wrote, both run the function when they miss together, and a `revalidateTag` on one makes the other miss.
