Skip to content

Tenants & scopes ​

Substrat tenancy is two levels, tree-shaped: the tenant is the business that pays you (a property-management firm, a retail chain, a publisher); beneath it are scopes — the housing associations it manages, its branch offices, its client companies, its brands. Users belong to the tenant, to a scope, or to several scopes with different roles.

This shape recurs in essentially every vertical B2B product, and it is nearly impossible to retrofit — which is why it's kernel-owned and first-class rather than a convention.

The entities ​

ts
import { tenant, scope } from '@substrat-run/contracts';

type Tenant = {
  id: TenantId;          // branded ULID
  slug: string;          // stable, URL-safe, unique
  name: string;
  status: 'active' | 'suspended' | 'deleting' | 'reaped'; // 'reaped' = terminal, bytes gone
  deletingAt: Instant | null; // set when it entered 'deleting'; null otherwise. The reap
                              // sweep ages a tenant off this to decide the grace window.
  provisionedByTenant: TenantId | null; // the manager vertical's own tenant when it created this
                              // one through the `provision-tenant` intent; null when staff did
  createdAt: Instant;
};

type Scope = {
  id: ScopeId;           // branded ULID — globally unique, not per-tenant
  tenantId: TenantId;
  parentScopeId: ScopeId | null; // v1: always null; the column exists so deeper
                                 // trees are additive, not a migration
  slug: string;          // unique within the tenant
  kind: string;          // YOUR vocabulary: 'brf', 'branch', 'brand', 'clinic'…
  name: string;
  status: 'provisioning' | 'active' | 'suspended' | 'archiving' | 'archived' | 'reaped';
                         // 'reaped' = terminal past 'archived'; DO storage gone, no restore
  storageShape: 'A' | 'B';
  jurisdiction: 'eu' | 'us' | 'global';  // fixed at provisioning; 'global' is unconstrained
  vertical: string | null;          // which vertical's deployment executes this scope
  verticalVersionId: string | null; // the registered version it runs (null if pre-registry)
  provisionedVersionId: string | null; // the version this scope's provision hook last ran
                         // against; differing from verticalVersionId means the hook is due
                         // (a few reconcile receipts ride beside it and are left out here)
  schemaVersion: string; // COUNT of applied (module, version) pairs, as a string.
                         // '0' = provisioned, nothing applied yet. Compared against the
                         // host's registered migration total to answer "which are behind".
  // Non-null when the scope's last migration attempt FAILED. The scope fails
  // closed and serves nothing; this is what stops it rendering as healthy.
  migrationFailure: {
    version: string;        // the `module@version` that threw
    error: string;
    attempts: number;       // consecutive failures
    lastAttemptAt: Instant;
  } | null;
  forkedFrom: ScopeId | null; // fork provenance: the scope this was copied FROM (importScope),
  forkedAt: Instant | null;   // and when — both null for a normally-provisioned scope
  expiresAt: Instant | null;  // when a fork stops being retained (GC); null = no expiry
  servingRef?: string | null; // the dispatch script this scope's data DO lives in (#286)
  archivedAt: Instant | null; // when it last entered 'archived'; null if never / on unarchive
  createdAt: Instant;
};

Design decisions worth knowing:

  • kind is vertical vocabulary, not a kernel enum. The kernel never branches on it. Call your scopes whatever your domain calls them.
  • Scope IDs are globally unique, so an event or an opaque ref never needs the tenant for disambiguation — but every kernel API still requires the pair (tenantId, scopeId) and cross-checks it. A confused-deputy bug in calling code fails closed instead of resolving to another tenant's scope.
  • jurisdiction is fixed at provisioning, forever. Data residency is decided when the scope is created, not toggled later.
billing · identity · the contractTenantslug · status · one Identity DO for all its peopleHolds no operational rows of its own.stockholmkind: branchactive · eugöteborgkind: branchactive · eumalmökind: branchprovisioningNo query crosses these lines. There is no join between two scopes.every scope is· its own database — one SQLite file, or one Durable Object· one operation at a time, run to completion· kind is your vocabulary: brf, branch, brand, clinic…· jurisdiction and bound version are fixed per scope
parentScopeId is null on every scope today. The column exists so a deeper tree is an addition rather than a migration. The tenant is who you bill and who can log in. The scope is where data lives and where consistency is decided — which is why isolation is a property of the substrate here, not a WHERE clause somebody has to remember.

One scope = one database = one consistency domain ​

Each scope is an isolation domain with its own SQLite database and a strictly serialized executor: one operation at a time, run to completion. This gives module code single-writer simplicity — a read-modify-write inside an operation cannot interleave with another operation on the same scope — and it bounds the blast radius of any problem to one scope, not one customer.

Serialization is per scope, not per system: a thousand scopes run a thousand operations at once, and only two operations on the same scope ever queue. What that means for throughput, and where reads go when a scope gets busy, is Reads & scaling.

The granularity rule: the scope maps to the consistency domain, not the tenant. A tenant with 300 housing associations is 300 scope databases plus a lightweight tenant root, not one 300-times-hotter database.

Provisioning ​

