Quickback Docs
Database per Tenant

Files, Embeddings and Deletes in Tenant Databases

Managed files, embeddings, hard deletes and the audit log when every organization has its own Durable Object database.

How managed files, vector embeddings, hard deletes and the audit log behave when each organization's rows live in its own Durable Object. Start at Database per Tenant for the model.

Managed files

A tenant table may declare a q.storageKey() column once the file bridge is on. Without it the column is refused (TENANCY_UNSUPPORTED).

tenancy: {
  isolation: 'durable-object',
  bridges: { files: { enabled: true, maxGrantSeconds: 600 } },
},

The object owns the row. The edge Worker alone holds the R2 binding and the presign secrets (R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). The tenant Worker gets neither; the import-closure check refuses src/lib/storage-keys.ts and src/lib/tenant-files.ts in tenant code, which runs against a tenant copy (src/tenant/storage-keys.ts) with the same key rules. Actions keep the same API as on the edge: db.allocateUpload, db.signDownload, and db.finalizeUpload.

Upload. db.allocateUpload(table, { ...values, ext, mime, size }) checks the type and size, then writes the row with its rendered key. In the same SQLite commit it records a reservation in the object's __qb_file_ops table and a deferred verify entry in the outbox. It returns { row, key, putUrl, headers, expiresAt, uploadId, status: 'pending' }. The object cannot sign, so putUrl leaves it as a marker. The response carries the reservation as a grant (a bridge envelope in a response header). Before the response leaves, the edge:

  1. checks that the grant names the object the edge routed to, that its table, column and key match the compiled registry and template, that its type, size and lifetime fit, and that its generation is the registry's current one (no pending restore, no purge cleanup running);
  2. writes the key to the platform manifest (tenant_file_manifest, features D1) as pending. A key the manifest already holds for another operation, or with different identity fields, is refused;
  3. signs the PUT and substitutes the marker. Any refusal replaces the whole response (TENANT_BRIDGE_*, TENANT_FILE_*, STORAGE_UPLOAD_*): a marker never reaches the client unsigned.

Bytes go from the client to R2. They never cross the object or its RPC. An older edge (below TENANT_FILE_BRIDGE_VERSION) is refused before any row is written (503 STORAGE_FILE_BRIDGE_EDGE_OUTDATED). So are jobs and alarms, which have no response for the edge to sign (STORAGE_FILE_BRIDGE_UNAVAILABLE).

Finalize. After the PUT, db.finalizeUpload(table, id) loads the row through the firewall and makes its verify entry claimable at once. The edge applies it from the response: it HEADs the object, and when the size and Content-Type match the reservation, marks the manifest row live and settles ready. The object marks the file ready only if the row still holds that key. Call finalizeUpload again to read the status: pending, ready, deleting, deleted, or unavailable. Without a finalize, the verify runs when the grant expires plus a five-minute grace, on the object's next drain. An object that is missing then, or one that does not match, is tombstoned and deleted (unavailable). An expired, replaced or rejected upload can never become ready.

Reads. db.signDownload(table, id) loads the row through the firewall and the table's access, then grants only a ready file of that row in the current generation (409 STORAGE_FILE_NOT_READY, details.status otherwise). The edge signs it only for a live manifest row of the same object, table and key. Organization membership alone is not row access: a member the owner arm excludes gets 404, as for any read. A signed GET is a bounded capability. It stays valid until it expires (at most maxGrantSeconds, default 600) even if the row is deleted or access is revoked meanwhile. Keep maxGrantSeconds short, or serve the bytes through your own authenticated action.

