Quickback Docs
Database per Tenant

Tenant Backups and Restore

Scheduled R2 dumps of every tenant Durable Object, encrypted dumps, reading backups, restore quarantine and the authorization epoch.

tenancy.backup dumps every organization's Durable Object to R2 on an alarm, alongside point-in-time recovery. This page covers dump scheduling and encryption, reading a backup from operator code, restore, and the authorization epoch that fences restored data. Start at Database per Tenant for the model.

Backups and restore

With tenancy.backup set, every tenant object backs itself up to R2 on its own alarm. A write marks the object dirty and schedules the next backup every later; an object nobody writes to runs no alarm and takes no backup. With every: 'off' no dump is ever scheduled (a running one finishes and pending ones are dropped on the next wake): point-in-time recovery (30 days) is then the routine backup, and the bucket serves only operator backups, dump restores and moving an organization between objects. A purge deletes the purged object's dumps (the receipt-fenced one it was admitted with included): no copy outlives the object except point-in-time recovery.

A backup is one NDJSON object at <objectId>/<startedAt>-<uuid>.ndjson: a header (the object, its applied migrations, its tables), one line per row ({"t": table, "r": row}, BLOBs as {"$b64": …}), and a footer with the row count and the rows per table ({"qb": "end", "rows": n, "counts": { table: n }}; every table in the header appears, empty ones as 0). A dump restore checks them before it touches anything: per-table counts that disagree with the rows (either way) or do not add up to rows refuse the dump. Dumps written before this footer gained counts have only rows. It streams in steps: each alarm reads tables in rowid order, uploads R2 multipart parts of exactly 5 MiB (only the last part is smaller), and keeps the leftover bytes and the (table, rowid) cursor in object-local storage, so the next step resumes where the last stopped. When it finishes, the edge records tenant_registry.last_backup_at / last_backup_key from the object's outbox, and dumps older than retainDays are deleted.

An active tenant’s backup is not a point-in-time snapshot: rows written while it runs may or may not be in it. For an exact copy, restore a point-in-time bookmark.

Operator routeEffect
POST /tenants/:id/backupTake a full backup now; returns { key, rows, counts, bytes, parts, startedAt, finishedAt, generation, archived }
GET /tenants/:id/backupsList the object's dumps
GET /tenants/:id/backups/counts?key=<key>One dump's footer, { key, rows, counts }, from a single bounded read of the dump's last 256 KiB (the dump is never loaded). counts is null for a dump written before footers carried it. A key of another object is refused (400 TENANT_BACKUP_READ_INVALID), a missing dump is 404 TENANT_BACKUP_NOT_FOUND. A tenant Worker older than this route answers TENANT_RPC_VERSION_MISMATCH: deploy the tenant Worker first. Also tenantBackupCounts(env, id, key) in src/lib/tenants.ts.
GET /tenants/:id/bookmarkThe object's exact current point-in-time bookmark, { bookmark, observedAt }. Record it before a risky change; restoring { "bookmark": "…" } returns to exactly this point (never restore { at: observedAt }, which is approximate). Refused for a purged object, or one whose purge is under way (its last bookmark is tenant_registry.last_purge_bookmark).
GET /tenants/:id/outbox-receiptsDelivery receipts: ?since=&limit=&outcome=
POST /tenants/:id/schedules/arm { "types"?: [...] }Re-arm the organization's tenant schedules (all, or the given job types); each runs after its debounce unless due sooner. Registered organization objects only. Returns { armed }. POST /tenants/schedules/arm-all does every registered organization (bounded concurrency) — a manual one-off after a deploy, never a cron.
POST /tenants/lookups/migrate { "limit"?: n }With a hashed lookup: convert one page of pre-hash rows across objects. Returns { rekeyed, remaining }; repeat until remaining is false.
POST /tenants/:id/rebuild-lookupsDelete the object's platform lookup rows and re-publish every current key from its rows, under the primary TENANT_LOOKUP_KEY (after a rotation). Its keys may not resolve until the drain finishes. Returns { applied }.
POST /tenants/:id/restore { "backupKey": "…" }Archived objects only. With encrypted dumps, add "allowPlaintext": true to restore a dump taken before encryption was on. Restore a dump: drop every tenant table, re-create the schema at the dump's migrations, load its rows (one transaction), then apply the migrations added since. An old dump comes forward to the current schema. Refuses a dump from another object, a truncated dump, or one taken at migrations this Worker does not know. Returns { kind: "dump", backupKey, rows, pending: true }; the object restarts and stays archived. Pending scheduled jobs are dropped (see restore quarantine).
POST /tenants/:id/restore { "bookmark": "…" } or { "at": <ms or ISO> }Archived objects only. Point-in-time recovery (30 days): onNextSessionRestoreBookmark, then the object restarts. Writes after the bookmark are discarded. Returns { kind: "pitr", bookmark, undoBookmark, pending: true }. A bookmark is exact. at is resolved with getBookmarkForTime, which Cloudflare documents as approximate: on a real deployment, writes made a few seconds before at were missing after the restore. For a precise target use GET /tenants/:id/bookmark beforehand, or the undoBookmark of an earlier restore.

