Quickback Docs
Database per Tenant

Deploying Tenant Databases

Named environments, tenant commands (tenantCommand and the compiler-owned qb.* programs), and migrations for a project with tenancy.isolation durable-object.

How a project with tenancy.isolation: 'durable-object' deploys its two Workers per environment, the compiler-owned commands trusted edge code runs inside a tenant object (tenantCommand), and how schema migrations reach every organization's database. Start at Database per Tenant for the model.

Named environments

With named environments, every target deploys its own pair: its edge Worker (environments.<key>.name) and its own tenant Worker (environments.<key>.tenantWorker.name). The tenant Worker's script name owns the QuickbackTenant namespace, which holds every organization's database. Like name, it is required on every target and never derived.

environments: {
  dev: {
    name: 'events-app-dev',
    tenantWorker: { name: 'events-app-tenant-dev', backupBucketName: 'events-app-tenant-backups-dev' },
    /* worker, bindings, domains … */
  },
  production: {
    name: 'events-app',
    tenantWorker: { name: 'events-app-tenant', backupBucketName: 'events-app-tenant-backups' },
    /* … */
  },
}

All targets run the same bundle. The build emits:

  • wrangler.toml: one [[env.<key>.durable_objects.bindings]] per target, with script_name set to that target's tenant Worker. Durable Object bindings do not inherit, and the top level emits no tenant binding, so no target can reach another target's tenant databases.
  • wrangler.tenant.jsonc: no top-level main or exports, so a bare wrangler deploy -c wrangler.tenant.jsonc fails with Missing entry-point. The top-level name is an inert placeholder, <name>-tenant-unselected. A positional entry (wrangler deploy -c wrangler.tenant.jsonc src/tenant/index.ts) deploys an unbound Worker under that name. Without the placeholder, Wrangler would take the package.json name (the production edge) and deploy tenant code over it. No target may use the placeholder. One env.<key> block per target carries main, exports, that target's account_id (its accountId, or providers.runtime.config.accountId), its TENANT_BACKUPS bucket (backupBucketName), and the rate-limit namespaces from its own edge stanza. tenantWorker.durableObjects overrides the tenant Worker's Durable Object policy for that target, independently of the edge Worker's.
  • package.json: deploy:<key>:tenant. Each deploy:<key> runs it before the edge deploy. dev:tenant runs the dev target. There is no bare deploy:tenant.

The tenant registry, lookups and outbox live in each target's own features D1 (worker.bindings.d1.features). Jobs ride each target's own queues (worker.bindings.queues).

The build refuses:

  • a target without tenantWorker.name;
  • two targets with the same tenant Worker;
  • a backup bucket that is another target's bucket, or one of the same target's worker.bindings.r2Buckets (the same per-target R2 uniqueness rule as every other bucket);
  • a tenant Worker named like an edge or files Worker, or like the top-level project name;
  • backupBucketName missing while tenancy.backup is set, or set while it is not.

Only the target that deploys as the project name may reuse the single-target <name>-tenant script and <name>-tenant-backups bucket. Set them on that target when you adopt environments in a deployed project, so it keeps its tenant databases. The continuity check above refuses any other name for it. A tenantWorker is also refused when tenancy.isolation is not 'durable-object'.

The sharing refusals apply even when two targets deploy into different Cloudflare accounts (accountId), where the same names would not collide. This is deliberately conservative. Per-client accounts (one target per client) may relax it later.