Deletes and replacement. The generated hard DELETE /:id and DELETE /batch, and db.delete(table) in an action, record a delete intent for each erased row's key. The generated routes write it in the delete's own transaction. allocateUpload(..., { id }) gives the row a new key and records a delete for the old one. The edge tombstones the manifest row first (irreversible), then deletes the object, then marks it deleted. A missing object counts as deleted. Retries repeat the same idempotent steps, and a deleted key is never signed again. The object reports a delete as deleting until the edge settles it. db.transaction() is synchronous in the object, so a storage-key delete inside one is refused (STORAGE_KEY_TX_DELETE): delete outside it. Raw SQL that bypasses the scoped db records nothing. Call deleteStorageObjects(env, table, rows) from src/tenant/storage-keys after it, as on the edge.

Keys. The stored key is the column's template rendering. The edge prefixes it with an immutable namespace the object never chooses: qbt/<project>/<environment>/<organization>/o/<stored key>. The environment is QUICKBACK_ENVIRONMENT, stamped on every named environment when the bridge is on, else default. A grant or entry is accepted only for its own organization's namespace. Partition tables cannot hold storage keys yet (TENANCY_UNSUPPORTED).

Restore. R2 objects are not in tenant dumps, and a database restore cannot bring back deleted bytes. When a restore takes effect, the old generation's file entries are discarded with the rest of its outbox. Every key the restored rows hold returns to pending and gets an attest entry in the new generation. The edge marks it ready only if the manifest row is still live and the object exists. A tombstoned or missing object stays unavailable, with the reason in __qb_file_ops.reason. Restore never clears a tombstone. Reservations of the abandoned timeline that the restored rows do not hold become unavailable; they are not deleted. A delete the restore discarded is queued again if the restored rows no longer hold the key. A grant or outcome from the old generation changes nothing.

Purge. The purge drain applies every pending file entry. A grant that was never uploaded is cleaned up at once, not left waiting for its expiry. After the object is erased, purge fences new grants for it (TENANT_FILES_PURGING) and starts a bounded cleanup with a durable cursor (tenant_file_purges). Every manifest object is tombstoned and deleted. Once every grant ever signed for the object has expired (plus grace), the organization's R2 prefix is listed and anything without a live manifest row written after the purge began is deleted. That sweep catches late uploads of unexpired grants. syncTenants resumes unfinished cleanups. cleanupTenantFiles(env, id) (from src/lib/tenants) runs one step and returns { done, phase, deleted }. Report the external cleanup complete only once done is true.

Version skew. A project with the bridge emits tenant RPC version TENANT_FILE_BRIDGE_VERSION. Projects without it keep their version unchanged. An older edge is never handed a file entry. Deploy the tenant Worker first, as always.

The bridge contract

Every bridge message is one envelope, defined in src/tenant/bridge.ts, which both Workers import:

FieldMeaning
vProtocol version (1).
bridge'files' or 'embeddings' (Embeddings). Each bridge has its own ops and payloads; the envelope, identity and outcome rules are shared.
opFiles: put / get (grants); verify / delete / attest (outbox entries). Embeddings: index / delete (outbox entries).
opIdStable operation id, carried by every retry of the operation.
object{ tenantId, partition } of the object that wrote it. The edge compares it with the object it routed to or drained, and never trusts it.
generationThe object's outbox / restore generation when it was written.
payloadOp-specific. For files: { table, rowPk, column, key, ... }. For embeddings: { table, rowPk, revision, configVersion, text } (index) or { table, rowPk, vectorId } (delete).

The deduplication identity is (object, generation, opId). The edge hashes the payload's identity fields per operation (files: table, rowPk, column, key; embeddings: table, rowPk, revision, configVersion). It refuses a later message with the same opId and a different hash (TENANT_BRIDGE_PAYLOAD_CONFLICT); an outbox entry is dead-lettered, never applied. Outcomes come back in the settlement's delivery receipt: detail.bridge = { opId, state, reason? }. The receipt keeps the operation id in ref. The object applies an outcome only when the envelope's generation is its current one and the operation is still in the state that outcome moves from. A duplicate or stale receipt is harmless. Delivery is at least once, so every external transition is idempotent.

Embeddings