An operator backup on an archived organization acquires exclusive maintenance admission before scanning. It refuses with TENANT_BUSY while older requests, jobs or alarms still hold permits, abandons an unfinished active scan, and starts a fresh one while blocking unarchive, restore and purge. Its completed receipt has archived: true and the current generation. Active and scheduled backups have archived: false and retain the incremental behavior above.

Encrypted dumps

.encrypted() and q.secret() protect the columns you mark. Everything else in a dump — amounts, names, memos, the table and column names themselves — would otherwise sit in R2 as readable NDJSON. With tenancy.backup.encrypt every dump is sealed to its tenant:

  • it cannot be read without the edge Worker's ENCRYPTION_KEK. The bucket, the tenant Worker and the tenant object's own storage are not enough;
  • it cannot be restored into another tenant, or into another partition object of the same organization;
  • a changed, truncated, reordered or forged dump is refused before a row is touched.
tenancy: {
  isolation: "durable-object",
  backup: { bucket: "TENANT_BACKUPS", every: "1d", retainDays: 30, encrypt: true },
},
encryptResult
unsettrue when the project has an .encrypted() or q.secret() column (it already runs ENCRYPTION_KEK and org_data_keys); otherwise dumps stay unencrypted
truesealed dumps. Without an .encrypted() or q.secret() column the build fails (TENANCY_BACKUP_ENCRYPT): there are no per-organization keys to seal with. One q.secret() column is enough
falseunencrypted dumps, with a build warning when the project has the keys to seal them

Key hierarchy. Nothing new to configure or store:

ENCRYPTION_KEK                      edge Worker secret
  └─ organization DEK v<n>          org_data_keys, wrapped by the KEK
       └─ HKDF-SHA-256(DEK, "qbdump:1:<org>:<n>")
            ├─ dump private key     X25519; derived on the edge when needed, never stored
            │    └─ dump public key handed to the tenant object
            └─ dump sender key      handed to the tenant object

The edge hands each tenant object its dump recipient — the public key and the sender key — with every forwarded request, and before an operator backup. The object keeps it in its own storage, so an alarm-driven dump needs no edge round trip. The recipient writes dumps and opens none: opening one takes the private key, which only the edge can derive.

One dump. A random 256-bit content key encrypts the dump with AES-256-GCM. The content key is wrapped to the recipient: an ephemeral X25519 exchange with the dump public key, run through HKDF-SHA-256 with the sender key as salt. The sender key is what authenticates the writer: someone who learns the public key and can write to the bucket still cannot produce a dump the edge will unwrap.

What is bound (as additional authenticated data): the tenant object, the object's outbox generation when the dump started, the dump id (its R2 key) and the key version bind the wrapped content key. Every frame then binds the hash of the whole header, its own position, and whether it is the last frame.

Layout. The key name is unchanged (<objectId>/<startedAt>-<uuid>.ndjson), and so are the purge fence, the backup receipt (key, generation, bytes) and readTenantBackup. bytes is the stored size.

BytesContent
[0, 4096)header: JSON padded with spaces, newline terminated. Plaintext, authenticated
[4096, 5 MiB)frame 0
[k × 5 MiB, (k+1) × 5 MiB)frame k: one R2 part

A frame is a 12-byte random nonce, then the ciphertext and its 16-byte tag. The plaintext inside is the NDJSON dump described above, unchanged.

What the bucket shows. R2 key names and the header are not encrypted:

VisibleWhere
the organization id, and the partition key for a partition objectkey name, header, custom metadata
when the dump started, to the millisecondkey name, header, custom metadata
a random id per dumpkey name
the object's outbox generation (a random id that changes on restore)header
the organization key version, the dump's ephemeral public key and wrapped content keyheader
the dump's size, and how often an organization is written to (one dump per every while it changes)object size and listing

