Quickback Docs
Database per Tenant

Tenant Code and the Outbox

Outbox delivery and receipts, vars, edge-only modules, and where helpers run in a tenant Worker.

Code that runs inside a tenant Durable Object has no D1, no Better Auth and no auth secrets. Side effects leave through the outbox, and the edge delivers them. This page covers the outbox, the vars tenant code can read, and which modules run where. Start at Database per Tenant for the model.

Outbox delivery

Everything a tenant object hands the edge goes through its outbox, a table in the object's SQLite written in the same transaction as the writes that caused it:

  • realtime frames, changes.broadcast frames included;
  • audit_events rows;
  • lookup-index changes;
  • jobs for other objects;
  • platform queue messages;
  • scope revocations (revocationCheck: 'kv').

The edge delivers each entry at least once, even if the request's waitUntil is cut off.

  • Claimed, never shared. An entry is claimed before anything applies it: the object reads it and leases it to that claimer for 30 seconds in one synchronous turn. Two drains, two responses, or a response and a sweep never hold the same entry, so a frame is not broadcast twice.

  • In the response. A handle() response carries what it claimed: at most 32 entries, or 32 KiB of them, in the x-quickback-tenant-outbox-claim header, which the edge strips. The edge does not call the object again to fetch them. Entries over those caps stay claimable. The response says how many remain, and the edge claims them with claimOutbox.

  • Realtime first. The edge publishes the claimed realtime frames before the response leaves it, in seq order within a claim, one Broadcaster call at a time. No D1 read or write happens before them. The registry report and the D1 bookkeeping run beside the frames, never in front of them.

  • Revocations beside realtime. revoke entries are stamped into the edge's revocation KV as soon as a claim arrives, beside the realtime frames and never behind the D1 bookkeeping or the restore fence. Like the frames, the write starts before the response leaves the edge, and for a kind the tenant admits (a tenant-backed scope kind) the response does not wait for it. Every lane that admits such a claim (the namespace gate, edge actions, tickets, refresh and authorize) re-proves it against the tenant's own rows, which the same write changed, so the removed subject is refused on its very next request, whatever KV says. A revocation of any other kind (a manual revokeScopeTokens on a platform kind, whose claims are proven against the platform database) has no such check, so a response carrying one returns once the KV is written (waiting at most 2 seconds). That makes the revocation visible at once in the location that wrote it; elsewhere it arrives within KV's propagation time (up to about a minute). Each (subject, kind, instance) is written once per claim. A KV failure or a missing KV binding retries the entry; a revocation is never dropped. An entry whose request ended before it was written is claimed again by the next response or drain for that object once its 30-second lease lapses.

  • Ordered lane. Lookup and registry entries go to D1 in one batch, guarded by tenant_registry.outbox_seq and the restore fence (outbox_generation, restore_session), which the batch reads back. Only one claim holding them is in flight at a time, and a later one is never claimed before an earlier one, so the index sees them in order. Audit rows, jobs and queue messages are applied only when that fence holds; otherwise they are released for the reconciling drain.

  • Settled, with a receipt. The edge reports each entry back as one of:

    • delivered: the row is deleted.
    • retry: the row is kept and released with backoff (1 s doubling to 60 s). A realtime frame is retried three times, then recorded failed.
    • failed: the row is dead-lettered (__qb_outbox_dead, counted in tenant_registry.outbox_dead_letters), or dropped for realtime.

    Settlements ride on the edge's next request to that object from the same isolate. Only if a settlement is still waiting a second later does one settleOutbox call carry everything pending, in calls of at most 64. Failures, fence releases, and a claim that holds later lookup or registry rows back settle at once. Any other claim holding lookup or registry rows waits only 50 ms for a request to carry it. Until it settles, the lane is blocked, and an isolate that dies inside that window leaves the lane blocked until the lease expires and the next response or sweep claims the rows. A settlement that never arrives changes nothing: its entries are claimed again after the lease, so delivery stays at least once. That covers an isolate that died, an object that refused the settlement, or a request answered 503 TENANT_RPC_VERSION_MISMATCH before the settlement it carried was read.

  • First request. On an object's first request the report write (which registers it in tenant_registry) finishes before the claim's lookups, audit rows, jobs and queue sends are applied. Realtime does not wait for it.

  • Oversized rows. A row too large for the inline header is claimed by claimOutbox, which always hands over the oldest claimable row, whatever its size.

  • Operator drains. sync and backup drain an active object normally. For an archived object (and during purge, restore and unarchive) they also take entries another claim holds, and a failed realtime replay is not retried. An archived object serves no requests, so nothing else would deliver them.

  • Chained jobs. A job delivered to another object of the organization drains that object's outbox too (up to 4 levels deep), after the claim that carried the job is settled.

  • When a claimer dies. Its entries stay leased until the lease expires, then the next response or sweep claims them again. A realtime frame keeps the publishId written with the row, so the Broadcaster drops a repeat it remembers, and the frame id (evt_<publishId>) lets clients drop the rest. Other kinds were already idempotent: audit rows by id, jobs by run id, queue messages by dedupeKey.

  • Order. Realtime frames are ordered within one claim. Across concurrent requests they are not, as before. Realtime no longer waits for the jobs and queue sends of the same claim.

