Skip to content
pleach
Operate

Multi-tenant deployments

Operate a multi-tenant `@pleach/core` deployment — RLS in storage, `tenantId` in the fingerprint, per-tenant audit rollups, deployment checklist. The how-to guide.

The runtime carries tenantId through the fingerprint key, the audit row and the storage schema. Billing rollups over the audit ledger are one query. Host-applied tenant-isolation RLS enforces isolation only once the host arms the tenant context (a server-set database setting or a signed JWT claim; see Defining the resolver).

This page is the operations guide and a checklist for standing up a customer-facing deployment. For the runtime.tenant accessors, see runtime.tenant facet. For the SaaS use-case shape, see Multi-tenant SaaS agent.

tenantId vs organizationId

FieldLayerWhat it does
tenantIdSubstratePartition key the event log, RLS policies, audit row, fingerprint, and OTEL attribute all read. The runtime's structural isolation primitive.
subTenantIdSubstrateOptional second scope for per-team / per-workspace attribution under the same tenant. Stamped on every event log row; NULL when omitted.
organizationIdApplicationYour application-layer org id (Clerk org, Supabase row id). Stays on the runtime for product-level queries; doesn't drive substrate isolation.

tenantId is opaque to the substrate. It partitions whichever axis you bill or attribute on: end customers in a SaaS, or your own teams and cost centers inside one Anthropic Workspace or OpenAI Project. See Migrating from Anthropic Enterprise and Migrating from OpenAI Enterprise.

tenantId defaults to "default" when omitted, so single-tenant deploys, local dev and tests need no wiring. Production multi-tenant deploys must pass a concrete value. An empty string is rejected at construction with TenantIdEmptyError, so an unset env var interpolated as "" throws at init.

new SessionRuntime({ tenantId: "" });
// → throws TenantIdEmptyError

Four places tenancy lives

Get all four right, and arm the tenant context on the database connection, and the RLS policies enforce isolation instead of application code.

ScopeFieldLives in
Cache / deduptenantIdFingerprint key — one tenant never sees another's cached call.
Event logTenant id and sub-tenant idStamped by EventLogWriter on every event-log row at write.
Storage RLSTenant idStamped on every row. The bundle ships the column and owner-scoped policies, not the tenant predicate; see Storage scoping.
Audit + telemetrypayload.tenantId, OTEL pleach.tenant_idPer-tenant ledger queries; cost rollups by tenant; OTEL spans carry the attribute for dashboards.

The substrate stamps all four from the single tenantId field. A leak in any of them is a real incident.

The shipped event-log policies

The schema bundle ships two more row-level policies for the event log:

  • A per-user read policy. It admits a SELECT only when the row's session belongs to the caller, so a user never reads another user's turns, even inside the same tenant.
  • A service-role bypass. The async write path runs as the service role, so the restriction is on reads.

Tenant isolation walls customers off from each other. The owner policy walls users off within a customer. Table and column names are documented with the first published release.

RLS policy templates + auditor

@pleach/compliance ships the Postgres tenant RLS fences as a schema tier, plus a CI-ready auditor (@pleach/compliance/tenant-rls) that confirms they're installed. Apply the tier after the core base tier (the CLI orders it for you):

npx @pleach/core schema --apply --with @pleach/compliance

It ships two files:

  • The first creates the tenant resolver function the fences call, only if you haven't defined one. The default reads a server-set setting and returns NULL when it's unset or empty. See Defining the resolver.
  • The second fences the event log, the call-row table, and, when they exist, the error table, the gateway cost-event table, the turn cost rollup and the stored BYOK credentials. Each fenced table gets RLS enabled and forced, a tenant fence for every role except service_role, and a policy that refuses anon. The file refuses to install over a resolver that returns a value when no tenant is set.

Both files are idempotent. Re-run the tier after adding @pleach/gateway so its tables are fenced too. The older @pleach/compliance/tenant-rls/policies.sql export now resolves to a pointer that raises an error when run.

auditRlsPolicies returns one row per expected table, so CI fails fast on an unprotected table:

import { auditRlsPolicies, TENANT_RLS_TABLES } from "@pleach/compliance/tenant-rls";

const report = await auditRlsPolicies({
  pool,
  expectedTables: TENANT_RLS_TABLES, // or the subset you have installed
});

