Caching
How reads know which tables they touched, and how writes invalidate exactly those reads.
better-supabase never patches cached rows. Every read records the tables it touched, every write reports the tables it changed, and caches refetch the reads that overlap. It's simpler than normalized caching and stays correct with RLS, includes, relation filters and cascading deletes, because the database does the work again instead of the client guessing.
Reads: touched tables
A read touches its table, every table it includes (nested includes too,
and _count includes), and every table named in a relation filter:
db.customers.list({
where: { notes: { some: { kind: "call" } } },
include: { organization: true, _count: { locations: true } },
});
// touches customers, notes, organizations, locationsbetterSupabase.tablesOf(spec) returns that list for a query spec, and
touchedTables(op) returns it for a built operation.
Writes: invalidation targets
A mutation invalidates its own table. A delete also invalidates tables whose
rows change because of it: foreign keys with on delete cascade, set null
or set default, followed through further cascades. gen records those
actions from the database, so there's nothing to configure.
invalidationTargets(betterSupabase.meta, "customers");
// ['customers', 'contacts', 'locations', 'notes', 'customerTags', ...]Database functions don't say what they change. Declare it once:
export const betterSupabase = createSupabase(schema).defineRpc(
"archive_customer",
{ invalidates: ["customers", "notes"] },
);db.$rpc('archive_customer', ...) then invalidates those tables like any
mutation.
Cache adapters
betterSupabase.cache(adapter) subscribes a CacheAdapter
to every mutation and declared RPC. Each call gets a CacheTarget with the
table, the changed row ids, and tables, the full list to invalidate.
| Adapter | What it invalidates |
|---|---|
queryCache(queryClient) from better-supabase/query | TanStack queries whose meta.bsTables overlaps tables |
nextCache() from better-supabase/next | tagFor(table) for each table and tagFor(table, id) per row: updateTag in Server Actions, revalidateTag(tag, { expire: 0 }) elsewhere, and a no-op outside a Next.js request |
Your own adapter implements one method, and testCacheAdapter from
better-supabase/testing checks it against the same cases.
Writes that don't go through db expire the same tags through a Postgres
trigger and a signed route. See
Cache invalidation outside the process.
Cache public data without the service role
A 'use cache' function can't read cookies or headers, so it has no user. For
data every visitor may read, such as a plan list or published articles,
bsb.public() returns a context that reads as the anon role. Row Level
Security still applies, so the read returns what an anonymous visitor may see
and nothing more. It never reads the request and never uses the service role.
async function plans() {
"use cache";
const { db } = await bsb.public({ tables: ["plans"] });
return db.plans.list().orThrow();
}It takes the same tables, id, tenant and life options as
bsb.cached() and tags the entry the same way. Doctor rule
BS640 reports a plain 'use cache' function that
reads the request instead.
TanStack Query
Query options from createQueries carry meta: { bsTables }. Invalidation
is a predicate over that meta, so a write to notes refetches a
customers.list that included notes, and nothing else. Keys stay
['bsb', table, method, ...args] for devtools and manual invalidation. See
TanStack Query.
Next.js
In a cached server component, tag the data with what it touched:
"use cache";
const spec = betterSupabase.spec.customers.list({ include: { notes: true } });
bsb.tags(spec); // tags customers and notes
const customers = await db.$run(spec).orThrow();Server actions and route handlers that write through db revalidate those
tags automatically (cacheTags: false turns it off).
bsb.tags also takes an array of specs or a
read set, and tags the union of the tables
they read.
Keep reads across requests and deploys
bsb.kept(fn, options) keeps a read in a store that outlives one render and
one deploy. The function runs with the caller's own context, under RLS: no
admin client is reachable from it, and each user (with their tenant and
authorization version) gets their own entry. A write through db to one of
tables expires the entry on every instance.
export const openInvoices = bsb.kept(
(ctx, customerId: string) =>
ctx.db.invoices.list({ where: { customerId, status: "open" } }),
{ name: "open-invoices", tables: ["invoices"], life: { revalidate: 60 } },
);
const invoices = await openInvoices(customerId);| Option | Default | What it does |
|---|---|---|
name | required | Part of the key and the name in reports. |
tables, readSet | none | A write to one of these tables expires the entry. |
tags | none | More tags, or a function of the arguments that returns them. |
life.revalidate | 300 | Seconds the entry is fresh. After that a call serves it once more and refreshes it in the background. |
life.expire | 86400 | Seconds the store keeps the entry. |
version | a hash of the generated schema | Part of the key. Change it when the result changes shape; a migration changes the default. The build id is never part of the key. |
tenant | the request's | The active tenant from the arguments. |
share | "user" | "tenant" keeps one entry for every caller with the same grant in the tenant, "public" one for every visitor; see below. |
The value goes through JSON, so a Date comes back as a string on a miss and
on a hit alike. A support session and a token that fails to verify read
through without the store, and so does a failed Result.
Pick the store in createNext:
import { vercelRuntimeCacheAdapter } from "better-supabase/server";
import { getCache } from "@vercel/functions";
export const bsb = createNext(betterSupabase, {
kept: { store: vercelRuntimeCacheAdapter(getCache) },
});| Store | From | Shared between instances |
|---|---|---|
memoryKeptStore() | better-supabase/server, the default | No |
vercelRuntimeCacheAdapter(getCache) | better-supabase/server | Yes, per region |
postgresKeptStore({ client }) | better-supabase/cache-postgres | Yes, in the cache tables |
Concurrent misses for one key run one fill per instance; the other calls
wait for it. Across instances a store with a lease coordinates them: one
instance fills and the others wait up to kept.wait milliseconds (250 by
default) for its entry, then fill themselves. A stale entry is refreshed by
the instance that takes the lease, while every instance serves the stale
value. postgresKeptStore takes the lease in one statement, so exactly one
instance wins. The Runtime Cache has no set-if-absent, so its lease is a lock
entry that two instances reading at the same moment can both take: it narrows
a stampede and does not prevent one. To keep the entries in the Runtime Cache
and still fill once, take the lease in Postgres:
import { postgresKeptLease } from "better-supabase/cache-postgres";
export const bsb = createNext(betterSupabase, {
kept: {
store: vercelRuntimeCacheAdapter(getCache, {
lease: postgresKeptLease({ client: cacheClient }),
}),
},
});It needs the leases table and function of
postgresCacheSql() and costs one statement
per miss. In tests/bench/kept-lease.ts (pnpm bench:lease), four instances
miss one key with 20 calls, a 50 ms fill and a Runtime Cache stand-in at 5 ms a
call whose writes reach the other instances 25 ms later:
| Lease | Miss p50 | Miss p95 | Fills |
|---|---|---|---|
| none | 64.1 ms | 65.3 ms | 4 |
| Runtime Cache lock | 82.8 ms | 84.0 ms | 4 |
postgresKeptLease | 103.0 ms | 106.5 ms | 1 |
The waiting instances pay for the write to reach their replica; the database sees one fill instead of four. With consistent reads (propagation 0) the lock entry also fills once, at 87.2 ms p50 against 70.9 ms for the Postgres lease.
An entry over 2 MB, with more than 128 tags or a tag over 256 bytes is not
stored: the call still returns the value and kept.onSkip gets the reason. A
store that fails never fails the call; it reads through and logs a warning.
Inside "use cache: private" the entry's tags and life also apply to the
enclosing entry, so a write expires both. In a scope that can't read the
request, pass the handle from bsb.sessionHandle():
openInvoices.as(session)(customerId).
Keep the reads of a cached function
Pass keep to bsb.cached() and every read of ctx.db in that function goes
through the kept store, so a cold page or a fresh instance answers it without
calling the database:
export async function getCustomer(id: string) {
"use cache: private";
const { db } = await bsb.cached({
tables: ["customers", "notes"],
id,
keep: { name: "customer" },
});
return db.customers.get({ id }, { optional: true }).orThrow();
}Each read gets its own entry, keyed on the user, the tenant, the operation and
the schema version, and tagged with the table it reads, so a write to the table
expires it like any other kept entry. Parallel renders of one page share a
single fill. Writes, db.$many() batches, function sources and $rpc() calls
always reach the database, and so does a read of a support session or of a
token that failed to verify. Request stats count only the reads that miss, and
keptHits counts the rest.
Keep a bootstrap answer
bsb.bootstrap({ rpc, kept: true }) keeps the wrapper's answer (data, reads,
subject and permissions) per user, session and tenant. A write to a table the
wrapper reads expires it. A session that ended is served from the store for at
most kept.life.revalidate seconds (default 30), unless bsb.evictSession()
ran for the user, which expires the entry at once. Leave kept off where a
revoked session must stop on the next request.
Expire kept entries from your own writes
A bsb.action with invalidates and the repository writes expire the kept
entries of the tables they touch. When you expire by hand, call
bsb.expireTags() instead of updateTag or revalidateTag: those expire
Next's cache and leave the kept entry, which a shared store holds for every
instance.
await db.notes.update(id, patch).orThrow();
await bsb.expireTags([`bsb:notes`, `bsb:notes:${id}`]);It calls updateTag in a Server Action and revalidateTag in a Route
Handler, expires the kept store, and resolves once the store has the tags, so
the next read on another instance fills again. Both calls count in the
request's tagCalls and expiredTags. Doctor reports the old calls
(BS648) and a refresh() that expires nothing
(BS649); better-supabase codemod expire-tags lists
each call with its replacement.
Share an entry per tenant
With share: "tenant", callers who hold the same permissions in a tenant read
one entry instead of one each. The entry is still filled through the first
caller's own client, under RLS; nothing reads with the service role. Three
things must agree before an entry is shared:
- the authorization provider lists every table in
tablesunder itstablesfield withshare: "tenant", and the permissions its select policies check (doctor BS428 reports a table whose policies filter by the caller); - the authorization hooks set
shareKey, which names the caller's grant on those permissions.permissionsShareKey()frombetter-supabase/blocks/permissionsreads it from the token's permissions claim and answersnullfor a truncated claim or a stale authorization version; - the function reads only
tables. Inside a shared fill, a read of another table, a function call,ctx.supabase,ctx.storageor adb.$escape hatch answers aforbiddenDbErrorwith codeSHARE_REFUSED, and the value is returned but not stored.
export const customerList = bsb.kept(
(ctx) => ctx.db.customers.list({ select: ["id", "name"] }),
{ name: "customer-list", tables: ["customers"], share: "tenant" },
);A page that loads in one RPC lists the function in functions instead. The
provider declares it in sharedFunctions with the tables it reads, which
join the entry's tables and tags, and inside the fill $rpc passes only the
listed functions. Doctor BS430 checks that the
function is security invoker, language sql and not volatile, reads only
those tables and no caller, and calls only functions it admits: another
listed function, a better_supabase helper that passes on its own, or one of
the provider's
permissionFilters
with a literal key the entry's permissions lists.
better-supabase config functions --shareable 'api.*_payload' runs the check
on candidates before you list them:
export const customerPage = bsb.kept(
(ctx, id: string) =>
ctx.db.$rpc("customer_payload", { id }, { schema: "api" }),
{ name: "customer-page", functions: ["customer_payload"], share: "tenant" },
);When any of the three doesn't hold, the entry falls back to one per user,
kept.onSkip gets the reason "share", and the logger warns once.
bsb.remote() takes the same share: "tenant" with its tables and
functions.
expectTenantShare from better-supabase/testing checks a provider's hooks:
two holders get one key and read the same rows, and a caller without the
grant gets another key.
Keep public data for every visitor
With share: "public", one entry serves every visitor, signed in or not. The
fill runs as the anon role through the anon client, as bsb.public() does:
it never reads the request, never uses the service role, and RLS decides which
rows it returns. The key carries no user and no tenant, and the tags carry
none either, so a write to one of tables expires the one entry. As in a
tenant fill, the function reads only tables and functions; another read
answers SHARE_REFUSED and the value is not stored.
export const plans = bsb.kept((ctx) => ctx.db.plans.list(), {
name: "plans",
tables: ["plans"],
share: "public",
});Use it for data with no tenant, such as plans, currencies or published
articles. A lookup that maps a public slug to an organization id works only
when an anon select policy exposes those rows; without one the fill keeps an
empty result for everyone. Doctor rule BS645 reports
a public entry on a table that anon can't select. For tenant data, use
share: "tenant".
Run your own services in a shared fill
An app that builds its own db, for example over its own Postgres pool in its
request context, passes it through shareGuard(ctx, db) from
better-supabase/server inside the fill. In a share: "tenant" fill the
guarded db reads only the entry's tables and functions, and a refusal keeps
the entry from being stored, as with ctx.db. Outside a shared fill it
returns the db unchanged, so a service can call it on every path.
import { shareGuard } from "better-supabase/server";
export const customerPage = bsb.kept(
async (ctx, organizationId: string) => {
const db = shareGuard(ctx, await appContext().db);
return customerService(db).page(organizationId);
},
{ name: "customer-page", tables: ["customers"], share: "tenant" },
);The db must run as the caller: its request context carries the caller's
sub and role in claims, and its connection sets them for RLS. A db whose
claims name another user, the service role or no one answers SHARE_REFUSED
for every read. inTenantFill(ctx, tables, body) from
better-supabase/testing runs a service the way a shared fill does, so a test
can check it without a Next.js request.
Query specs
A QuerySpec is a read described as plain JSON:
{ v: 1, table, method, args }. betterSupabase.spec.<table>.<method>(...) builds one
with full types, db.$run(spec) runs it, and InferResult<typeof spec> is
its result type. Because it serializes, the same spec can be built on the
server, sent to the client, used as a query key and passed to
useLiveQuery.
const spec = betterSupabase.spec.customers.list({
select: ["id", "name"],
limit: 20,
});
type Rows = InferResult<typeof spec>; // { id: string; name: string }[]
await queryClient.prefetchQuery(q.$spec(spec));Live updates
Live queries reuse the same model: a trigger broadcasts "table changed" (no row data) and the client invalidates the queries that touched that table, which then refetch through RLS.
Last updated on
better-result
Return better-result values from repositories with withBetterResult, or convert single results at the boundary.
Postgres cache for Next.js and Astro
Keep Next.js cacheHandlers entries and Astro route cache responses in Supabase Postgres, so every instance shares them and a tag you expire takes effect everywhere.