Delivery receipts

Each settled entry leaves a row in the object's __qb_outbox_receipts table:

  • generation and seq;
  • kind;
  • method: the realtime method or event, or the job or queue message type;
  • target: the Broadcaster shard, job target, queue binding, audit row id or lookup name;
  • ref;
  • createdAt and sentAt (ms);
  • attempts;
  • outcome (delivered, retrying or failed) and reason;
  • detail: { publishId, matched, duplicate } for realtime, where matched is the number of sockets the Broadcaster sent to; { dedupeKey } for queue messages; { runId } for jobs.

A receipt moves to delivered and stays there. Receipts are written in the same object turn as the settlement, so they cost no extra request.

  • Retention. Receipts older than tenancy.outbox.receipts.retainDays (default 7), and the oldest beyond maxRows (default 50 000), are pruned on the object's alarm, on the first settlement after each wake, and after every 256 settled entries.
  • Backups and restore. Receipts are not tenant data. Dumps skip them, and a dump restore keeps them, because restoring data does not undo what was already sent. A point-in-time restore rewinds the whole object, so it rewinds receipts and outbox rows (with their leases) to the bookmark as well. The reconciling sync then moves to a new outbox generation, drops the rewound non-audit rows and releases every lease. Settlements still in flight for the old generation write their receipts but touch no row. Purge erases receipts with the object.
  • Reading them. GET <api>/tenants/:id/outbox-receipts?since=<ms or ISO>&limit=<1-1000>&outcome=delivered|retrying|failed (sysadmin, oldest first). It returns { receipts, next }; pass next as since for the next page. In code, call listTenantOutboxReceipts(env, name, { since, limit, outcome }) from src/lib/tenants.ts.
  • Push and email. These already keep a per-send row in your own tenant table (for example comms_log). Pass that row's id as ref when enqueueing instead of duplicating it.

Vars in tenant code

The tenant Worker has no bindings of the edge's, vars included, so tenant code that reads env.<NAME> fails the build (TENANCY_ENV_UNAVAILABLE). List the plain vars it needs in tenancy.vars:

tenancy: {
  isolation: "durable-object",
  vars: ["ATTENDEE_APP_URL"],
},
environments: {
  dev: { /* … */ worker: { vars: { ATTENDEE_APP_URL: "https://app-dev.example.com" }, /* … */ } },
},

Each target's tenant Worker gets the value its own edge has ([env.<name>.vars], or the top-level [vars] without environments), so tenant code reads env.ATTENDEE_APP_URL like edge code does; a target that does not set it gets none. Only plain vars qualify: a declared secret (bindings.secrets, a target's requiredSecrets, a secrets.required name of the edge) or a name that reads like one (*SECRET*, *TOKEN*, *PASSWORD*, *_PASS/_PW/_PWD, *PRIVATE*, *CREDENTIAL*, *APIKEY*, *SALT*, *_SIGNING*, *_HMAC*, *PEPPER*, *BASIC_AUTH*, *_DSN, database / Redis / Mongo *_URL* and *_URI*, *CONNECTION_STRING*, *_PEM, and *_KEY(S) / *_KEK(S) other than *_PUBLIC_KEY(S), *_SITE_KEY(S) and *_PUBLISHABLE_KEY(S)) fails the build (TENANCY_VARS_SECRET), as does a name no target defines as a string var (TENANCY_VARS_UNDECLARED). Every other env.* read in tenant code still fails.