Nothing else: no table name, column name, migration tag, row count or value. Whether a dump is encrypted shows in its first bytes and in the enc: v1 custom metadata, not in its name.

Restore, counts and reads. Use the same helpers and routes. The edge reads the dump's header through the tenant Worker, unwraps the content key, and hands that one key to the object, which authenticates every frame before it drops a table. tenantBackupCounts opens only the last frame (at most one part, 5 MiB, instead of the 256 KiB suffix read of an unencrypted dump). readTenantBackup receives ciphertext from the object and opens it on the edge; data is the NDJSON as before.

An unencrypted dump is refused (TENANT_DUMP_PLAINTEXT_REFUSED): with nothing sealing it, nothing shows who wrote it. To restore a dump taken before encryption was turned on, pass allowPlaintext: true (restoreTenant(env, id, { backupKey, allowPlaintext: true }), or the same field in the route body). encrypt: false builds no dump crypto at all, so a project that turns it off cannot restore its encrypted dumps until it turns it back on.

Key rotation.

EventDumps already writtenNew dumps
rotateOrgDataKeystill open. A dump records its key version, and retired versions stay in org_data_keysseal to the new version once a forwarded request (or an operator backup) carries it. Until then they seal to the previous version, which still opens
rewrapOrgDataKeys, then dropping the old ENCRYPTION_KEKstill open. No DEK changed, so no dump key changedunchanged
deleting the organization's org_data_keys row (crypto-shredding)unreadable, permanently, with its encrypted columns. That is the point of the deleteseal to the fresh key the next write creates
losing every ENCRYPTION_KEK that wraps the DEKunreadable, permanentlynone can be written
a features-D1 restore to a bookmark before a rotationdumps sealed to the version the restore removed are unreadable (TENANT_DUMP_KEY_VERSION_UNKNOWN). So are column values written under itthe object follows the edge back to the version that exists again. Take a fresh backup of each tenant after reopening

There is no separate dump key to back up or rotate. Keeping ENCRYPTION_KEK and the features database's org_data_keys recoverable is what keeps dumps recoverable.

Fail closed. An object that has not been handed its recipient yet (no request has reached it since the feature was deployed) takes no dump: the alarm logs tenant.backup.skipped and tries again after every; an operator backup hands the recipient over first. It never writes an unencrypted dump. While a dump is running, its one-time content key sits in the object's own storage beside the rows being copied, and is deleted with the run.

Errors. Each refusal has its own code, in the thrown error, the operator route's response and one JSON log line (tenant.dump.key_rejected, tenant.dump.open_failed or tenant.restore.rejected, with the tenant object and the dump key). No message or log line carries key material or row data.

CodeCause
TENANT_DUMP_TENANT_MISMATCHthe dump's header names another tenant object
TENANT_DUMP_ID_MISMATCHthe dump was written under another key (renamed or copied)
TENANT_DUMP_KEY_VERSION_UNKNOWNthe organization holds no DEK of the version the dump was sealed to
TENANT_DUMP_KEY_UNWRAP_FAILEDthe content key does not open with this organization's key for that tenant, generation and dump: another tenant's dump, a changed header, or a writer without the sender key
TENANT_DUMP_AUTH_FAILEDa frame failed its auth tag: a changed byte, a missing, moved or foreign frame, or a truncated dump
TENANT_DUMP_TRUNCATEDshorter than a header, or a header with no frames
TENANT_DUMP_HEADER_INVALID / TENANT_DUMP_UNSUPPORTEDnot a dump header, or a format version this Worker does not read
TENANT_DUMP_KEY_REQUIREDan encrypted dump reached the object without its content key (call the edge helper)
TENANT_DUMP_PLAINTEXT_REFUSEDan unencrypted dump, without allowPlaintext: true
TENANT_DUMP_RECIPIENT_MISSINGan operator backup of an object that has no recipient and could not be handed one

Deploy the tenant Worker before the edge Worker, as for any tenant RPC change. An edge that finds a tenant Worker without encrypted dumps stops with TENANT_RPC_VERSION_MISMATCH before it takes a backup.

Reading a completed backup in operator application code