const gaps = report.filter((r) => !r.compliant);
if (gaps.length > 0) throw new Error(`RLS gaps: ${JSON.stringify(gaps)}`);
  • AuditRlsPoliciesOptions — pool (a duck-typed query(sql, params?) client: pg, postgres.js or a Supabase service-role client), expectedTables, and an optional schema (default public).
  • RlsPolicyAuditRow — per table: table, policyName, present, references_current_tenant (a loose check kept for compatibility), and the strict fields rlsEnabled, rlsForced, tenantFence, noAnon, resolverFailsClosed, compliant and problems. Gate on compliant.
  • TENANT_RLS_TABLES — every table the fence tier covers.

The runtime.tenant facet

Read the tenant identity from the runtime, not from your own request context:

runtime.tenant.id;     // "acme"        — the partition key
runtime.tenant.subId;  // "team-7" | undefined

id and subId are properties, not methods. The facet is built once and frozen, so runtime.tenant === runtime.tenant always holds (safe in useMemo deps).

Use it in plugins, tool handlers and gateway adapters. Reading constructor config directly (config.tenantId) is deprecated, because only the facet stays aligned with event-log stamping and the OTel attribute. See facets and tenant facet.

Construction pattern

Per-request runtime, scoped to the requesting tenant.

// lib/runtime.ts
import { createClient } from "@supabase/supabase-js";
import { SessionRuntime } from "@pleach/core";
import { SupabaseAdapter } from "@pleach/core/sessions";
import { SupabaseSaver } from "@pleach/core/checkpointing";

export function buildRuntime(req: AuthedRequest) {
  // Service-role client is fine here.
  const supabase = createClient(
    process.env.SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!,
  );

  return new SessionRuntime({
    storage:        new SupabaseAdapter({ client: supabase }),
    checkpointer:   new SupabaseSaver({ client: supabase }),
    userId:         req.user.id,
    tenantId:       req.user.orgId,         // substrate partition key
    subTenantId:    req.user.workspaceId,   // optional second scope
    organizationId: req.user.orgId,         // application-layer org row
    plugins:        [compliancePlugin, gatewayPlugin],
    enabledSafetyPolicies: req.user.org.enabledPolicies,
  });
}

Pass tenantId on every runtime construction and never default it in production. organizationId stays for application-layer joins; keep the two in sync until your product model needs them to diverge.

In a Next.js route handler, read the JWT once at the top and thread the claims into the runtime:

// app/api/chat/route.ts
import { jwtVerify } from "jose";

export async function POST(req: Request) {
  const token = req.headers.get("authorization")?.replace("Bearer ", "");
  const { payload } = await jwtVerify(token!, secret);
  const runtime = new SessionRuntime({
    storage:        new SupabaseAdapter({ client: supabase }),
    checkpointer:   new SupabaseSaver({ client: supabase }),
    userId:         payload.sub as string,            // "user-7"
    organizationId: payload.org_id as string,         // "org-acme"
  });
  // ... handle the request
}

The canonical foot-gun is the mismatch: a non-empty organizationId with tenantId left at "default". The application thinks it's scoped, but the substrate pools every tenant's events into one partition. Thread the same value into both, or assert equality:

if (
  config.organizationId &&
  config.organizationId !== runtime.tenant.id
) {
  throw new Error("organizationId and tenantId must match");
}

Event log stamping at write

EventLogWriter stamps a tenant id and a sub-tenant id on every event-log row at write time. A missing id is a bug. Add a post-deploy smoke query that counts event-log rows missing either id, and expect zero.

Storage scoping

The schema bundle ships RLS policies that filter on user_id = auth.uid() for signed-in (authenticated) clients. anon and other roles match no owner policy (see Schema → RLS template). Service-role clients, the typical server-side path, bypass RLS, so the runtime enforces scope by writing rows with the correct owner, organization and tenant.

The predicates that ship scope sessions and checkpoints by owner, and the event log and call rows by owner through the session row. Each table also ships a service_role FOR ALL bypass.

Owner scoping comes with core; you add tenant scoping

The tenant id ships as a column (text, not null, defaulting to 'default') on the event log, the error table and the call-row table, and the runtime stamps it on every write. The core policies scope rows by owner only. Apply only the core bundle and you get owner isolation.

To add tenant isolation, apply the @pleach/compliance tier (npx @pleach/core schema --apply --with @pleach/compliance), with the resolver you want in place first.