A tenant table may declare embeddings once the embeddings bridge is on. Without it the declaration is refused (TENANCY_UNSUPPORTED). The project also needs a Vectorize index (providers.database.config.vectorizeIndexName).

tenancy: {
  isolation: 'durable-object',
  bridges: { embeddings: { enabled: true, candidates: 50 } },
},

The object owns the row and the intent. The edge Worker alone holds the AI and VECTORIZE bindings. The tenant Worker gets neither, and the import-closure check refuses src/lib/tenant-embeddings.ts in tenant code. There is no embeddings queue or consumer for tenant tables, and no client-facing embeddings endpoint.

Intents. Every insert, update and delete through the scoped db passes the audit wrapper's write chokepoint. That covers generated CRUD and batch routes, actions, jobs and trigger hooks. For each returned row the object re-reads the row's source fields from SQLite. When the text changed, it bumps the row's revision in __qb_embedding_ops and writes an embedding outbox entry (index) in the same SQLite transaction. A write that rolls back leaves no intent. A write whose text did not change writes none. A delete, a soft delete, or a row whose text is now empty writes a delete for its current vector. onInsert: false and onUpdate: false are honored. onUpdate: [fields] behaves like true, because only a change of the embedded text re-indexes. The entry carries the text, capped so the envelope fits the shared 8 KB limit; the models truncate far below it. The write must use .returning() with the primary key, as for every chokepoint consumer. A .returning() without it is logged and skipped. Raw SQL that bypasses the scoped db, and sql: triggers, record nothing. Re-index after them with rebuildTenantEmbeddings.

Edge execution. The drain applies index entries in order, after the claim's registry fence held:

  1. The vector id is derived here, never by the object. It is a SHA-256 of project, environment, organization, generation, table, row, revision and configuration version. Ids are immutable: a late result never overwrites newer content under the same id.
  2. The id goes into the platform manifest (tenant_embedding_manifest, features D1) as pending before Workers AI is called. Cleanup never depends on enumerating unknown vectors. An entry whose id the manifest holds for another operation is refused (TENANT_BRIDGE_PAYLOAD_CONFLICT). A newer revision of the same row already indexed skips the AI call (obsolete).
  3. Workers AI embeds the text. A vector of the wrong dimensions is refused and never stored (TENANT_EMBEDDING_DIMENSIONS).
  4. The vector is upserted into the organization's namespace. That is a hash of project, environment, organization and table, derived by the edge.
  5. The manifest row moves to live only if it is still pending. If a delete or a sweep tombstoned it during the call, the edge deletes what it just wrote and settles obsolete.

The object accepts a ready outcome only for the same operation and revision, in its current generation, while the row is still pending. Anything else is obsolete, and the object queues a delete for that vector. Delivery is at least once. A retry repeats the same id and values. An AI call may still run twice, or after the row changed; it costs a call, never correctness. The configuration version hashes model, fields and separator. An entry written under another configuration settles obsolete without an AI call.

Deletes. A delete entry tombstones the manifest row (irreversibly), deletes the vector, then records it deleted. A missing vector counts as deleted. A tombstoned id is never indexed again.