The edge↔tenant contract is versioned (TENANT_RPC_VERSION in src/tenant/contract.ts, the same constant in both Workers). A tenant Worker answers versions from TENANT_RPC_MIN_VERSION up to its own and returns 503 TENANT_RPC_VERSION_MISMATCH otherwise. The current protocol is version 16 (version 3 put dump restore under the shared restore fence and added the authorization epoch; version 4 adds tenant commands and epoch-carrying restore permits; version 5 adds callJob() for result jobs; version 6 adds queue outbox entries for platform queues; version 7 the bounded backup read; version 8 the callJob epoch fence; version 9 the backup-fenced purge; version 10 room commit permits; version 11 leased outbox delivery; version 12 revoke outbox entries for scope revocation; version 13 armSchedules() for tenant schedules; version 14 scheduleControl(); version 15 durable Idempotency-Key receipts; version 16 partition-placed jobs). Deploy the tenant Worker before the edge: a version-15 edge carries its idempotency claim on every write, and an older tenant Worker answers it 503 TENANT_RPC_VERSION_MISMATCH rather than ignore the claim. A version-15 tenant Worker still serves older edges; their requests carry no claim and get the edge's replay cache only. An edge below version 11 gets no inline claims and keeps using takeOutbox / ackOutbox. An edge below version 12 is never handed a revoke entry, by a claim or by takeOutbox: those entries wait for the new edge, so no revocation is settled unapplied. It still accepts version-2 to version-5 edges: no method those edges call changed meaning, so deploying the tenant Worker first opens no 503 window. An edge older than version 6 is handed no outbox entries from the first queue entry on, so it never acknowledges a message it would not send; those entries wait, in order, for the new edge, and a version-2 edge's dump restore fails closed until the edge is deployed. A percentage (gradual) deploy of the tenant Worker is safe from version 3 to 4. While it runs, some tenant objects and their control objects use the old code and some the new, and both directions work. A control object answers an older holder's permit request with the plain token string that holder expects, and the holder releases it as before. A version-4 holder whose control object still runs version 3 gets a version-mismatch refusal before anything is written, then retries at TENANT_RPC_MIN_VERSION with the old protocol. Its permit then carries no authorization epoch, so command() answers unavailable / TENANT_RPC_VERSION_MISMATCH until that control object is upgraded. handle(), jobs and alarms keep serving, and the restore fence is the same permit table either way. command() itself accepts only version 4 (TENANT_PERMIT_VERSION). Upgrading from version 1 requires both Workers to be deployed. Old edge calls fail closed while the tenant Worker is upgraded first.

Tenant commands

Besides handle(), the object has one more entry point for trusted edge code: command(version, request). It runs a compiler-owned program inside the object. Callers pick a command by name and pass its fields. They never send SQL, callbacks, method names or credentials, and app code cannot add commands. Every name is reserved under qb.*.

import { tenantCommand } from './lib/tenants';

const res = await tenantCommand(env, organizationId, { name: 'qb.epoch' });
if (res.status === 'ok') res.reply.authEpoch; // { tenantId, authEpoch, lifecycle: { state, schemaVersion } }
CommandModeReply
qb.epochread{ tenantId, authEpoch, lifecycle: { state: 'active', schemaVersion } }: the authorization epoch
qb.admitScopereadRegistered only when a scope kind is tenant-backed. { kind, instanceId, tenantId, authEpoch, roles, subjectId, provingTable, subKeys }, or denied with SCOPE_EPOCH, SCOPE_NOT_FOUND, SCOPE_NO_ROLE, SCOPE_WRONG_SUBJECT or SCOPE_AMBIGUOUS
qb.scopeGrantReadreadRegistered only when a tenant-backed kind declares oauth.serverGrant. { kind, instanceId, subjectId, tenantId, authEpoch, linkedUserId, roles, subject, instance } (identity and instance projections as JSON), or denied with SCOPE_NOT_FOUND or SCOPE_GRANT_SUBJECT_DENIED
qb.scopeGrantLinkwriteSame registration. { kind, instanceId, subjectId, tenantId, authEpoch, outcome: 'linked' | 'unchanged' }, or denied with SCOPE_EPOCH, SCOPE_NOT_FOUND, SCOPE_GRANT_SUBJECT_DENIED or SCOPE_GRANT_LINK_CONFLICT
qb.roomAccessreadRegistered only when a resource-backed realtime room is on a tenant table (Tenant rooms). { room } when the room's row passes the table firewall for a member of this organization, else denied with ROOM_ACCESS_DENIED

tenantCommand first reads the organization's tenant_registry row, and wakes the object only when the registry vouches for it:

Registry rowResult
None: the platform has never served the tenant, or its first report is still in flightunavailable / TENANT_NOT_PROVISIONED (retryable). The object is not woken, so no empty tenant database is created.
purgedunavailable / TENANT_PURGED, without waking the object
Written under another tenancy.jurisdictionunavailable / TENANT_JURISDICTION_MISMATCH
Registry read failsunavailable / TENANT_UNAVAILABLE
Any other stateThe object decides (archived, migration and restore are checked there)

A tenant gets its row when it first serves a request or a job, or when an operator provisions it (POST /tenants/:id/provision, provisionTenantTarget in src/lib/tenants.ts: verified against Better Auth's organization table first — organization, or organizations with the database's usePlurals: true, like every generated import of a Better Auth table in both Workers). Until one of those, a new organization's commands answer TENANT_NOT_PROVISIONED. denied is kept for definitive refusals made by a command. Pass only a server-verified organization id, never one taken from the request. The HTTP forwarder (tenantForward) does not read the registry: it routes the authenticated principal's organization, so it adds no D1 read per request.

