Operating Tenant Databases
Scope revocation, the tenant registry, generated operator routes and lifecycle operations, FGA, and deleting the namespace.
Day-two operations for a project with per-organization Durable Object databases: revoking access, the tenant registry, the generated operator routes, fine-grained authorization inside tenant objects, and removing the namespace. Start at Database per Tenant for the model.
Scope revocation
With auth.jwt.revocationCheck: 'kv', changing a scope-conferring row revokes
the carried scope claims that row backed (revoke-on-touch): the subject's
qbrev:scope:<subject>:<kind>:<instance> keys are stamped in the edge's KV
namespace. The tenant Worker has no KV, so for a tenant table the object
records the revocation in its outbox and the edge stamps it:
- In the write's transaction. Every scope-conferring tenant table (the
fromtable of a relationship a scope role is grantedvia) carries SQL triggers that write arevokeoutbox entry on everyDELETEand on everyUPDATEthat changes a column the row confers through (soft deletes included), naming the row's id and subject column and its resource (instance) column. Those columns are the subject and resource columns, each relationship'swhere:columns, every scope role'ssubKeys, every field the table's firewall names (its soft-delete column included), the tenant column and the primary key, so a backfill or data migration of other columns revokes nothing. When the compiler cannot resolve one of them, the trigger fires on everyUPDATE. An update that moves the row to another subject or instance also revokes the new pair. Being SQL triggers, they fire for every write path in the object: CRUD routes, actions,unsafeDb, jobs, trigger handlers, foreign-key cascades and compiler commands. A write that rolls back leaves no revocation.INSERT OR REPLACEdeletes a conflicting row without firing theDELETEtrigger (SQLite'srecursive_triggersstays off, so authored SQL triggers keep their semantics): the build refusesINSERT OR REPLACE/REPLACE INTOon a conferring table in tenant actions and trigger bodies (TENANCY_REVOCATION_REPLACE). Change a conferring row with anUPDATE(oronConflictDoUpdate). - Stamped by the edge, at least once, beside the realtime frames (see
Outbox delivery), at the time the edge applies the entry,
like every edge revocation: a later stamp only revokes more (a token proven
between the write and the stamp re-proves), and no stale read can lower it.
The entry keeps its write time for the receipt. The edge accepts a
revokeentry only for a declaredauthz.scopeskind; one whose instance the platform lookup index places in another organization is logged (tenant.revoke.foreign_instance) and still applied, since a wrong revocation only forces a re-prove. - Restores and purges. A dump restore drops the tables, and a purge erases
the database, without firing a trigger; a point-in-time restore rewinds the
outbox with the data. So a dump restore first queues a revocation for every
conferring row it replaces, in the load's transaction. A point-in-time
restore hands the current conferring rows and any queued revocations to the
control object before scheduling the rewind. Every reconcile
(
POST /tenants/:id/sync, abandon) and every cancel queues them again, and only a reconcile drops them once its requeue committed (an orphaned stash is pruned after a week). A purge queues them once per archive, then drains them in rounds, at most 300 rows per request (each row costs up to two KV writes, and a Worker invocation gets about 1000 KV operations). While any remain it answers409 TENANT_PURGE_DRAININGwithdetails: { remaining, more }andRetry-After: retry the purge until it completes; nothing is queued twice. An edge older than version 12 cannot purge while revocations are queued. Rows that exist again after a restore simply re-prove. - Your own revocations. In tenant code,
revokeScopeTokens(env, subject, kind, instanceId)(an import oflib/jwt-revocationin a tenant feature is re-pointed at the tenant version) records arevokeentry with your write. It takes theenvyour action, job or trigger handler received, neverenv.KV, and throwsTENANT_REVOCATION_UNAVAILABLEwithout the outbox. The other exports oflib/jwt-revocation(revokeUserTokens,revokeMemberTokens,revokeSessionTokens,checkTokenRevocation) are edge-only: in a tenant feature a call fails the build, its parameter type naming the reason. - Admission. A revoked claim stops riding on tokens; admission itself
re-reads the row. Tenant scope admission
requires the proving row's conditions (
where:) and excludes soft-deleted rows through the table's firewall (deleted_at IS NULL).
Registry
tenant_registry in the features D1 inventories tenant names and application
state; Cloudflare's object listing does not include those fields. Beside it,
tenant_operations holds one receipt per lifecycle operation
(Lifecycle operations). The edge
upserts a row from the object's wake report. The object repeats the
report on later responses until the edge acknowledges a successful registry
write, so a transient D1 outage does not lose inventory or migration failures.
Each report carries a generation and a strictly increasing sequence, stored atomically with the report in the object's local KV. The sequence advances on every wake and migration retry, including pre-migration progress markers, even when timestamps are identical. The edge updates an existing row only when its generation matches and the report sequence is higher. Delayed or repeated reports cannot replace newer health, schema versions, or errors. An acknowledgement consumes only the exact current report, including its generation and sequence. Unordered RPC failures preserve rows that already have an ordered health report. PITR installs a fresh report generation together with the outbox fence; reconciliation republishes the recovered object's health under that generation. Dump restore installs the same fresh generation. Failed preparation restores the previous report fence, and explicit abandonment republishes current health under its recovery generation.
| Column | Meaning |
|---|---|
state | active, migrating, failed, frozen, archived, purged. Wake reports never overwrite frozen, archived or purged. |
schema_version | Applied tenant migrations |
report_generation, report_sequence | Report ordering fence (initially initial) and last accepted sequence (initially 0) |
last_pre_migration_bookmark | PITR bookmark taken before the last migration |
last_error | The last migration error, or null |
tenant_id, partition_key | The organization, and the partition key for partition objects (id is the object name) |
last_backup_at, last_backup_key | The last finished backup |
outbox_seq | The last ordered-lane outbox entry (lookup, registry) the edge applied |
jurisdiction | The objects' jurisdiction |
Fan out over every object with forEachTenant from src/lib/tenants.ts;
syncTenants(env) drains every object's outbox with it — an operator or manual
sweep: nothing needs it on a schedule, since every alarm asks the edge to drain
its own object. It skips archived and
purged tenants, runs at most concurrency at a time (default 4), and
reports each tenant's failure instead of throwing:
import { forEachTenant } from "../lib/tenants";
const results = await forEachTenant(env, async (tenantId, stub) => {
return tenantId;
}, { concurrency: 8 });Operator routes
The edge mounts tenant operations at <api>/tenants (e.g. /api/v1/tenants).
They are plain Hono routes: they are not in the OpenAPI document or the MCP
tool list.
tenancy.operator.http decides which of them exist. Generating the
lifecycle helpers never implies exposing them over HTTP:
tenancy: {
isolation: 'durable-object',
// No generated operator routes. Your own `operator:` actions call the
// helpers in src/lib/tenants.ts (archiveTenant, restoreTenant, purgeTenant, …).
operator: { http: false },
}tenancy: {
isolation: 'durable-object',
// Only these routes are mounted; nothing else answers under <api>/tenants.
operator: { http: { allow: ['archive', 'unarchive', 'sync', 'retry-migration'] } },
}Route names are the path segments below: retry-migration, archive,
unarchive, purge, sync, rebuild-lookups, schedules (the GET plus
arm, hold and arm-all), lookups-migrate, outbox-receipts, backup,
backups (the list plus backups/counts), bookmark, restore,
cancel-restore. An unknown name, an empty list, or http set beside the
deprecated operator.purge fails the build (TENANCY_OPERATOR_HTTP). An
allowlist that mounts any mutation (every name but backups, bookmark,
outbox-receipts) needs auth.cloudflareAccess covering <api>/tenants;
without it the build fails (TENANCY_OPERATOR_AUTH): a sysadmin session cookie
is not enough authority for a lifecycle mutation. With
http: false no src/tenant/admin.ts is generated and src/index.ts mounts
nothing at <api>/tenants; src/lib/tenants.ts is unchanged. Leaving http
unset mounts every route and warns: the default becomes false in the next
breaking release.
Every route needs a sysadmin (user.role === 'sysadmin', Better Auth admin
plugin). With auth.cloudflareAccess configured, the caller must also come
through Cloudflare Access, and the build fails (TENANCY_ADMIN_NOT_BEHIND_ACCESS)
unless an Access application covers both the path and the API host (the
hostnames in providers.runtime.config.routes and domain; with none
configured, only an application without hosts covers it).
| Route | Effect |
|---|---|
POST /tenants/:id/retry-migration | Clear the reset count and migrate the object again; records the new report |
GET /tenants/operations/:operationId | The durable receipt of a lifecycle operation, settled from the object's receipt or the registry when it was left requested / uncertain. See Lifecycle operations. |
POST /tenants/:id/provision | The only route that creates a tenant object. Refuses an id that is not a Better Auth organization (404 TENANT_ORGANIZATION_UNKNOWN) and a partition name; wakes the organization's object so it migrates and reports, registers it from that report, returns the registry row. Idempotent: a registered organization is returned as is. Use it to move an existing organization into a tenant object (provision, then archive, backup, restore, sync, unarchive). Partition objects are created by their first request, never here. |
POST /tenants/:id/archive | The object answers 423 TENANT_ARCHIVED; tenant_registry.state → archived (forEachTenant skips it). Data is kept. Refuses a purged object, and refuses an unknown id (TENANT_NOT_PROVISIONED) without waking it: no lifecycle operation but provision creates an object. If archive fails after the object archived (for example the registry write failed), retry it: it re-records the object's own report, which says archived. The other operator routes (unarchive, sync, backup, backups, retry-migration, restore) likewise act on registered objects only. When the edge drains queued work from an object it has not registered, it records the state the object reports, archived included, never active by default. |
POST /tenants/:id/unarchive | Serve again; state → active. Registered objects only: an unknown id is refused (TENANT_NOT_PROVISIONED) without waking it, as is a purged one. Refuses (TENANT_RESTORE_PENDING) while a restore is pending or not yet reconciled by POST /tenants/:id/sync, or while an unconfirmed restore or stranded maintenance fence awaits POST /tenants/:id/cancel-restore — the explicit last step of restore quarantine. |
POST /tenants/:id/purge | Body { "confirm": "<id>" }. archived tenants only: records the current point-in-time bookmark in tenant_registry.last_purge_bookmark, records the durable purge marker in the control object, erases the object (deleteAlarm(), then deleteAll()), marks it purged; the object answers 410 TENANT_PURGED from then on. Resumable: after an error, retry it (interrupted purges). Any other state, or a wrong confirm, answers 409. |
tenancy.operator.purge (deprecated: name 'purge' in operator.http.allow,
or leave it out). When your own code imports purgeTenant from
lib/tenants (an organization-delete flow that archives, cleans up platform
rows and storage, then erases the object; a named import, export * or a
named re-export, or a namespace / dynamic import of lib/tenants in a file that
names purgeTenant; type-only imports and comments do not count),
the raw purge route is not mounted: an operator could otherwise erase an object behind your flow's back.
It does not exist at all then (404), and purgeTenant stays available to your
code. Set tenancy.operator: { purge: true } to mount it anyway, or
{ purge: false } to leave it out when nothing imports purgeTenant. An
operator.http.allow list that names 'purge' mounts it regardless of what
your code imports: the list is the explicit opt-in.
Purge is not immediate erasure: Durable Object point-in-time recovery keeps
the data for 30 days after deleteAll(). Purge is still final as far as these
routes go. No route brings a purged tenant back: restore and unarchive refuse it,
and the marker is never cleared. tenant_registry.last_purge_bookmark records
the bookmark from just before the purge. Getting the data back means restoring
that bookmark and clearing the control object's marker in your own code; no
generated route does either.
The same operations are functions in src/lib/tenants.ts: provisionTenantTarget,
retryTenantMigration, archiveTenant, unarchiveTenant, purgeTenant.
Lifecycle operations
Every mutation above runs through one executor, runTenantOperatorOperation
in src/lib/tenants.ts, against one registry, TENANT_OPERATIONS. The
registry is the state machine: which tenant_registry.state an operation may
start from, what it leaves, and whether the caller must confirm.
| Operation | From | To | Confirm |
|---|---|---|---|
provision | no row | the object's own report (active, migrating, failed) | |
archive | active, migrating, failed, frozen | archived | |
unarchive | archived | active | |
purge | archived | purged | { confirm: "<id>" } |
restore | archived | archived (pending) | |
cancel-restore | archived | archived | { confirm: "<id>" } |
retry-migration, sync, rebuild-lookups, backup, schedules.arm, schedules.hold | any registered state but purged | unchanged | |
schedules.arm-all, lookups.migrate | not bound to one tenant | ||
backups, bookmark, outbox-receipts, schedules.status | reads: registered, not purged |
The executor runs, in order: the registry read and the transition check
(409 TENANT_INVALID_TRANSITION, 404 TENANT_NOT_PROVISIONED), the
confirmation (409 TENANT_CONFIRM_REQUIRED), the begin audit row (a failed
write is 503 TENANT_AUDIT_UNAVAILABLE and nothing runs), the operation,
then the outcome row. All of that happens before the tenant object is woken, so
an invalid transition never creates or touches an object. Reads skip the audit.
Every mutation has an operation id and a durable receipt. Send yours as
X-Quickback-Operation-Id (8–128 characters of [A-Za-z0-9_-], else
400 TENANT_OPERATION_ID_INVALID) or let the route mint one; the response
carries it as operationId. The receipt is a tenant_operations row in the
features D1, written requested before the object is touched and settled
completed or failed after, with the operation's parameters hash, actor,
actorAuthMethod, fromState, resultingState, error code and the recorded
response (≤ 4000 characters). Every audit row of the operation carries the same
operationId in metadata, with phase: requested | completed | failed | uncertain. If the outcome cannot be recorded after the operation ran, the
receipt says uncertain, never a false completed.
Repeating an id with the same parameters replays the recorded outcome
without running again (replayed: true in the response; a recorded failure is
thrown again). The same id with different parameters is 409 TENANT_OPERATION_ID_CONFLICT; an id whose receipt is still requested or
uncertain is 409 TENANT_OPERATION_PENDING until it is reconciled.
GET /tenants/operations/:operationId (also reconcileTenantOperation(env, id) in src/lib/tenants.ts) returns the receipt and settles a requested or
uncertain one from durable evidence: the object's own last-operation receipt
(archive and unarchive record the operation id atomically with their change),
else the registry state the operation leaves (resultingState; an open
restore_session for a restore). A settled receipt records reconciledBy and
gains its missing completed audit row with reconciled: true. Without
evidence the receipt is returned unchanged (evidence: 'none') for a human to
decide.
Your own operator: action uses the same executor, so an authored control
plane and the generated routes cannot drift:
import { archiveTenant, runTenantOperatorOperation } from "../../../lib/tenants";
export default defineAction({
path: "/ops/archive-org",
method: "POST",
input: z.object({ organizationId: z.string(), operationId: z.string().optional() }),
access: { userRole: ["sysadmin"], authMethod: ["cloudflare-access"] },
operator: { target: { table: "organizations", by: "input.organizationId" } },
async execute({ env, ctx, input }) {
return runTenantOperatorOperation({
env, ctx,
tenantId: input.organizationId,
operation: "archive",
operationId: input.operationId,
execute: ({ operationId }) => archiveTenant(env, input.organizationId, { operationId }),
});
},
});With tenancy.operator.http: false this is the only way lifecycle mutations
happen, and it carries the same transition check, confirmation, audit rows and
operation id as the generated routes would.
Target resolvers. Three functions in src/lib/tenants.ts separate naming a
tenant from creating one, so no ordinary operation can wake an object for an
identifier nobody owns:
| Function | Admits | Never |
|---|---|---|
resolveTenantTarget(env, id) | A registered, unpurged object (404 TENANT_NOT_PROVISIONED, 410 TENANT_PURGED otherwise) | Creates state or wakes the object |
provisionTenantTarget(env, organizationId) | An organization that exists in Better Auth (404 TENANT_ORGANIZATION_UNKNOWN); wakes and registers it; idempotent | A partition name; an id Better Auth does not know |
resolveRecoveryTarget(env, id) | A registered row including purged (with lastPurgeBookmark), for your own exceptional recovery action | An unknown id |
A partition name <orgId>:<key> is trusted through the registry's own
ownership columns, not by parsing the name: a row registered to another
organization is 409 TENANT_TARGET_MISMATCH. runTenantOperatorOperation
applies the same check to every operation.
FGA
With authz.fga, fga_tuples is a table of every organization's
object. It is not in the platform D1.
ctx.fga(check,listObjects,expand,read,write, andsharewith link sharing) exists in the actions of tenant features, for every principal the edge admitted to the object: a member whose active organization it is, a caller a namespace lane proved with no organization seat, a share-link principal. The object is the organization. A delete is visible to the next check.- The edge hydrates no
ctx.fga. It forwards/fga/v1/*to the caller's organization object, like a tenant route (no organization:400 TENANT_REQUIRED). - Tuples never cross organizations. Two organizations can hold tuples for the same object id, and each sees only its own.
access: { fga }arms are allowed on tenant tables: their reads, views, writes and record actions run in the object, where the gate finds the tuples. A platform table, a partitioned feature, a room binding andrealtime.wsTicketstill cannot carry one.
Share links
Link subjects work tenant-local: a link's
row in fga_share_links and its tuple live in the organization object, next
to the object they protect, and the lifecycle triggers (object delete or
move, parent delete, fresh insert) run there, in the tenant migration set.
The edge keeps the share router (/share/v1/open, exchange, link) and the
x-share-token / qb_share middleware, and resolves a credential in two
steps:
- The token's stored hash is looked up in the compiler-owned hashed lookup
__fgaShareLink(tenancy.lookupssemantics: the platform D1 holdsHMAC(TENANT_LOOKUP_KEY, "__fgaShareLink\0<hash>"), a hash of a hash;TENANT_LOOKUP_KEYbecomes a required secret). The lookup converges after the minting object's next response, like every lookup. - One command,
qb.shareLinkResolve, runs in that object: the row by hash or id, live, its tuple still present, ascope:<kind>:<role>creator re-proven against the relationship row (one row, this organization), and thefieldsprojection of the object. Theorgcreator edge (Better Auth membership) is proven on the edge. A cookie carries the organization id, so a cookie request routes with no lookup.
The link principal is forwarded like any other; the tenant Worker applies it
only on a route whose access has an fga arm for the link's object type and
runs every other route as the caller it replaced. Inside the object the token
is stored as SHA-256(token): the object holds no secret, and a 256-bit
random token needs no key. Signed user:* share tokens do not exist in this
mode (POST /fga/v1/share on a user:* relation is 400, a GET /share/v1/<token> with one is 404); user:* tuples remain writable with
ctx.fga. The link resource tables must be tenant tables.
These shapes are refused, because each would read or write tuples from somewhere other than the organization object:
| Code | Cause |
|---|---|
TENANCY_FGA_SHARING | authz.fga.sharing is set but the model declares no link subjects. Signed user:* tokens are verified on the edge against tuples it does not hold. Declare type link and list it on the shared relations. |
TENANCY_FGA_MEMBERSHIP | authz.fga.membership is set. Those tuples are written from Better Auth hooks on the edge. Write the tuples from a tenant action instead. |
TENANCY_FGA_ACCESS_ARM | A platform table, a partitioned feature's table, a standalone action, a room binding or realtime.wsTicket declares an access: { fga } arm. Only a tenant table's reads, views, writes and record actions are gated in the organization object. Call ctx.fga.check(...) in a tenant action instead. |
TENANCY_FGA_MIXED | A platform feature's action, or an action in a partitioned feature, reads ctx.fga. A partition object's database holds no tuples. |
TENANCY_LOOKUP | tenancy.lookups.__fgaShareLink is declared by the project; the name is compiler-owned. |
Moving to 'durable-object' does not copy the tuples already in the features
D1. fga_tuples leaves the platform schema, so the next generated D1
migration may drop it. If you need the existing tuples, copy them into each
organization's object before you apply that migration.
Deleting the namespace
A deleted tombstone for QuickbackTenant destroys every tenant database.
The build refuses a bindings.durableObjectMigrations entry that deletes or
renames the class (TENANCY_NAMESPACE_DELETION) unless
tenancy.allowNamespaceDeletion: true is set and no table still lives in
a tenant object. Then the tenant Worker's exports carry
{ "state": "deleted" } and the edge no longer binds the class.
Deploying Tenant Databases
Named environments, tenant commands (tenantCommand and the compiler-owned qb.* programs), and migrations for a project with tenancy.isolation durable-object.
Tenant Database Limits
Every configuration the compiler refuses with tenancy.isolation durable-object, with its error code and the fence that replaces it.