Search. GET <collection>?similar=<text> and GET <collection>/views/<name>?similar=<text> are the semantic reads. Before forwarding, the edge authorizes and rate-limits the caller, then embeds the text (at most 1 KB) and queries the organization's namespace for candidates matches (default 50, 10–100). The client never chooses the namespace. The matches ride the RPC principal, not a header, so a client cannot supply them. In the object, a match resolves to a row only through that row's current ready vector in the current generation and configuration. The resolved rows join the read route's filter set beside the firewall, access, soft-delete and query filters. Masking and views then apply as for any read. Results come best match first unless ?sort= is given.

  • Rejected candidates leave no trace. There are no scores, no vector metadata, no ids and no counts.
  • ?similar= cannot be combined with ?search=, ?total=, aggregations or cursors (400). Pages use ?offset= / ?limit=, and offset + limit may not exceed candidates (400).
  • Without matches carried in, for example from an older edge, the route answers 503 EMBEDDING_SEARCH_UNAVAILABLE, never an unfiltered list. If the AI or Vectorize call fails, the edge answers the same.
  • The edge evaluates the read route's role gate (view.access ?? read.access, the same evaluateAccessPreRecord the object runs) before any AI or Vectorize call. A refused caller gets the object's own 403 ACCESS_ROLE_REQUIRED body and costs nothing. An unknown view embeds nothing; the object answers it.
  • The edge then charges the table's read rate limit (the same RL_<limit>_<period> binding the read route uses, bound on the edge Worker too) under its own key, <table>:similar:<organization>:<caller> — one bucket per user per organization, separate from the list's own count. Over the cap: 429 RATE_LIMITED with Retry-After, and no AI or Vectorize call. rateLimit: false on the resource or project turns it off; an unbound limiter (local dev) no-ops.
  • The edge checks the registry before any AI or Vectorize call. A purged object gets 410 TENANT_PURGED; one with a restore pending, or not active, gets 503 TENANT_RESTORE_PENDING.
  • Indexing is eventual. Right after a write, a row may be missing from results until its new vector is ready. A query may return fewer than limit rows when candidates fail the filters. It is not an exact top-K.

The vector namespace is the organization. So the table's firewall may bind only its organization column, and its read access must be role-only. An owner arm, a record predicate, a relationship or FGA arm, or an access function would make the candidate universe wider than the caller's rows (TENANCY_EMBEDDINGS_SCOPE). Source fields must be plain columns. Masked, .encrypted(), .sealed(), q.secret(), q.vaultRef() and q.storageKey() columns are refused (TENANCY_EMBEDDINGS_PROTECTED_SOURCE). Vectors live only in Vectorize: embeddingColumn (TENANCY_EMBEDDINGS_COLUMN) and metadata (TENANCY_EMBEDDINGS_METADATA) are refused. Use ordinary query filters beside ?similar= instead. Partition tables cannot embed yet (TENANCY_UNSUPPORTED). A defineEmbedding search helper over the same index is refused (TENANCY_EMBEDDINGS_SERVICE). It queries without a namespace and returns raw ids and scores.

Models. @cf/baai/bge-small-en-v1.5 (384), @cf/baai/bge-base-en-v1.5 (768, the default), @cf/baai/bge-large-en-v1.5 (1024) and @cf/baai/bge-m3 (1024). Every embedded tenant table shares the one index, so they must share a dimension (TENANCY_EMBEDDINGS_MODEL). Create the index with that dimension and cosine metric. A model or field change changes the configuration version. Until a rebuild, old vectors stop matching. A change of dimension needs a new Vectorize index (a new vectorizeIndexName) and a rebuild of every organization. The bridge does not build a second index side by side.

Restore. When a restore takes effect, the old generation's embedding entries are discarded with the rest of its outbox. Every restored row is re-indexed in the new generation with a new revision and vector id. Rows the restore removed are marked deleted. A vector from the old generation never resolves to a row, because the generation is checked, and a late old-generation receipt never reaches the object. The manifest is outside the rewound database. syncTenants sweeps vectors whose generation is not the registry's current one, once they are five minutes old, so in-flight results land first. The sweep tombstones, deletes and records them.

Purge. The purge drain settles pending index entries without an AI call. It still applies delete entries. Once the registry row is purged, searches are refused before any AI call, and every manifest vector of the object is an orphan. syncTenants deletes them in bounded, resumable steps. cleanupTenantEmbeddings(env, id) (from src/lib/tenants) runs one step and returns { deleted, done }. Report the external cleanup complete only once done is true.

Operations (from src/lib/tenants; authenticate the caller and verify the tenant first):