The object then checks each request in this order:

  1. The RPC version. command() accepts only version 4 or later (TENANT_PERMIT_VERSION). Then TENANT_COMMAND_FINGERPRINT, a hash of the command registry that both Workers carry in src/tenant/contract.ts. It is checked before the name, so a split deploy reports itself as one. Then the command name and the exact request shape: unknown fields are refused, and string fields are capped at 512 characters. Then the target: the request's tenantId must be this object's name. Partition objects and control objects serve no commands. Each failure throws (TENANT_RPC_VERSION_MISMATCH, TENANT_COMMAND_FINGERPRINT_MISMATCH, TENANT_COMMAND_INVALID) before the command reads any tenant data. As with every RPC, waking the object still runs its own migrate on wake first.
  2. The restore permit. The permit also carries the authorization epoch, and no restore can begin while it is held. A pending restore answers unavailable / TENANT_RESTORE_PENDING.
  3. Archived, purged and unmigrated objects answer unavailable (TENANT_ARCHIVED, TENANT_PURGED, TENANT_MIGRATION_FAILED).
  4. The body runs in one ctx.storage.transactionSync, with no await. A write command marks the object dirty inside that transaction, so the next backup includes it, and the backup is scheduled after the transaction commits.

tenantCommand(env, tenantId, request) returns { status: 'ok', reply } | { status: 'denied', code } | { status: 'unavailable', code }. It checks the reply against the command's schema; a reply of the wrong shape becomes unavailable / TENANT_COMMAND_REPLY_INVALID. Read commands are retried once after an object reset or a retryable RPC error. Write commands are sent once, and overloaded objects are never retried. Failures carry codes only: TENANT_UNAVAILABLE, TENANT_OVERLOADED, TENANT_DEPTH_EXCEEDED, TENANT_RESTORE_PENDING, the registry codes above, or one of the refusal codes above. A version or fingerprint mismatch is unavailable, not denied: it is deploy skew, not a policy decision. For a write command, unavailable means the outcome is unknown: the write may have committed before the failure. Logs record the command name and code, never the request or the error text. A malformed (or null) request, an unknown command, or an organization id that is reserved, contains : or is longer than 512 characters throws.

Commands do not carry the wake report or the outbox signal that handle() responses do. A command write that queues outbox entries (lookup, audit, realtime, jobs) is applied on the object's next drain: the next proxied request that reports a non-empty outbox, the object's next alarm (which asks the edge to drain it), syncTenants(env), or drainTenantOutbox.

Migrations

Tenant tables have their own migrations in quickback/drizzle/tenant/. The build bundles them into quickback/drizzle/tenant/migrations.ts, and each object applies pending migrations when it wakes:

  1. Inside blockConcurrencyWhile, so no request runs against an old schema.
  2. All pending migrations in one transaction, recorded in __qb_tenant_migrations.
  3. A point-in-time-recovery bookmark is taken first and reported to tenant_registry.last_pre_migration_bookmark.
  4. A failure never throws from the constructor. The object records it and answers 503 TENANT_MIGRATION_FAILED with the real SQLite error (0001_x: UNIQUE constraint failed: …). The failing statement goes to the logs and tenant_registry.last_error, never to the client. Other tenants keep serving.
  5. Before migrating, the object records which migrations it is attempting and flushes that record (storage.sync()). A wake that finds the same attempt unfinished was preceded by a reset mid-migration — the 30 s blockConcurrencyWhile limit, but also eviction, a deploy or a failover — so it retries. After 3 resets of the same pending set the object marks itself failed instead of retrying on every request. A different migration set starts a fresh count; POST <api>/tenants/:id/retry-migration clears the count and migrates again.

SQL triggers on tenant tables — your sql: triggers and the compiler's own (the FK match checks) — install in the same wake, after the migrations, whenever their content hash changes or a migration ran (a table recreate drops its triggers). They never reach the features D1. A dump restore drops every table with its triggers, loads the rows with no trigger firing, then runs this same wake, so the triggers come back; a point-in-time restore rewinds the triggers together with the data.

Keep wake work well under 30 s. The object never sets an alarm while recovering, so a failing wake cannot reset the platform's alarm retry budget.

Restoring the bookmark discards writes made after it. It recovers a failed migration; it is not a rollback.

The build refuses drizzle-kit table-recreate migrations on tenant tables (TENANCY_UNSAFE_RECREATE) when the table is referenced by another table, or when the copy targets a NOT NULL column that was nullable or has no DEFAULT. Inside the migration transaction PRAGMA foreign_keys=OFF is a no-op, so the recreate's DROP TABLE cascade-deletes child rows in every tenant. No migration is written. Make the change additive (a new nullable column or a new table, backfilled by a data migration) and rebuild.

Keep tenant schemas additive across one release: during a rollout, objects still on the previous Worker version read the same tables.

On this page