Last updated:
Lunora supports Cloudflare Workers Cache for HTTP routes. RPC queries and mutations are POST /_lunora/rpc by design and not cacheable at the edge, so caching is exposed on the surfaces that have a cacheable URL: httpRoute HTTP endpoints, httpAction handlers, and a query published over REST with .expose({ rest: true, cache }).
The httpRoute methods below are the lower-level escape hatch: they send the
value you pass, with one exception. When the request carries a credential, a
Cache-Control that is not already private or no-store is sent as private
(see Credentialed requests). The REST cache policy is
the fully guarded surface: it re-derives public vs private the same way, also
never stores a credentialed exchange in the shared cache, and folds the varying
headers into the cache key rather than trusting Vary. Prefer it when the
endpoint is a procedure.
Enabling Workers Cache
Add the cache block to wrangler.jsonc:
{
"name": "my-app",
"cache": { "enabled": true },
// ...
}When cache.enabled is true, the dev server (lunora dev or the Vite plugin) and the CLI (lunora prepare / lunora deploy) automatically bump compatibility_date to at least 2026-05-01 if it is lower. You do not need to know or set the date manually. Lunora reconciles it for you and preserves the comments and formatting in wrangler.jsonc.
You can also enable cache for one named export, with exports[name].cache.enabled:
{
"exports": {
"default": {
"cache": { "enabled": true },
},
},
}Declarative cache headers on httpRoute
The httpRoute builder carries three chainable methods for cache headers. They attach automatically to the JSON response. Streaming routes (a .stream() handler) send only the SSE headers.
| Method | Header | Purpose |
|---|---|---|
.cacheControl(value) | Cache-Control | TTL, public/private, stale-while-revalidate, etc. |
.cacheTag(value) | Cache-Tag | Logical tag for bulk purging via ctx.cache.purge. |
.vary(value) | Vary | Store separate cached variants per request header. |
import { httpRoute, LunoraError, v } from "lunorash/server";
import { api } from "@/lunora/_generated/api";
export const getProduct = httpRoute
.get("/api/products/:id")
.params({ id: v.string() })
.cacheControl("public, max-age=300, stale-while-revalidate=3600")
.cacheTag("products")
.vary("Accept-Encoding")
.handler(async ({ ctx, params }) => {
const product = await ctx.runQuery(api.products.get, params);
if (product === null) {
// A route handler returns a JSON payload, not a `Response`: throw to send a 404.
throw new LunoraError("NOT_FOUND", "Product not found");
}
return product;
});The headers are sent on 200 OK and 204 No Content responses. Error responses (a thrown LunoraError, a validation failure) and streaming SSE responses do not carry them.
Credentialed requests
The handler runs under the caller's ctx.auth, so a response to a request with
credentials is treated as belonging to that caller. Cloudflare keys its cache on
the URL and ignores Vary for anything but Accept-Encoding, so a public
response built for one signed-in user could be served to the next visitor.
When the request carries Authorization, Cookie, Cf-Access-Jwt-Assertion, an
x402 payment header (Payment-Signature, X-Payment), or a Cloudflare Access
identity, Lunora rewrites the declared Cache-Control before sending it:
- A value that already contains a bare
privateorno-storeis sent unchanged. - Otherwise
public,s-maxageandproxy-revalidateare removed andprivateis added.public, max-age=300, stale-while-revalidate=3600becomesprivate, max-age=300, stale-while-revalidate=3600. A baremax-age=300becomesprivate, max-age=300, because a shared cache would store it too. - A field-qualified
private="set-cookie"does not count as private: it marks only the named headers, and a shared cache may store the rest of the response. It is replaced by a bareprivate.
Only those credentials are recognised. If your app authenticates on another
header, such as X-Api-Key, declare it, or those callers are treated as anonymous
and get the declared value, public included:
httpRoute
.get("/api/me")
.cacheControl("public, max-age=60", { credentialHeaders: ["x-api-key"] })
.handler(handler);This is the same list a REST endpoint declares with
cache.credentialHeaders. A credential that is
not a header at all, such as a signed query parameter, cannot be detected: do not
mark such a route public.
Anonymous requests get the declared value unchanged. In development the first rewrite on each route logs a warning. A browser sends every cookie for your domain, so a public route served to browsers that hold any cookie is cached only privately for them. Serve shared, cacheable data from a cookie-free hostname or path if it needs edge hits for those visitors.
Programmatic cache purging
ctx.cache is built by the Worker, so it reaches HTTP action handlers only — the ones mounted on httpRouter(). Purge by tag, or purge everything:
import { httpAction, httpRouter } from "lunorash/server";
const app = httpRouter();
app.post(
"/admin/refresh-products",
httpAction(async (ctx) => {
if (!ctx.cache) {
return new Response("Workers Cache is not enabled in wrangler.jsonc", { status: 501 });
}
await ctx.cache.purge({ tags: ["products"] });
return Response.json({ ok: true });
}),
);
export default app;ctx.cache.purge accepts:
tags?: string[]purges every cached response whoseCache-Tagmatches any listed tag.purgeEverything?: booleanwipes the entire cache for this worker.
Why only HTTP actions?
Queries, mutations, and RPC actions all run inside the Durable Object, where the Cloudflare cache binding does not exist — ctx.cache is undefined for every one of them, which is why the example above branches on it. Only an HTTP action's context is built in the Worker itself, alongside the fetch handler, so only it can reach ExecutionContext.cache.
So a mutation cannot purge, and there is no ctx hop that gets it one: MutationCtx has no runAction, and an action reached through ctx.runMutation/ctx.runAction runs on the caller's DO context, without a cache. Drive the write from an HTTP route instead — call the mutation with ctx.runMutation, then purge in the same handler once it returns.
Memoizing an expensive action result
Everything above caches an HTTP response. RPC is POST /_lunora/rpc, so it
is not edge-cacheable, and an action result therefore has no cache in front of
it. Two different problems hide under "cache my action", and only one of them
needs code.
If the action is fetching from an upstream API, cache the fetch
Anything you read over HTTP that changes on a slow clock (model metadata, pricing
tables, currency rates) should be cached at the fetch, not at the action.
Cloudflare does this for you:
const response = await fetch("https://api.example.com/models", {
// Cache the upstream response at the edge for an hour, keyed on the URL.
cf: { cacheEverything: true, cacheTtl: 3600 },
});That needs no Lunora code, no table and no TTL bookkeeping, and every colocation shares one cached copy. Reach for the recipe below only when there is no URL to key on.
Otherwise, use defineActionCache
For a genuinely computed result (an embedding, a derived summary), the framework
already ships the memo: defineActionCache is a schema-extension component that
adds one table and derives the key for you, so there is no hand-rolled hash and
no bespoke read/write pair.
import { defineActionCache } from "@lunora/server";
export const cache = defineActionCache({ ttlMs: 60 * 60 * 1000 });// lunora/schema.ts — merges in as `actionCache_entries`
export const schema = defineSchema({ ... }).extend(cache.extension);
// Re-export so codegen registers it; schedule it from a cron for bulk cleanup.
export const { purgeExpired } = cache.functions;import { action, v } from "@/lunora/_generated/server";
import { cache } from "./cache";
export const embed = action
.input({ text: v.string() })
.action(async ({ args, ctx }) => cache.wrap(ctx, "embed", args, async () => callEmbeddingModel(args.text)));wrap(ctx, name, args, compute) returns the stored value on a hit and runs
compute on a miss. The key is a SHA-256 over name plus the args encoded
through the wire codec with sorted keys, so { a, b } and { b, a } are one
entry and bigint / Date / bytes arguments key distinctly.
invalidate(ctx, name, args) drops one entry; invalidateAll(ctx, name) drops
every entry under a name and returns { complete, deleted } — call it again
while complete is false. Expiry is lazy (a read past the TTL is a miss and
the row is overwritten by that same call), each miss reaps a few expired rows,
and purgeExpired reclaims entries whose names went quiet. A result over
maxValueBytes (512 KB default) is returned but not stored.
See @lunora/server for the full surface.
No single-flight. Two callers that miss at the same instant both run compute; the unique index on the key means one result is stored rather than two
rows appearing, but the work was done twice. Preventing that needs a lock held across an arbitrarily long external call, whose own failure mode — a crashed
holder wedging the key — is worse than a cold start being paid twice. If you genuinely need the stampede guard, take the lease yourself in a mutation: a
mutation runs to completion inside one Durable Object without interleaving, so exactly one caller can observe "no live lease" and take it, and the compute
stays in the action.
wrap reads and writes through the app's own ctx.db, so on an .rls("required") schema the merged actionCache_entries table needs a policy like any
other. Declare one that denies client access outright — entries are keyed by a digest and carry no ownership column, so there is nothing for a row policy to
scope to.
Scaffolding cache-aware routes
Use the built-in generator to scaffold a route with cache examples commented in:
vis generate lunora-http-route --name=listProductsThis produces:
import { httpRoute, v } from "lunorash/server";
export const listProducts = httpRoute
.get("/api/listProducts")
.searchParams({
// q: v.optional(v.string()),
})
// .cacheControl("public, max-age=300, stale-while-revalidate=3600")
// .cacheTag("listProducts")
// .vary("Accept-Encoding")
.handler(async ({ ctx, searchParams }) => {
return { ok: true, searchParams };
});Uncomment the cache lines and adjust the values for your use case.
Best practices
- Tag by entity, not by endpoint. Use
cacheTag("products")on every route that returns product data, then purge"products"once when anything changes. Don't create one tag per route. - Use
stale-while-revalidatefor reads.public, max-age=300, stale-while-revalidate=3600means Cloudflare serves from cache for 5 minutes, then revalidates in the background for up to an hour. Your backend sees reduced load. - Vary on content negotiation. If your endpoint returns different formats based on
Acceptor compresses differently perAccept-Encoding, add.vary("Accept-Encoding")so Cloudflare stores separate variants. - Invalidate eagerly, cache generously. Cache reads for a long TTL, then purge immediately when a mutation changes the underlying data. A short TTL is a band-aid for missing invalidation.
- Keep cache headers deterministic.
.cacheControl()and.cacheTag()accept plain strings. Apart from the credential rewrite above there's no parsing or validation, so a typo in the header value is sent verbatim. Test your headers withcurl -Ior the Cloudflare dashboard.