readTenantBackup from src/lib/tenants.ts transports the latest completed, quiescent backup through the tenant Worker. The backup bucket remains bound only to that Worker. No download HTTP route, arbitrary SQL, archived tenant-job admission or edge bucket access is added. Call this helper only after your application verifies the operator and target organization; it does not perform HTTP authentication itself, like the other operator helpers.

After archiveTenant and backupTenant, pass only the receipt's key, generation and bytes to readTenantBackup(env, organizationId, { key, generation, bytes }). The result is { key, generation, bytes, etag, data }, with data an ArrayBuffer of the original encoded NDJSON. Use new TextDecoder().decode(data) only after the helper succeeds, then validate and project the application data you intend to retain. Keep raw dumps private; a dump contains all tenant tables.

The hard whole-buffer limit is 8 MiB of encoded bytes. Optional maxBytes may lower that limit, never raise it. A larger dump fails with TENANT_BACKUP_READ_TOO_LARGE; it is not truncated. Do not purge a tenant when retention fails. Larger exports need a future bounded streaming protocol.

The helper requires the exact latest completed receipt, an archived organization, a matching current generation, and no writes since that backup. Old receipts, active backups, foreign keys, partition/control objects, changed byte lengths and malformed replies refuse. Legacy receipts without the new fields require a fresh archived backup. The tenant checks R2 metadata and the actual stream length, then returns binary bytes rather than base64 or a result-job JSON payload. Exclusive maintenance remains held through the body read: pending restore or purge refuses the read, and restore, purge or unarchive cannot begin during it. The edge checks the registry before and after the RPC; application workflows must still recheck their maintenance fingerprint before a later destructive operation.

This helper needs tenant RPC version 7. Deploy the tenant Worker before the edge Worker; an older tenant Worker cannot supply the new operation. A failed or ambiguous maintenance release keeps the existing recovery fence, requiring operator reconciliation rather than silently reopening admission.

The same operations are backupTenant, listTenantBackups and restoreTenant in src/lib/tenants.ts. Dump restore has an 8 MiB encoded NDJSON limit (413 TENANT_RESTORE_TOO_LARGE), checked before reading the body or changing any table. Larger dumps need PITR until streaming restore is implemented. Restore cancels any in-progress multipart upload, clears its cursor and carry, and schedules a fresh backup. Both restore kinds and migration retry acquire exclusive admission before reading R2 or changing data. They refuse with TENANT_BUSY while previously admitted HTTP handlers, deferred waitUntil work (including nonblocking after-commit hooks and effects.enqueue callbacks), jobs, alarms or backup work remain in flight. HTTP responses return before nonblocking effects settle; their admission permits remain held through nested deferred work and release after success or rejection. Retry after that work finishes. New work is quarantined while the operation runs; a known success or failure releases its matching gate. An ambiguous operation or failed release retains quarantine for explicit operator recovery. Backup and restore operations are serialized.

Use effects.enqueue, nonblocking afterCommit hooks or c.executionCtx.waitUntil(...) for deferred tenant work. Authored access to the raw waitUntil export of cloudflare:workers is refused with TENANCY_UNTRACKED_BACKGROUND in tenant modules and their statically named relative authored dependencies, including aliases and helper re-exports that bypass the request's tracker. This includes a dynamic import's ordinary fulfillment callback reading the namespace through implicit arguments[0], even when its declared parameter is unused or the access is in a nested arrow. Uninspectable argument or namespace escapes fail closed. Unrelated Cloudflare exports remain available when their access is explicit. External packages, path aliases and computed module names are outside this source-level check. Keep unrelated Cloudflare imports; use the tracked context instead of importing waitUntil. Await database work that must finish before the response. Arbitrary promises or timers launched without await or a tracked scheduler are outside this lifetime contract; do not retain a tenant database handle in them. A failed upload keeps its checkpoint and retries; writes during a backup schedule another backup after it completes.

Restore quarantine

Every restore, dump or point-in-time, follows the same steps:

  1. POST /tenants/:id/archive. A restore of an object that is not archived is refused (tenancy: archive before restore), as is a restore while an earlier one is pending (TENANT_RESTORE_PENDING).
  2. POST /tenants/:id/restore. It returns pending: true; the object restarts.
  3. POST /tenants/:id/sync reconciles the restore under a new outbox generation. The object is still archived.
  4. Inspect it, then POST /tenants/:id/unarchive. Nothing serves a restored object before this explicit step. Unarchive refuses (TENANT_RESTORE_PENDING) until step 3 has reconciled the restore, or while an unconfirmed restore or stranded maintenance fence is open — clear those with POST /tenants/:id/cancel-restore.