Edge-only modules in tenant code

lib/realtime (needs the Broadcaster), lib/security-audit (needs the audit database) and lib/auth (Better Auth) do not run in the tenant Worker. Loading one there would drop its side effect silently, so the compiler guarantees: (When a tenant table has an encrypted column, lib/encryption and lib/secrets join this list: they are re-pointed at the tenant key runtime and refused where that fails.)

  • Rewritten. In tenant feature files and tenant queue handlers, a value import of lib/realtime or lib/security-audit is pointed at the tenant version, which records the event in the object's outbox. This covers import/export … from in either quote style, import "…", and import("…")/require("…") with a literal path (quotes or a backtick with no ${}). The path is resolved against the importing file, so only paths that land on the project's lib/ change. import { createAuth } from "…/lib/auth", optionally aliased and with type names alongside, becomes a stand-in that throws: read the caller from ctx instead.
  • Refused. The build then walks every module the tenant Worker loads from src/tenant/index.ts (again after provider build hooks, so a file a hook adds or rewrites is checked too) and fails (TENANCY_EDGE_IMPORT_IN_TENANT, with the import chain) on any value reference to one of those modules that remains: a shared quickback/lib helper or a platform feature that imports ./realtime, any other import from lib/auth, or a string that resolves to one of them (a relative path, or one starting @/, ~/ or src/ — so "src/lib/auth" itself is refused). It also refuses every import() or require() whose argument is not a plain string literal (+, a template with ${}, a variable, .join()): the compiler cannot check it, and the bundler includes every file such a pattern could match. require used as a value (const r = require) and a relative path that leaves the generated src/ are refused for the same reason (the generated import of the tenant migrations bundle is the one exception). .js, .mjs and .cjs helpers are walked like .ts files. Shared modules are not rewritten because the edge Worker uses them too: import lib/realtime from the tenant feature itself, or keep the helper free of it.
  • Allowed. import type, type specifiers, typeof import("…"), comments and ordinary strings.

Helpers run where their caller runs

A helper a tenant action, tenant job or JS trigger handler imports runs inside the tenant object too. After all files are generated, the compiler walks each of them through its runtime imports, resolving relative imports and tsconfig.json paths aliases the way the edge-bundle walk does. Every authored module it reaches, such as a feature lib/ file, another feature's file or a quickback/lib helper, gets the checks a tenant action gets:

  • edge-only ctx members and env bindings (TENANCY_CTX_UNAVAILABLE, TENANCY_ENV_UNAVAILABLE);
  • async transaction() callbacks (TENANCY_ASYNC_TRANSACTION);
  • tables of another object (TENANCY_CROSS_PARTITION);
  • inserts that choose the id of a scope instance or proving table (TENANCY_ADMISSION_ID_STRATEGY).

A tenant job's own body (its top-level constants and execute) gets the same checks. The checks are per module, not per function: a helper file is scanned whole once anything imports it, including exports the caller never uses.

The error names the helper and the entry point that reached it. Compiler- generated modules are not expanded, and package imports are allowed. A relative or alias import that names no file in the build, or a computed import() / require(), fails with TENANCY_HELPER_UNRESOLVED: the compiler can't check code it can't find. A helper nothing in the tenant Worker imports is not checked.

JS handler: triggers on tenant tables run in the object as well. Each handler's source gets the same checks as an action body, and its imports are walked like a helper's. A handler receives the env a tenant action gets (a copy of the tenant Worker's bindings without the backup bucket, which holds every organization's dumps; tenancy.backup.bucket may not double as any app, provider or queue binding), so whatever it passes env to records into the object's outbox in the same way: createRealtime(env) broadcasts, tenantRuntime(env).enqueue(…) queue messages and the tenant revokeScopeTokens(env, …). The tenant createRealtime logs tenant.realtime.no_outbox (an error) when it is given an env without the outbox, instead of dropping the call silently. A handler whose source can't be extracted as one arrow function or function expression fails with TENANCY_TRIGGER_UNVERIFIABLE.

On this page