Tenant Table Placement
Which tables move into per-organization Durable Objects, which stay on the platform D1, lookup indexes, and partitions.
With tenancy.isolation: 'durable-object', the compiler decides per table whether it lives in each organization's Durable Object or in the shared platform D1. This page covers that decision, changing it on a deployed table, platform lookup indexes into tenant tables, and partitions. Start at Database per Tenant for the model.
Tenant ownership
Inside the object, a tenant table's effective firewall is the authored one behind a tenant pin:
organizationId = ctx.tenantId AND (<the firewall you wrote>)ctx.tenantId is the organization the object serves. The object sets it from
its own name on every request and job, overwriting whatever the caller sent;
the edge strips it before forwarding. Three things follow:
- Reads. Every read is pinned to the object's organization, including
skipTenantScopesrelationship probes and the sysadmin escape. A row naming another organization — a bad copy or restore — is invisible to everyone. - Writes. Every insert stamps
organizationIdfromctx.tenantId: CRUD create, changesets, upserts, batch and the actiondb. An attendee with no active organization creates rows in the right tenant. - Who sees what is still the authored firewall.
any: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }, { field: 'eventId', equals: 'ctx.scope.event' }]lowers to tenant AND (org member OR attendee of this event). The org arm means org membership. A relationship or scope caller never getsctx.activeOrgIdfrom its relationship row, so it reads its own event's rows, never the organization's. An org-only table is for members only: a non-member's list or create gets403 ORG_REQUIRED, and a read by id finds nothing. The pin itself never satisfies that check — creates on a members-only table still need the caller's ownctx.activeOrgId, while an org-OR-scope table's creates are bounded by the firewall-on-write check.
ctx.tenantId is compiler-owned: the build adds the pin for you, and a
firewall that names ctx.tenantId itself is a compile error, in either
isolation mode.
A tenant object holds one organization, pinned through one column. A firewall
whose org arms bind two different organization columns (a buyer and a seller
org on one row) fails with TENANCY_ORG_COLUMNS. An any: [org, owner] table
that moves into tenant objects prints a warning: each request reaches one
object, so an owner without an active organization no longer reaches their
rows across organizations.
The pin does not change the edge↔tenant contract, so TENANT_RPC_VERSION
stays the same. The pin is compiled into the tenant Worker's own code, the
tenant object sets ctx.tenantId itself, and the edge strips any forwarded
value. A mixed rollout is therefore safe in both directions: an older edge
cannot supply a tenant, and an older tenant Worker never reads one.
Placement changes on deployed tables
Once a project runs with isolation: 'durable-object', its features D1 holds
only platform tables. So a table that is in the deployed features D1 (the
quickback/drizzle/features snapshot) and that the firewall places in tenant
objects is moving — a shared project switching to 'durable-object', or an
any: / optional organization arm that the old rule placed on the platform.
Without a declared placement it fails the build with
TENANCY_PLACEMENT_MOVED: deploying would leave
its rows in D1 while each tenant object serves an empty table. Declare
placement: 'tenant' once its rows are copied into each organization's object,
or placement: { platform: true, crossTenant: true } to keep it where it is.
quickback build sends the deployed table list as
migration.priorState.existingFeaturesTables (an older CLI does not). A build
with no deployed-schema facts at all — no existingFeaturesTables and no
features history, or a latest snapshot that does not parse — cannot tell, so every table whose placement derives
tenant only from an any: / optional organization arm fails with
TENANCY_PLACEMENT_UNCONFIRMED until it declares its placement (or the build
runs with a current CLI). A project with no migration history at all is
greenfield: the CLI sends an empty list, and a raw-files validate compile
treats missing history the same way.
Override it per table with placement. An organization-scoped table kept on
the platform must say so, because every tenant's rows then share one database:
placement: { platform: true, crossTenant: true },All features sharing a partition kind must use the same key column. All tables in one feature share a placement, because they share one schema file and one route file. To shard a high-volume feature further, see Partitions.
When a tenant table's organizationId or a foreign-key column has no index,
the compile prints one [quickback:notice] listing every such table.column:
each request filters, and each FK check reads, on it. It is a performance hint,
not a security warning.
Admission tables stay on the platform
Only a tenant-backed scope kind, its
tenant namespaces and its tickets admit inside tenant
objects. Every other admission and request-time authorization path runs on the
edge Worker and reads its tables from the platform D1. If a tenant object held
one of those tables, the D1 copy would be missing. Or, during a migration, it
would be a stale copy whose rows keep admitting subjects the tenant has
already revoked. So the build fails with TENANCY_ADMISSION_DEPENDENCY when
any of them reads a tenant or partition table. A scope kind that reads a
tenant table but can't be tenant-backed fails with the planner's own codes
instead (see Which kinds can be tenant-backed),
and a namespace with TENANCY_NAMESPACE_*:
| Surface | Tables checked | Paths named in the error |
|---|---|---|
authz.scopes.<kind> | each role's relationship tables (from and any hops), each role's self.table, and the instance table | instance-bound OAuth (authorize, code exchange, refresh, issueScopeGrant, bound namespace and ws-ticket checks), the ctx.self recheck on every action route, and the scope refresh of each namespace using the kind's relationships |
authz.namespaces.<name> | relationship lanes' tables and the loads table | namespace gate and hydration |
realtime.wsTicket | scopeTable, the tables behind role / access.authzRole, and the namespace lanes | ws-ticket mint |
| A platform feature | every relationship its CRUD, read, view, masking and action access, and its firewall arms, resolve: authz.roles relationship roles, authz.rules, authz.permissions (including arrows from / to) and direct via arms, with hops and loads | request-time authorization |
A platform action with anchor | the relationship's tables and its reach tables | anchored transaction |
A platform action's refs and operator | each ref's table, each ownedVia.junction, and operator.target.table | loaded and firewalled before execute |
| A platform table's derived JSON keys | each derivedFrom.table | CRUD reads and action requires: |
A live view (defineView) | root and every project-table include | the view materializer (GET /views/..., ws-ticket view lane) |
The error names the surface, the paths that depend on it, and each tenant
table with its placement. A scope kind whose instance table is ambiguous also
fails: set authz.scopes.<kind>.instance. A kind with no resolvable instance
table loads no instance, so only its relationship tables are checked, unless
the kind is also a tenancy.lookups key. Then its tokens are routed by an
instance id that no table binds to a tenant, so the build fails until you set
instance.
The table above is what the compiler names in friendly messages. Three more checks stand behind it:
- Platform action source. A platform action or feature
lib/file that names a tenant table fails the build. So does a schedule (services/schedules), a queue handler that is not a tenant job, and anyquickback/libhelper, auth hook (quickback/hooks), middleware (quickback/middlewares) or Better Auth plugin (quickback/plugins) the edge Worker loads (scanned per module). That covers its export name as an identifier, its SQL name as a string (an inlinesqliteTable("projects", …)), andFROM/JOIN/INTO/UPDATE/TABLE <name>in any string or template (in actions, only withallowRawSql). The scan is conservative: a local variable that only shares a tenant table's name is refused too, so rename it. Instead of a cron sweep, declare a tenant schedule (each object runs its own work on its own alarm) or have the edge arm a tenant job (scheduleTenantJob); to read a tenant's data from the edge, call a result job. - The emitted edge bundle. After all files are generated, the compiler
walks the edge Worker's runtime imports from
src/index.ts. It follows relative imports,tsconfig.jsonpathsaliases such as~/,export … from, and literalimport()/require(). Type-only imports are skipped. The build fails if an edge module imports a tenant feature's module (its schema, table, resource or routes), or callsimport()/require()with a computed path the walk can't follow. - At runtime.
src/lib/firewall-registry.tsis the one edge module allowed to import tenant modules. It maps every table to its firewall for the scopeddb. Only its tenant imports are exempt; its other imports are still walked. Its tenant entries throwTENANT_TABLE_ON_EDGEoutside the tenant Worker, so an edge query that slips past the compile-time checks fails instead of reading D1. A raw SQL string that never goes through the scopeddbis caught only by the compile-time scan.
To fix it, keep those tables on the platform. An organization-scoped one needs
placement: { platform: true, crossTenant: true }. A platform table can't
hold a foreign key into a tenant table (TENANCY_FK_PLATFORM_TO_TENANT), so
move the tables it references with it, or drop the reference. Or remove the
dependency.
Lookup indexes
Some lookups start from a value, not an organization: an invite code, a public
slug, an SES message id, a phone number. Declare them in tenancy.lookups:
lookups: {
inviteCode: { table: "invites", column: "code", hash: true },
event: { table: "events", column: "id" },
},SQL triggers in every tenant object record each insert, update and delete of
the column (soft-deleted rows count as deleted) in the object's outbox. The
edge applies them to the platform tenant_lookups table after the response, in
order (tenant_registry.outbox_seq drops a stale batch). Read it on the edge:
import { resolveTenant, resolveTenants } from "../lib/tenants";
const tenantId = await resolveTenant(env, "inviteCode", code); // null, or throws if several
const phoneTenants = await resolveTenants(env, "phone", phone);A lookup named after a scope kind resolves tokens: an instance-bound token
(ctx.oauth.boundTo) reaches the organization whose rows hold that id.
Without a matching lookup those tokens get 400 TENANT_REQUIRED. A token for a
tenant-backed kind is the exception:
it routes to the tenant it pins, and the lookup is used only to issue it.
The index converges, it is not transactional with the write: it lags until
the edge drains the object's outbox (after that object's next response, or
syncTenants(env)). Adding a lookup re-sends every current key on each
object's next wake.
Hashed lookups
Every organization's lookup rows share one D1. A lookup whose values are
credentials (invite tokens, share-link tokens, sign-in codes) should not sit
there in plaintext: set hash: true. The row's key is then h1: followed by
HMAC-SHA256(TENANT_LOOKUP_KEY, "<name>\0<value>") as 64 lowercase hex. The
h1: marker tells a hash from a value that is itself hex, so a row written
before hashing is always recognisable. The lookup name separates domains, so
the same value in two lookups gets two unrelated keys. A lookup column whose name reads like a credential (token,
code, secret, key, password) and is not hashed draws a
TENANCY_LOOKUP_PLAINTEXT compile warning. Ids and slugs are fine in plaintext.
When the values are not secret, acknowledge it once on the lookup and the
warning stops:
lookups: {
projectCode: { table: "projects", column: "code", hash: false, reason: "project codes are printed on invoices" },
},reason needs hash: false and a non-empty string; anything else is a
TENANCY_LOOKUP compile error.
- The secret.
TENANT_LOOKUP_KEYis required on the edge Worker (it joins the generated secret inventory and the boot guard): one or more 64-hex keys (openssl rand -hex 32), comma-separated, primary first. The tenant Worker never holds it. Its outbox carries the value to the edge, which hashes before anything reaches D1. A missing or malformed key refuses: the outbox entries retry, and resolution fails, so nothing is ever written in plaintext. - Unchanged API.
resolveTenant(env, name, value)takes the value and hashes it. Receipts record the lookup name only. A dead-lettered lookup row copied to the audit database at purge has its value withheld. - Rotation. Resolution tries every key and re-keys a row it finds under an
older one; writes use the first. Rotate in two deploys, so no isolate still
on the old list writes a row the others cannot clean up: (1) append the new
key (
old,new) and deploy; (2) promote it (new,old) and deploy; (3) runPOST /tenants/:id/rebuild-lookupson every organization, which re-publishes each object's rows under the new key; (4) drop the old key. - Turning it off. Removing
hash: true(or rolling the edge back past it) leaves the hashed rows unresolvable: rebuild every organization's lookups afterwards. - Adopting
hash: trueon an existing lookup. Rows written before it hold the value. Resolution also matches the plaintext row (never a value shaped like a stored hash) and re-keys it. Every outbox drain of an object (a request, a job call, an alarm's drain request, an operator call) and its wake report convert up to 100 of that object's plaintext rows in place first, once per object per isolate. For organizations that do not wake, runPOST /tenants/lookups/migrate(orsyncTenants(env), which also converts up to 200 rows across objects) until it reports none remaining — manually, not on a cron. Any write of a key replaces its plaintext row. Set the secret first, then deploy the tenant Worker, then the edge.
Partitions
One object per organization puts a busy organization on one thread. Shard a high-volume, naturally partitioned feature by its unit of contention:
placement: { partition: "conversation", key: "conversationId" },Each (organization, key) gets its own object, named <orgId>:<key>, so the
object name alone says which tenant it serves. The table stays
organization-scoped (the firewall still applies) and every table in the feature
uses the same key.
| Request | Result |
|---|---|
Key from ?conversationId=, the x-quickback-partition-key header, or the JSON body field | Forwarded to <orgId>:<key>; the query parameter is consumed |
| No key | 400 PARTITION_KEY_REQUIRED |
| Two different keys in one request | 400 PARTITION_KEY_MISMATCH |
| A row whose key differs from its object's | Refused by a trigger in the object (400 PARTITION_KEY_MISMATCH) |
Partition objects carry the same schema and migrations as organization
objects (their organization tables stay empty), take their own backups, and
appear in tenant_registry with partition_key. One partition kind per
project (TENANCY_PARTITION_KINDS).
No foreign key and no action crosses partitions: the build refuses
TENANCY_FK_CROSS_PARTITION and TENANCY_CROSS_PARTITION. Store the other
side's id without .references() (opt it out of the reference diagnostic with
references: { projectId: { references: false, reason } }) and send the update
through the outbox — delivered by the edge after the response, at least once,
to a tenant job in the target object:
const [row] = await db.insert(messages).values({ conversationId: input.conversationId, body: input.body }).returning();
tenantRuntime(env).send("tenant", { type: "conversation.posted", conversationId: input.conversationId });send("tenant", …) targets the organization object; send({ key }, …) a
partition object of the same organization, and only with a
partition job (TENANT_JOB_PLACEMENT otherwise, at write
time).
Database per Tenant
tenancy.isolation 'durable-object' gives every organization its own SQLite database in a Durable Object, served by a generated tenant Worker, while the edge Worker keeps auth, routing and platform tables.
Tenant-backed Scope Kinds
Scope kinds whose admission runs inside the organization Durable Object — requirements, qb.admitScope, server-issued grants, tenant namespaces and namespace actions.