A dump carries no schedule: dump restore drops the object's pending scheduled jobs (scheduleTenantJob), its job-run dedupe records and its queued non-audit outbox entries in the same transaction as the load, so nothing scheduled against the replaced rows fires against the restored ones. Reschedule recurring work after unarchive. PITR instead rewinds the schedule to the bookmark with the rest of the database.

Restore first acquires an external admission gate: a small control object in the existing tenant namespace, under a reserved __qb_control__: name. The gate is outside the database being rewound. It refuses restore while requests or outbound jobs are in flight, then quarantines handlers, jobs and alarms until reconciliation. Control objects use the class's implicit ctx.exports namespace; no extra namespace or binding is provisioned. A tenant object does not ask its control object per request: it keeps the permit it was last granted as a lease and admits its own requests, jobs and alarms under it with no control RPC. The lease is an ordinary permit, so the gate still refuses restore while it is held. Restore, purge, migration retry and archived backups first revoke it: refused (TENANT_BUSY) while any work admitted under it (deferred callbacks included) is still running; otherwise the lease is released, and none is granted again until the fence is released. A lease admits work for at most 30 seconds; the next admission after that re-validates with the control object. An idle lease stays registered until it is revoked or replaced, so a control object reports TENANT_BUSY to any caller that skips the object's own revocation. A restart or eviction leaves its permit behind; the object's next admission, or the next restore's prune, removes it. Cross-object work (an outbox job from another object) still takes and releases the source object's permit per delivery.

Restore fences the old outbox generation and removes platform lookup rows. After a confirmed restore restarts the object, call POST /tenants/:id/sync to rebuild lookups under the new generation. Reconciliation discards the queued outbox entries other than audit rows and scope revocations, because they describe writes the restore replaced (a dump restore already dropped them with the load). A queued revocation is kept: rolling data back never un-revokes a claim. A dump restore is confirmed once its load commits; a dump that is refused (too large, truncated, another object's) changes nothing and releases quarantine like a rejected PITR prepare. TENANT_RESTORE_PENDING means the operation is unconfirmed or the old session has not restarted. A rejected prepare releases quarantine and restores its old lookup index. An unrelated restart never turns an unconfirmed prepare into a successful restore.

For an uncertain operation, inspect the current state and explicitly call POST /tenants/:id/cancel-restore with { "confirm": "<objectId>" }. If the old session is still running, this first restarts it and returns pending; repeat the explicit recovery call after restart. Recovery keeps the current database and queued work, rebuilds lookups, and stays archived. A failed pre-invocation rollback resumes its recorded cleanup instead. Recovery owns one persisted mode so delayed cleanup cannot race abandonment. Once abandonment is claimed a restore can no longer be armed, but one that took effect anyway (a PITR bookmark is irreversible once scheduled; a dump load committed) is recorded in the control object: abandonment then discards queued non-audit outbox entries like a confirmed restore and returns applied ({ bookmark, undoBookmark } or { backupKey, rows }; null when nothing applied). A restore whose arming RPC was lost before it reached the control object cannot be recorded; such an abandonment keeps queued work. A completed restore also stays archived; inspect it before POST /tenants/:id/unarchive. Never automatically retry the restore write.

Authorization epoch

The control object also holds an authorization epoch, a counter that no restore can rewind. It is per object name: an organization object and each of its partition objects have their own. Every restore, dump or PITR, advances it when the restore begins, and keeps it across success, rollback and abandonment. Read it with tenantAuthorizationEpoch(env, objectId) in src/lib/tenants.ts (or the object's authorizationEpoch RPC), or with the qb.epoch command, which reads it under the restore permit.

The epoch is exposed for admission checks; nothing enforces it yet. Enforcement arrives with tenant admission (plan 032): credentials pinned to an earlier epoch will then be refused, so a restore forces re-login even when restored rows would grant the old access again. Restore does not call /oauth2/revoke.

Point-in-time recovery does not run under local wrangler dev. The staging account drill remains an open release gate: write A, note time T, write B, archive, restore to T, sync after restart, and verify A remains, B is gone, lookup entries match the restored rows, and scheduled work resumes safely. Do not treat the local reconciliation simulation as a completed PITR drill. The R2 dump/restore drill runs locally in the tenant-do output-matrix fixture.

On this page