Appearance
0011. Dedicated tenants: a tenant's data in its own database
Status: proposed (awaiting the security reviewer and the architecture owner). Applies to crates/kernel (placements, database set, moves), crates/authz (the audit sink), crates/doors, crates/api-mcp, crates/events, crates/jobs, crates/orbit-bin (configuration, orbit migrate, orbit tenant ...) and deploy/.
Context
Every tenant lives in one Postgres database today. Some customers need their data in a database of their own (data residency, a contract, noisy neighbours, a separate backup and restore cycle), and single-tenant installs want an instance that serves one tenant and nothing else. Hosting stays out of scope: Orbit only needs to be told which databases exist; how they are created and where they run is the operator's business.
Decision
Placement model
Named databases. The database every install has today is named
sharedand keeps its environment variables (ORBIT_DATABASE_URL,ORBIT_WORKER_DATABASE_URL,ORBIT_DOORS_DATABASE_URL,ORBIT_MIGRATION_DATABASE_URL). Others are listed in a TOML document, given inline inORBIT_DATABASESor as a file inORBIT_DATABASES_FILE:toml[databases.eu1] runtime = "postgres://orbit_app:...@eu1/orbit" # web, worker worker = "postgres://orbit_worker_login:...@eu1/orbit" # worker, scheduler doors = "postgres://orbit_doors_login:...@eu1/orbit" # web owner = "postgres://orbit_migrator:...@eu1/orbit" # orbit migrate, orbit tenant max_connections = 10 # runtime pool size (optional)Names are lowercase (
^[a-z][a-z0-9_-]{0,62}$);sharedis reserved. Each process takes only the URLs its roles may hold, exactly as with the environment (ADR 0004): every serving role refuses a document with anownerentry,webrefusesworkerentries,worker/schedulerrefusedoorsentries. No URL or password is ever logged or shown in an error: the configuration'sDebugprints names only, and errors name the database and the role, never the URL.Each database knows its name.
orbit migraterecords the name inkernel.database_identity(owner-written, readable throughkernel.database_name()). A process refuses a pool whose database answers to another name, so swapped URLs fail at once instead of writing a tenant into the wrong database. A database is migrated as one name for good.Placements.
kernel.placementsin the shared database maps a tenant to the database that holds its data and the state of that placement:state databasepeerwrites (no row) sharedallowed activethe tenant's database allowed movingthe source (still serving reads) the target refused moved_fromthe target (serving) the source (still holds a copy) allowed The table is owned by the owner, has no row-level security (it holds no tenant data, only names) and is readable by
orbit_runtime,orbit_workerandorbit_doors. Every database has the table (migrations are the same everywhere); only the shared one's is read.kernel.tenant_moves(shared, owner only) logs every move with its per-table manifest.
Routing
- Every request, command, query, job, event delivery and audit write resolves the tenant's placement (
orbit_kernel::Databases) and uses that database's pools. A lookup that fails, or names a database this process was not configured with, refuses the work; nothing ever falls back toshared. - The write gate. A writing transaction (a command, a job, an event delivery, the audit sink's own entries, the doors' role sync) opens on the tenant's database, takes the tenant's write lock in shared mode (
pg_advisory_xact_lock_sharedonorbit.tenant.write:<id>), and only then re-reads the placement: it must still name this database in a writable state. For a tenant onsharedthe re-read is in the same transaction; for a dedicated one it goes through the shared pool (never the pool the transaction holds, so no pool can wait on itself). A tenant that ismovingis refused withBusError::TenantMoving, which every door reports asCONFLICTwith the reasontenant_moving(retry shortly); jobs are retried, events stay in the outbox. Queries take no lock and read from the source while a move runs. - Pools are created lazily, on a database's first use, each bounded (
max_connections, defaultORBIT_DATABASE_MAX_CONNECTIONSor 10; worker pools 32). Each new pool is checked like the shared ones at start (no superuser, noBYPASSRLS, the right group) and must answer to its database's name. The worker role opens every configured database at start, because it serves all of them. - Workers. The worker role runs one event relay, one job worker and one scheduler per configured database, each on that database's pools. The relay skips a tenant that is not writable on its database (its events wait, in order); the job runner retries a job of a moving tenant and skips (marks done, logged) one of a tenant placed elsewhere. Scheduled entries are read at start, as today: restart the scheduler after a provisioning or a move.
- Migrations.
orbit migratemigrates every configured database (shared first), or one with--database <name>, with that database's owner URL. Each database gets the same kernel, platform and module migrations, so the per-module roles and grants (ADR 0005) and row-level security exist in every one. The superuser scripts (deploy/postgres/init) must have run in each database first; roles are cluster-wide, grants per database.
What stays shared
- Sign-in mapping.
doors.identities(sidecar user and organisation ids to Orbit actor and tenant ids), MCP token revocations and the files door's quota and redeemed tokens stay in the shared database: a token is mapped before its tenant is known, and an actor may belong to tenants in several databases. - Placements and the move log.
- Everything else of a tenant moves with it:
kernel.tenants, enablement and switches, memberships and removals, audit entries, personal-data keys, the outbox and delivery state, the tenant's queued jobs, and every module's rows. - The doors read and sync a dedicated tenant's membership in its own database through
doors.role_ofanddoors.sync_role(doors migration 0005), which refuse to run in the shared database.sync_rolecannot checkdoors.identities(they are shared), so it checks that the tenant exists in that database instead: anyone holding the doors credentials of a dedicated database can set a role for any actor id in its tenants. That is the same trust ADR 0002 already gives those credentials.
Moving a tenant
Operator commands, on the owner connections only, never in a serving process, each audited in the tenant's database (actor and door system):
orbit tenant provision ... --database <name>creates the tenant directly in that database and records its placement (active).orbit tenant move --tenant <id> --to <name>:- refuses an unfinished earlier move, the same database, an unknown one, a target that is not migrated exactly like the source (same tables and columns), and, unless the superuser applied
deploy/postgres/init/03-tenant-moves.sql, an owner that may not setsession_replication_role; - audits
kernel.tenant.movein the source; - freeze: sets the placement to
movingand waits for the tenant's write lock in exclusive mode in the source, so every writer that read the old state has finished; every later writer seesmovingand refuses; - copy: reads the source in one
REPEATABLE READsnapshot and writes the target in one transaction, table by table in foreign-key order (every table with atenant_idcolumn outsidedoors, pluskernel.tenantsand the tenant's queued jobs), in batches, withsession_replication_role = replica(triggers such as the audit log's append-only guard and payroll's locked-run guards are for the application, not for a copy of rows that already passed them). Rows the target already holds for the tenant (from an earlier attempt that died after its commit) are deleted first. Sequences behind copied columns are moved past the copied values; - verify: per table, the row count and a checksum (the sum of a 64-bit hash of each row's text in UTC and ISO styles) must be the same in the target transaction as in the source snapshot; otherwise everything rolls back;
- switch: commits the target, then sets the placement to
moved_from(database = target, peer = source) in one statement guarded by the expectedmovingrow; the manifest is kept inkernel.tenant_moves.
A run that dies anywhere before the switch leaves the source authoritative (state
moving, so still frozen); running the command again starts over,--abortunfreezes.- refuses an unfinished earlier move, the same database, an unknown one, a target that is not migrated exactly like the source (same tables and columns), and, unless the superuser applied
orbit tenant move --tenant <id> --finishpurges the source's copy: only frommoved_from, only if the target holds the tenant, and only if the source still matches the manifest (nothing wrote to the stale copy). It first marks the movefinishing, so no abort can return the tenant to a purged source; a finish that dies after that is completed by running it again. Rows are deleted in reverse order, only wheretenant_idis that tenant (and row-level security is set to it), and the count is checked to be zero; every queue row of the tenant goes too. The placement becomesactive.orbit tenant move --tenant <id> --abortreturns to the source before--finish: frommovingit deletes the target's partial copy and unfreezes; frommoved_fromit freezes the target, checks that it still matches the manifest (nothing written since the switch, audit entries included) and that the source still holds exactly the verified copy, and only then switches back and deletes the target's copy. Once the tenant has written to the target, abort is refused: move it back instead (after--finish).The three commands for one tenant take a session advisory lock on the shared database (
orbit.tenant.move:<id>) for their whole run, so they never interleave; every guarded state change must match exactly one row or the step stops.Identity columns no foreign key references (
events.outbox.seq,leave.holiday_assignments.seq) are numbered by the target, in the source's order, so a move into a database that already holds tenants never collides; they are left out of the checksum.A writer waits at most 5 s (
lock_timeout) for the tenant's write lock and then fails as if the tenant were moving, so a job that dispatches a command while a move queues for the lock cannot deadlock. Jobs are at-least-once: one still running when the snapshot is taken runs again in the target.
Sealed columns and files
Personal fields are sealed with AAD that binds the tenant, key version, table, column and row id (orbit-pii), never the database, and the tenant's wrapped data keys move with it in pii.tenant_keys under the same master key; so every sealed value opens in the target unchanged (tested). Blob storage is not moved: paths are already scoped to the tenant and module, and the store is per install, not per database.
Dedicated deployment mode
ORBIT_TENANT_ALLOWLIST (comma-separated tenant ids) makes an instance refuse every other tenant: the doors refuse the token (UNAUTHENTICATED), the bus refuses the dispatch like an unknown tenant, the relay holds its events and the job worker hands its jobs back to the queue in place, a minute later and with their attempts kept, for an instance that serves it. An allowlisted instance runs its worker and relay only on the databases that hold one of its tenants (read at startup; restart it after a move). Run at least one worker without an allowlist on any database that also holds other tenants. With a dedicated database per tenant and one instance per tenant this gives single-tenant installs that still share one sign-in service.
Backups
Each database is backed up and restored on its own (pg_dump as the superuser or the database owner, ADR 0005). Restoring one database alone is consistent for the tenants it holds, but the shared database holds their placements and identities: restore the shared database together with any database it names, or re-create the placements by hand. While a move is moved_from, the tenant's last pre-move state also sits in the source.
Failure modes
| What fails | What happens |
|---|---|
| Placement lookup (shared database down) | Every request for every tenant fails (INTERNAL); nothing falls back |
| A dedicated database is down | Its tenants fail; other tenants are unaffected; its relay and jobs log and retry |
| Crash during freeze or copy | Target transaction rolls back; source stays authoritative and frozen until the move is run again or aborted |
| Crash after the target commit, before the switch | Re-running deletes the target copy and copies again |
Crash during --finish | The move is finishing: --abort is refused, --finish again completes it |
| Two move commands for one tenant at once | The second is refused (per-tenant move lock) |
| A source job of a switched tenant | Waits (queued again after 10 minutes, without using up a retry) until the move finishes or aborts; --finish deletes it |
| A writer started before the freeze | The freeze waits for it; its write is in the snapshot |
| A writer of the source after the switch (a stale process) | It re-reads the placement after the lock and refuses; --finish refuses if the source changed anyway |
| Verification mismatch | Nothing is committed in the target; the error names the table |
| Swapped database URLs | The pool's database answers to another name and is refused |
Consequences
- Every write costs one placement lookup, one advisory lock and one re-read; a read one lookup. The shared database is in the path of every request for every tenant.
- The copy is generic (catalog driven), so a new module's tables move without code, as long as they carry
tenant_idand the database's migrations are the same everywhere. A table that keeps tenant data without atenant_idcolumn is not moved: the module must not do that. - A tenant's events emitted while moving are not lost: they stay in the source outbox, are copied, and are delivered from the target after the switch. Cron ticks that fall in a move window are skipped.
03-tenant-moves.sqllets the owner setsession_replication_role, which skips triggers and foreign-key checks for its own sessions; it could already drop the triggers it owns, so this gives it nothing new.