CallDoes
rebuildTenantEmbeddings(env, id, table, { after?, pageSize?, maxPages? })Re-indexes rows in bounded pages by primary key, draining after each page. It skips rows whose current vector is ready for the same text, generation and configuration. Returns { queued, done, next }; pass next back as after to resume. Use it after a configuration change, a raw SQL write, or to retry failed rows.
tenantEmbeddingStatus(env, id)Counts per table and state (pending, ready, failed, obsolete, deleted). Rows from a previous generation are counted apart.
cleanupTenantEmbeddings(env, id)One bounded orphan-cleanup step for the object.

Version skew. A project with the bridge and an embedded tenant table emits tenant RPC version TENANT_EMBEDDING_BRIDGE_VERSION. Projects without it keep their version unchanged. An older edge is never handed an embedding entry, and the object ignores semantic matches from one. Deploy the tenant Worker first, as always.

Not proven by local tests: real model dimensions, Vectorize namespace limits per index, Vectorize's eventual consistency after upserts and deletes, and query latency. Verify those against a dedicated Cloudflare test account before relying on them.

Hard deletes and the audit log

The tenant Worker has no AUDIT_DB. A hard DELETE (single or batch) on a tenant table writes its audit_events row to the object's outbox — in the object's own SQLite, in one transaction with the delete, so a failed delete leaves no audit row — and the response tells the edge to drain it. The edge sets each row's target_org_id and actor_org_id to the object's organization (tenant code cannot attribute a row to another one; a mismatch is logged and kept in metadata.tenantClaimed), writes the rows to the audit database (idempotent by id), then acknowledges them. Unacknowledged rows are retried after the object's next response. A malformed audit payload moves to the object's __qb_outbox_dead table instead of blocking the queue, and tenant_registry.outbox_dead_letters counts them. Database failures leave rows queued for retry; error messages never classify them as permanently invalid. Purge first drains pending rows and copies dead letters into the audit database. If either step fails, or pending rows remain, purge refuses to erase the object. Purge is exclusive. It takes the control object's maintenance fence, which is refused (TENANT_BUSY) while any request, job or alarm holds a permit, including one waiting on I/O, so nothing writes into the object after it is erased. deleteAll() erases any marker the object keeps itself, so purge then turns that fence into a permanent purged marker in the object's control object (__qb_control__:<name>, outside the tenant's storage). Only then does it call deleteAlarm() and deleteAll(), and mark its own storage purged. A reset anywhere in between leaves a tenant that is still purged, never a live empty one:

  • Every request, command, job, alarm and schedule takes a permit from the control object, and the permit carries the marker. The object answers 410 TENANT_PURGED, and commands answer unavailable / TENANT_PURGED, even while its own storage still says archived.
  • On wake, an archived object asks its control object, and so does any object that has not yet had one successful check. If the marker is there, the object does not migrate: it marks itself purged and reports tenant purged. If the control object cannot be read, the object migrates as usual and asks again on its next wake. It still serves nothing, because its permits carry the marker.
  • Archive, unarchive, restore, cancel-restore, retry-migration, backups, scheduling and lookup rebuilds all refuse a purged tenant.

tenant_registry still says archived after an interrupted purge. To recover, retry POST /tenants/:id/purge. Purge is resumable: once the marker exists it needs no fence, erases whatever is left, and marks the registry purged. The retry keeps last_purge_bookmark from the first attempt and never records a bookmark taken after the erase.

The marker is a control-object operation, not just a flag. Workers built before it already refuse every permit and restore while an operation is set, so a mixed deploy fails closed on it. Limits:

  • During a gradual deploy, a control object still on the previous Worker cannot record the marker. Purge then releases its fence and fails before it erases anything; retry it once the deploy finishes.
  • Do not purge while a tenant Worker rollout is in progress. An edge Worker on the previous build reaching a tenant object on the previous build runs the old, unmarked purge.
  • Rolling the tenant Worker back to a build from before the purge marker un-protects interrupted purges. The marker still refuses permits there, but that build's POST /tenants/:id/cancel-restore treats it as an uncertain restore and can clear it.

On this page