Defining the resolver

The resolver is the boundary, so its inputs are the whole attack surface. The fences call pleach_current_tenant(). The default the compliance tier creates reads a server-set setting, which your server sets per transaction:

BEGIN;
SELECT set_config('pleach.tenant_id', $1, true);
-- ... queries ...
COMMIT;

Use the default only for server-owned connection pools, because any client that can run SQL on the connection can set the same value. On Supabase, define the resolver yourself before applying the tier. Read the tenant from the verified JWT, and only from a claim the user can't write (app_metadata, or a claim your auth hook issues):

CREATE FUNCTION pleach_current_tenant() RETURNS text
  LANGUAGE sql STABLE
  AS $$ SELECT NULLIF(auth.jwt() -> 'app_metadata' ->> 'tenant_id', '') $$;

The tier never overwrites a resolver you defined. Yours must return NULL when no tenant is set, or the fence file refuses to install.

The fences are restrictive, so they only narrow access: an existing owner policy keeps working, now confined to the caller's tenant. To fence a table of your own, add a restrictive policy for all commands, with the row's tenant id equal to the resolver's value in both the using and the check clause.

Do not resolve the tenant from a request header

A resolver that falls back to a header such as x-tenant-id is caller-controlled: a client that sets the header chooses the tenant its own RLS predicate evaluates against. If you need the header leg behind a gateway that routes by tenant, the gateway must strip inbound x-tenant-id on every request, so the only value Postgres sees is one your own edge set.

Avoid a COALESCE(..., 'default') tail too. It fails open, reading the 'default' tenant on an unarmed connection. The strict form above returns NULL when nothing is armed, so the predicate matches no rows.

With a hardened resolver armed, the same event-log row queried by two tenants returns one row for the matching tenant and zero for the other, independent of any application-layer org check.

For shared sessions (multi-user within a tenant), extend the default policies with a membership lookup through the session-members table, so a user reads a session they own or are a member of. Apply analogous policies on checkpoints, the event log and call rows. The call-row table additionally needs a tenant-id read filter, so ledger rows never leak across tenants regardless of membership.

Cache isolation

The fingerprint includes tenantId. Two identical calls from two tenants produce different fingerprints, hit different cache buckets, and never share a cached result. That lets you deploy a shared cache layer (Redis, an in-memory LRU, a CDN edge cache) without an isolation review per layer.

Don't add tenantId to a cache key by hand outside the fingerprint flow. The runtime already does it, and a second write site is a chance to forget.

For example, org-acme and org-globex ask the same question against search_corpus. Only tenantId differs, so the hashes differ. Whichever tenant hits second gets a fresh provider call, and its ledger row lands with cacheHit: false.

Per-tenant ledger queries

The audit ledger row carries the tenant id, and token counts sit in the row's JSON payload under tokenCost. A cost rollup is one query: group call rows by tenant and day over a window, then sum input and output tokens and count calls. Group by turn id for per-turn cost, or join to sessions for the session title.

getAggregateUsage(client, store, filter) from @pleach/core/query wraps this with typed filters. It scopes to one userId and groups by session, agent, model, tool, day or week.

OTel pleach.tenant_id attribute

Once runtime.tenant is configured, every emitted OTel span carries pleach.tenant_id automatically: provider calls, tool runs, subagent spawns and checkpoint writes. See OTel observability for the full attribute surface and collector wiring.

Per-tenant safety policies

Tenants in one deployment can have different active safety policies. Both run the same plugin set; only the active list changes.

const runtime = new SessionRuntime({
  // ...
  enabledSafetyPolicies: tenantConfig.safetyPolicies,
});

enabledSafetyPolicies participates in the fingerprint key, so enabling a policy invalidates that tenant's cache automatically.

Provider isolation per tenant

Two patterns let tenants bring their own provider credentials:

Pattern A — BYOK via runtime construction

Construct the provider with tenant-supplied credentials at runtime build:

const provider = req.user.org.byokKey
  ? new AnthropicSdkProvider({ apiKey: req.user.org.byokKey })   // tenant BYOK (Anthropic-native)
  : new AiSdkProvider({                                          // platform pool via OpenRouter
      model:    createOpenRouter({ apiKey: process.env.OPENROUTER_API_KEY! })("anthropic/claude-sonnet-4-5"),
      maxSteps: 5,
    });