ts
// A scope belongs to a tenant, so the tenant record must exist first.
host.admin.createTenant(actor, { id: tenantId, slug, name });

await host.provisionScope(actor, {
  tenantId,
  scopeId,
  storageShape: 'A',        // optional
  jurisdiction: 'global',   // optional (defaults to 'global'); immutable once set.
                            // 'eu'/'us' are gated until Regional Services is in place.
});

Both take a platform actor (the control-plane staff subject) and are audited. Provisioning is idempotent and journaled — safe to re-run, safe to drive from a reconciliation sweep — and requires an existing active tenant, so a scope can never be orphaned. The host maintains a directory (a separate database) as the authoritative inventory of tenants and scopes; it's what getScope validates addressing against, and the input to migration sweeps and ops tooling.

A scope begins in provisioning, becomes active, and can be suspended and resumed. Archiving is reversible while its storage is retained; reaping an archived scope deletes that storage and leaves a terminal reaped directory tombstone. The tenant has its own reversible deleting grace state before a terminal reap. Entitlements, custom domains, and these lifecycle actions are described in The platform layer.

Guarding a version bind ​

A scope's verticalVersionId records its bound version. A caller moving data before binding can ask the directory to update that pointer only if the binding it read still holds:

ts
await host.admin.bindScopeVersion(actor, tenantId, scopeId, incomingVersionId, {
  expectedVersionId: current.verticalVersionId,
});

null expects a scope with no bound version. Omitting expectedVersionId keeps an unconditional bind. A changed binding is refused with precondition_failed; the caller must reload the scope before retrying its move. Both adapters enforce the expectation in the atomic pointer update, so two moves from the same version cannot both win.

The platform's own data moves bind this way. A preview push or scope bind that copies a scope into another version's deployment binds with the version it copied from. Only once that bind lands does it wipe the copy it left behind. The wipe empties the scope's store in the old deployment rather than reaping it, so a later bind back to that version can copy the data in again. Where the old deployment supports it, the wipe is also conditional: it runs only if nothing has been restored into that store since the copy was read, so a rollback that lands during the cleanup keeps its data. The copy into the new deployment is conditional the same way: it is refused if that store was loaded, or took a write, since the move read it, so a move that has fallen behind never overwrites a store that is already being served. The cleanup is best effort. A move that fails between its copy and its wipe can still leave a copy behind, and nothing reconciles those yet.

Storage shapes ​

storageShape records how a scope's data is physically hosted in production:

  • Shape A — the scope's execution domain is the database (embedded SQLite as primary store). Right for small, document-centric, realtime-friendly scopes.
  • Shape B — the execution domain is a control plane (hot state: ACLs, entitlements, counters, locks) fronting a separate per-tenant database for bulk storage, read replicas, and export tooling.

The choice is per-scope, fixed at provisioning, and invisible to module code — the scope-host contract is identical either way. On the pure-SQLite adapter both shapes are one SQLite file per scope.

storageShape is not the only store a vertical can hold. Orthogonal to shape A/B, a vertical's manifest can declare stores the platform mints for it, one per tenant:

  • tenantStores — one platform-minted store per tenant. kind defaults to relational: an independent SQL database (D1 on Cloudflare, a separate .sqlite file on the pure adapter), minted by provisionTenantStore and opened through openTenantStore. kind: 'blob' is object storage (an R2 bucket), the same store a blobStores entry declares. blobStores is the older spelling and still accepted; a binding named in both is refused, because both would be bound as <BINDING>__<tenant>. A push still sends blobs in the manifest's blobStores, so an older control plane reads the same document it reads today.
  • The attachment store is never declared by hand: when any module declares attachmentTargets, substrat push declares an ATTACHMENTS blob store, the platform binds each installed tenant's bucket as ATTACHMENTS__<tenant>, and the Cloudflare host resolves the one for the tenant it is serving. The worker wires nothing. A relational store of that name is refused.

A scope store is the level below those. scopeStores declares one platform-run object per scope: a binding and a driver, with no default driver. The only driver named so far is graph. A hosted upload carries no store binding: the vertical's calls go through the platform, which addresses the object. A binding used by another store, and the name ATTACHMENTS, are refused. A driver with no registration is refused too, and none is registered yet, so a push that declares a scope store does not succeed until that registration exists. Hosted upload of the store script is a later step. See Scope stores.

The per-tenant stores follow one ownership rule, and it is the load-bearing part: the builder supplies no id. The vertical declares a need; the platform mints the database or bucket, holds the cloud credential, and attaches a binding to the serving script, re-derived from the ledger on every upload. A vertical is handed a store — it never names one, so it can never name someone else's.

Addressing is capability-shaped ​

ts
const stub = await host.getScope(principal, tenantId, scopeId);
await stub.invoke('workorder/create', input);

getScope mints a capability stub bound to one principal and one scope. From then on, tenancy is ambient: operations receive ctx.tenantId / ctx.scopeId / ctx.principal from the stub's context, and your business logic never passes IDs around. There is no parameter to get wrong, and nothing to forget to check — the scope re-validates every call against its own state anyway.