const runtime = new SessionRuntime({ provider, /* ... */ });

Simplest pattern; works when one tenant uses one provider.

Pattern B — Gateway plugin

Install @pleach/gateway and route every call through a tenant-aware gateway that picks the right credentials per call:

const runtime = new SessionRuntime({
  plugins: [gatewayPlugin],
  // ... the gateway plugin reads tenantId off the runtime and
  // routes per its own config
});

Use when tenants share a provider but need different rate limits, fallback chains or observability sinks.

React: per-tenant HarnessProvider

Key provider construction on the current tenant, or a tenant switch leaks the previous tenant's runtime:

function App({ tenantId, userId }: { tenantId: string; userId: string }) {
  const runtime = useMemo(
    () =>
      new SessionRuntime({
        storage: indexedDbAdapter(`pleach-${tenantId}`),
        userId,
        organizationId: tenantId,
      }),
    [tenantId, userId],
  );

  return (
    <HarnessProvider runtime={runtime}>
      <Chat />
    </HarnessProvider>
  );
}

The useMemo keyed on [tenantId, userId] keeps the runtime across re-renders and rebuilds it on a tenant switch.

Cross-tenant analytics (admin)

For internal dashboards that span tenants, query the ledger directly with a service-role client. getAggregateUsage has no "tenantId" groupBy: it scopes to a single userId. Use raw SQL for a tenant rollup and the typed helper for one user's usage:

import { getAggregateUsage } from "@pleach/core/query";

const usage = await getAggregateUsage(adminClient, store, {
  userId:    "user-123",
  groupBy:   "model",
  dateRange: { from: "2026-06-01", to: "2026-07-01" },
});

Never expose these queries to tenant-facing code paths. The service-role client bypasses RLS, so one accidental import in a browser bundle is a tenant-isolation incident.

Checklist before going to production

  • tenantId passed on every runtime construction (and never "")
  • organizationId matches tenantId (or the divergence is intentional)
  • subTenantId wired where you need per-team / per-workspace attribution
  • Service-role keys never reach the browser bundle
  • Schema bundle applied (this gives you the tenant id column and owner-scoped RLS)
  • Tenant-isolation policy written and applied by you — the bundle does not ship one. Define a strict resolver first, then predicate on it; see Defining the resolver. Verify with: list the event-log table's policies from pg_policies and read their predicates — if nothing references your resolver, cross-tenant reads are not being refused.
  • RLS policies extended for membership where shared sessions are needed
  • enabledSafetyPolicies resolved per-tenant
  • BYOK / gateway pattern chosen and wired
  • React HarnessProvider useMemo keyed on [tenantId, userId]
  • Per-tenant cost dashboards built off getAggregateUsage and pleach.tenant_id OTEL attribute
  • Post-deploy smoke query: count event-log rows with no tenant id → 0
  • Tenant-isolation test: two tenants, identical input — verify different fingerprints, different event log rows, no cache crossover

withTenantHeader adapter

withTenantHeader wraps a fetch client (or any outbound HTTP layer) and stamps a tenant header, taken from runtime.tenant.id, onto every outbound request.

import { withTenantHeader } from "@pleach/core/tenant";

const tenantFetch = withTenantHeader(fetch, {
  header:   "x-tenant-id",
  tenantId: runtime.tenant.id,
});

Use it for hosts behind an upstream gateway that routes by tenant header. It replaces manual header threading, which is deprecated. See tenant facet.

Outbound stamping is safe; inbound trust is not

The adapter stamps requests leaving the runtime, which is fine. The hazard is a Postgres resolver that reads x-tenant-id, because it trusts whatever the caller sent. If the header reaches PostgREST, your edge must strip any inbound copy first. See Defining the resolver.

Tenant checks for your CI

@pleach/* releases are checked for tenant stamping and scrubber allowlist coverage before they ship. Installing a package adds no check to your build, so mirror them for your own code:

  • RLS on every tenant table. Call auditRlsPolicies() from @pleach/compliance/tenant-rls (documented above) in a CI step against your database.
  • The tenant id on every write you add. Write event-log rows through the writer, and fail review on any direct insert that leaves the partition column NULL.
  • Redaction for your own event types. Keep personal data out of a custom event type's payload, or redact values before you emit it.

Where to go next