All chapters
  1. Start hereA valid token is not a permission
  2. Foundations · 1Identity and trust primitives: who is calling, and who checks
  3. Foundations · 2People and identity proofing: accounts, passwords and recovery
  4. Foundations · 3Sessions and browser security: cookies, CSRF, XSS and the BFF
  5. Foundations · 4Authenticators and MFA: passwords, passkeys and phishing resistance
  6. Foundations · 5API keys and application credentials: what a key proves
  7. Foundations · 6Tokens: bearer, JWT anatomy, validation and revocation
  8. Foundations · 7OAuth, OpenID Connect and federation: delegation and login
  9. Authorization · 8Authorization from first principles: subject, action, resource, context
  10. Authorization · 9Access control models: RBAC, ABAC, ReBAC and ownership
  11. Authorization · 10The enforcement architecture: PEP, PDP, PIP and PAP
  12. Authorization · 11Policy as code: versions, tests, engines and decision logs
  13. Authorization · 12Tenant and data isolation: one platform, many brokerages
  14. Authorization · 13Identity governance and lifecycle: joiner, mover, leaver
  15. Authorization · 14Privileged access: standing rights, just-in-time elevation and break-glass
  16. Workloads · 15TLS, PKI and certificates: proving a host, and a client
  17. Workloads · 16Workload and service identity: SPIFFE, mTLS and caller allowlists
  18. Workloads · 17API gateways and zero trust: the edge checks, the service decides
  19. Workloads · 18Event-driven identity: Kafka principals, ACLs and replay
  20. Workloads · 19Cloud IAM and secretless deployment: roles, federation and no stored keys
  21. Workloads · 20External SaaS, webhooks and trust: calls that cross company lines
  22. Workloads · 21Private controlled environments: what private networking does and does not secure
  23. AI-native · 22Authenticating to model providers: keys, gateways and cloud IAM
  24. AI-native · 23MCP identity and authorization: discovery is not permission
  25. AI-native · 24RAG and retrieval authorization: only what this caller may read
  26. AI-native · 25Agents as principals and delegates: whose authority is this?
  27. AI-native · 26Agent-to-agent trust: identity, capabilities and forwarded authority
  28. AI-native · 27Coding agents and CI: repository scopes, OIDC and no production keys
  29. Operations · 28Auditing and observability of access: decisions you can prove later
  30. Operations · 29Threat modeling and testing: the negative tests that prove access control
  31. Operations · 30Operational lifecycles: rotation, revocation and outages
  32. Reference · 31Standards, frameworks and products: what each one is, and what it is not
  33. Reference · 32Architecture decision playbooks: choosing an auth strategy
  34. ReferenceGlossary
  35. AboutAbout this site and its sources
Authorization · 12

Tenant and data isolation: one platform, many brokerages

Shared tables with a tenant column, row-level security, schemas or a database per tenant. Object checks, cross-tenant tests, administrators and service accounts, residency, and why a model must never write the tenant filter.

You will choose
Between a shared table, row-level security, a schema per tenant and a database per tenant, and say what each one really isolates.
You will prove
Isolation with cross-tenant tests that send a valid token for the wrong brokerage on every path.
You will keep
The tenant filter in deterministic code built from the verified identity, never written by a model.

A new reporting team builds a weekly summary for brokerage brk-north: how many quotes, how many referred to inspection. They connect to the quotes database with the application's role, set the tenant to brk-north as the documentation says, and run SELECT quote_id, tenant FROM quotes. The database has row-level security turned on. The report comes back with three rows: Q-5531 and Q-5532 of brk-north, and Q-6620 of brk-south.

Nobody disabled anything. Row-level security was enabled on the table and a tenant policy existed. But the application's role owned the table, and in PostgreSQL the owner of a table is not filtered by its own row policies unless someone also forces them. The real run of that setup is below; it printed exactly those three rows.

Every multi-tenant system has a wall like this between customers, and most walls have a door that someone forgot. This page is about building the wall at the right layers, knowing who can walk around each one, and proving with tests that nobody does.

What a tenant is on this site#

The broker portal serves several brokerage firms. Each firm is a tenant: one external customer organization that shares the portal and its databases with the others. A tiny example: brk-north and brk-south are two tenants; broker u-broker-n1 belongs to brk-north and must never see a quote of brk-south.

Inside the insurer, submissions belong to a business unit: commercial-west or commercial-east. That is a different boundary, internal to the insurer, and the example keeps both. The broker sees a quote, Q-5531; the insurer works the same record as submission SUB-1004; the record has a tenant (brk-north) and a unit (commercial-west), and every decision is made on the record both ids point to.

Tenant isolation is the guarantee that no principal acting for one tenant can read, change or infer data of another tenant, through any path: the API, a search index, a cache, a report, a log, a backup, or an agent's tool.

Before AI. Multi-tenant SaaS has been built on this for decades: a tenant_id column on every table and a Hibernate filter or a base repository that adds it to every query; a schema per customer in larger systems; a separate database for the customers who demand it in their contract. The new part is that a model may now write queries and filters, and it must not be the one that decides which tenant they cover.

Four ways to separate tenants#

A team designing tenant isolation for the quotes data has four common choices. They differ in what enforces the boundary, what it costs, and who can still cross it.

The simplest is a shared schema: one quotes table for every brokerage, with a tenant column, and the application adds WHERE tenant = ? to every query. The boundary is your code; one forgotten predicate leaks.

The second keeps the shared table and adds row-level security: the database filters rows by a policy, using a per-transaction setting the application fills from the verified token. A forgotten predicate now returns nothing, provided the connection's role is subject to the policy.

The third gives each tenant its own schema (a named namespace of tables) inside one database; the boundary becomes grants and the search path, and every migration runs per schema.

The fourth gives each tenant its own database. A connection reaches only one database, so no query joins across tenants; the cost is many databases to patch, back up and migrate.

Guideline (OWASP Multi-Tenant Security Cheat Sheet, read 2026-11-18) lists the same four strategies and names the boundary of each: separate databases are a "Database and credential boundary", "Strong when credentials, network access, administrative paths, and backups are isolated; higher operational cost"; separate schemas a "Namespace and database-role boundary" that needs "disciplined grants, role separation, search_path handling"; shared tables a "Policy and row boundary" that "Requires enforceable tenant ownership"; and hybrid designs "Document and test the boundary used for each data class".

Diagram: Four ways to separate brokerages · what enforces the wall, and who can still walk around it

Rows are the four isolation models, from cheapest to strongest boundary. Read across a row: what enforces the boundary, who can still cross it, and what it costs. Read down the middle column: every model has a door for principals whose credentials span tenants.

  1. Shared schema
    1. the query's tenant predicate: The application adds the tenant from the verified subject to every query.
    2. any path that forgets it: One query by id only returns another tenant's row.
    3. lowest: One schema, one migration, one backup.
  2. Shared + row-level security
    1. a database policy: The database filters every query by the tenant the application set from the verified token.
    2. owner without force, superuser, bypass role: Table owners bypass unless row security is forced; superusers and roles with the bypass attribute always bypass.
    3. low: Policies per table, a non-owner application role, transaction-local settings.
  3. Schema per tenant
    1. grants and the search path: Each tenant's tables live in its own schema; a role reaches only schemas it has privileges on.
    2. roles granted on several schemas: Schemas are not rigidly separated; a wrong search path or a broad grant crosses them.
    3. medium: Every migration runs once per tenant; half-applied migrations leave tenants on different schemas.
  4. Database per tenant
    1. credentials and connection target: A connection reaches only one database, so no query joins across tenants.
    2. holders of many tenants' credentials: Shared backups, admin tooling and jobs that hold every tenant's credentials cross the boundary.
    3. highest: Many databases to patch, back up, migrate and monitor.
ModelWhat enforces the boundaryWho can still cross itOperational costTypical trigger
Shared schema, tenant columnthe application's queryany code path that forgets the predicatelowestthe starting point for most B2B SaaS
Shared schema + row-level securitythe database policy, fed from the verified tokentable owners (unless forced), superusers, BYPASSRLS roles, a connection with the wrong settinglowdefense in depth for shared tables
Schema per tenantgrants and the search pathroles granted on several schemas; code that sets the wrong search pathmedium: migrations per schematenant-specific extensions, larger customers
Database per tenantcredentials and connection targetanyone holding several tenants' credentials; shared backups and admin toolinghighestcontract or regulatory demands, data residency, very large tenants

Read the third column carefully. None of the four models stops a path whose credentials span tenants: a database per tenant is strong only if the reporting job, the backup operator and the support console do not each hold every tenant's credentials.

This site's recommendation: start with a shared schema where the service checks every object and the repository adds the tenant predicate from the verified context; add row-level security beneath it when the table is shared by many code paths; move a tenant to its own schema or database when a contract, residency rule or size demands it, not before.

The smallest wall: a predicate from the verified context#

Before any database feature, the example puts the tenant into the query in one place: the repository. The broker's token was validated, the subject built from it, and the repository takes the tenant from that subject. The request supplies only the record id. This is services.py QuoteRepository.find, quoted as it is:

class QuoteRepository:
    """Data access. The predicate comes from the verified context; request parameters supply only the id."""

    def find(self, record_id: str, ctx: dict[str, Any]) -> dict[str, Any] | None:
        """SELECT ... WHERE (quote_id = ? OR submission_id = ?) AND <tenant or unit predicate from ctx>."""
        r = find_record(record_id)
        if r is None:
            return None
        if ctx.get("tenant") is not None and r["tenant"] != ctx["tenant"]:
            return None
        if ctx.get("business_unit") not in (None, "*") and r["business_unit"] != ctx["business_unit"]:
            return None
        return dict(r)

The snippet below demonstrates what the predicate does for a context of tenant brk-north, by quote id and by submission id. A successful run proves the repository refuses another tenant's record even with no policy check in front of it; it does not replace that check.

import services

repo = services.QuoteRepository()
north = {"tenant": "brk-north", "business_unit": None}      # from the broker's verified token
for record_id in ("Q-5531", "SUB-1004", "Q-6620", "SUB-2001"):
    row = repo.find(record_id, north)
    print(record_id, "->", row["quote_id"] + " " + row["tenant"] if row else None)
print("find_unsafe Q-6620 ->", repo.find_unsafe("Q-6620")["tenant"])

Run in a scratch copy of examples/uw-auth on 2026-11-18:

Q-5531 -> Q-5531 brk-north
SUB-1004 -> Q-5531 brk-north
Q-6620 -> None
SUB-2001 -> None
find_unsafe Q-6620 -> brk-south

The submission id SUB-1004 leads to the same record as Q-5531, and SUB-2001 is refused like Q-6620, so switching identifiers does not cross the wall. The last line is the labelled mistake: find_unsafe queries by id only. It exists in the example to show the hole (case UW-A03) and is never used by the safe path.

Two layers decide here, on purpose. The quote service asks the policy decision point about the record (rule R-AZ-03), which is the authorization decision and can answer 404 or 403 with a reason (see Enforcement). The repository predicate is the backstop that makes a forgotten check return nothing. Guideline (OWASP Multi-Tenant cheat sheet): "Treat client-supplied tenant identifiers as selectors only" and "Bind tenant context to a server-verified identity and current tenant membership or service authorization."

Production pitfall. A tenant_id in the URL, a header or the request body is a selector at most. If the repository reads the tenant from the request instead of from the verified subject, every broker can choose their tenant.

Object checks across tenants, in the lab#

Roles alone cannot express tenant isolation: every broker has the role broker, in every tenant. The access-control models lab shows it on five requests. It opens on the tenant preset: the attribute model, with the cross-tenant broker request selected.

PrincipalActionRecordRBACABACReBACReBAC reason
u-broker-n1 (broker, brk-north)quote.readQ-5531allowallowallowrole, attributes and relationship match
u-broker-n1 (broker, brk-north)quote.readQ-6620 (brk-south)allow (hole)denydenytenant brk-south is not the caller's tenant brk-north
u-uw-w1 (assigned underwriter)decision.recordSUB-1004allowallowallowrole, attributes and relationship match
u-uw-w2 (peer underwriter, same unit)decision.recordSUB-1004allow (hole)allow (hole)denyno assigned_to relationship between u-uw-w2 and SUB-1004
u-uw-e1 (underwriter, commercial-east)submission.readSUB-1004allow (hole)denydenyunit commercial-west is not the caller's unit commercial-east

The second row is the tenant row: the role model allows the cross-tenant read, the attribute model (tenant on the subject, tenant on the record) refuses it. The models themselves are explained on Access models. The agent here is a scripted stand-in, so these results show how the access controls work, not how good any model is.

Row-level security, and who walks around it#

Row-level security moves the tenant predicate into the database, so that every query on the table is filtered, including the ones a developer forgot to write the predicate for. Product (PostgreSQL 18, as documented on 2026-11-18): with row security enabled, "all normal access to the table for selecting rows or modifying rows must be allowed by a row security policy", and with no policy "a default-deny policy is used". USING filters existing rows; WITH CHECK checks new ones.

The demo in examples/frameworks/postgres-rls/ ran on PostgreSQL 18.7 in a throwaway container with no published port (./run.sh, psql -X -e -f rls.sql). The policy reads the tenant from a transaction-local setting the application fills from the verified token:

ALTER TABLE quotes ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON quotes
  USING (tenant = current_setting('app.tenant', true))
  WITH CHECK (tenant = current_setting('app.tenant', true));

Then six steps, as the run printed them (excerpt; every line shown is verbatim, steps 3 and 4 shortened to their result):

--- 1. ENABLE only: the table OWNER still sees every tenant (owners bypass RLS by default)
SET LOCAL ROLE uw_owner;
SET LOCAL app.tenant = 'brk-north';
SELECT quote_id, tenant FROM quotes ORDER BY quote_id;
 quote_id |  tenant   
----------+-----------
 Q-5531   | brk-north
 Q-5532   | brk-north
 Q-6620   | brk-south
(3 rows)

--- 2. FORCE ROW LEVEL SECURITY: now the owner is filtered too
ALTER TABLE quotes FORCE ROW LEVEL SECURITY;
SELECT quote_id, tenant FROM quotes ORDER BY quote_id;
 quote_id |  tenant   
----------+-----------
 Q-5531   | brk-north
 Q-5532   | brk-north
(2 rows)

--- 3. cross-tenant SELECT by id: zero rows, not an error (the API maps this to 404)
(0 rows)
--- 4. cross-tenant INSERT: refused by WITH CHECK
psql:/sql/rls.sql:45: ERROR:  new row violates row-level security policy for table "quotes"
--- 5. no tenant set (a forgotten SET): zero rows
 visible_rows 
--------------
            0
--- 6. superuser: bypasses RLS even with FORCE (never connect the application as a superuser)
SELECT current_user, count(*) AS visible_rows FROM quotes;
 current_user | visible_rows 
--------------+--------------
 postgres     |            3

Step 1 is the reporting team's three rows from the opening. Step 2 closes the owner's door with FORCE. Steps 3 to 5 show the policy working: another tenant's row does not exist for this transaction, a write for another tenant is refused, and a transaction that forgot to set the tenant sees nothing (current_setting('app.tenant', true) returns NULL, and NULL matches no row). Step 6 is the door FORCE does not close.

Role connectingFiltered by the tenant policy?Source
ordinary role, not the owneryes, once RLS is enabledPostgreSQL docs; run
table owner, RLS enabled onlyno: owner saw 3 rowsPostgreSQL docs ("Table owners normally bypass row security"); run step 1
table owner, FORCE ROW LEVEL SECURITYyes: 2 rowsrun step 2
superuserno, even with FORCE: 3 rowsPostgreSQL docs; run step 6
role with BYPASSRLSnoPostgreSQL docs ("Superusers and roles with the BYPASSRLS attribute always bypass the row security system"); not part of the run

This site's recommendation: the application connects as a role that does not own the tables, is not a superuser and has no BYPASSRLS; force row security on tenant tables anyway, so that a later ownership change does not silently open them; and set the tenant with SET LOCAL inside each transaction. A plain session-level SET on a pooled connection can carry one request's tenant into the next request on the same connection; that was not demonstrated in the run, it is a reasoning note, and the OWASP sheet's advice matches it: "Re-establish the tenant context for every transaction" and "Fail closed if the tenant context is missing or invalid."

Common confusion. Row-level security is a backstop beneath the service's authorization, not a replacement for it. It knows the tenant of a row; it does not know that only the assigned underwriter may record a decision, or that a broker may read but not submit for a closed quote. Those decisions stay in the policy decision point (Policy as code).

Proving it: cross-tenant tests#

A wall nobody has tried to cross is a hope. A cross-tenant test acts for one tenant with entirely valid credentials and asks for another tenant's data on a specific path, and passes only when nothing comes back. The valid credential is the point: a test with a broken token tests authentication, not isolation.

The example's definition-of-done evidence includes seven such tests, one per path: the broker by quote id and submission id, an underwriter and an agent across units, retrieval, precedent search, and an MCP tool. They were run in a scratch copy on 2026-11-18 (/opt/homebrew/bin/python3 -m unittest test_negative.Dod5NoCrossTenantRead -v):

test_agent_cannot_read_another_units_submission (test_negative.Dod5NoCrossTenantRead.test_agent_cannot_read_another_units_submission) ... ok
test_broker_can_never_search_precedents (test_negative.Dod5NoCrossTenantRead.test_broker_can_never_search_precedents) ... ok
test_broker_cannot_read_another_tenants_quote_by_quote_id_or_submission_id (test_negative.Dod5NoCrossTenantRead.test_broker_cannot_read_another_tenants_quote_by_quote_id_or_submission_id) ... ok
test_mcp_tool_cannot_reach_another_units_submission (test_negative.Dod5NoCrossTenantRead.test_mcp_tool_cannot_reach_another_units_submission) ... ok
test_precedent_search_never_returns_another_units_precedent (test_negative.Dod5NoCrossTenantRead.test_precedent_search_never_returns_another_units_precedent) ... ok
test_retrieval_never_returns_another_tenants_chunk (test_negative.Dod5NoCrossTenantRead.test_retrieval_never_returns_another_tenants_chunk) ... ok
test_underwriter_cannot_read_another_units_submission (test_negative.Dod5NoCrossTenantRead.test_underwriter_cannot_read_another_units_submission) ... ok

----------------------------------------------------------------------
Ran 7 tests in 0.001s

OK

The first broker test is the core pattern, worth copying. Broker u-broker-s1 of brk-south gets a genuine token and asks for Q-5531, SUB-1004 and Q-5532. Each answer must be status 404 with no body:

def test_broker_cannot_read_another_tenants_quote_by_quote_id_or_submission_id(self) -> None:
    plat = services.Platform(NOW)
    tok = tokens.issue_for("u-broker-s1", aud=tokens.API_AUD, now=NOW)
    for rid in ("Q-5531", "SUB-1004", "Q-5532"):
        r = plat.read_quote(tok, rid, "req-" + rid)
        self.assertEqual((r["status"], r["body"]), (404, None), rid)

A useful cross-tenant suite has a row for every path that returns tenant data, and a column for every identifier that reaches a record:

PathWhat the test sendsExpected
read APIother tenant's quote id, then its submission id404, no body, for both
write APIa submit or update for the other tenant's quoterefused, nothing written
list and searcha query that would match other tenants' recordsonly own-tenant results, no counts that reveal others
retrieval for the agenta search with a filter the model proposed for "all tenants"own-tenant chunks only (UW-A13)
cachesame request for two tenants back to backno cached answer crosses (tenant in every key)
export and reportsthe reporting role with the tenant setown-tenant rows only, under FORCE
database rolea direct connection as the application role with no tenant setzero rows

Guideline (OWASP Multi-Tenant cheat sheet): test the authorization matrix for each row-level-protected table, derive the table list from the schema and compare it with pg_class and pg_policies, "Exercise connection reuse" by running two tenants' requests over reused connections, and test a backup with two tenants: recover one and verify the other's records are absent. The last two are the tests teams skip, and they catch the leaks that unit tests cannot. The full negative suite of the site is on Threats and tests.

Administrators, auditors and service accounts#

Some principals legitimately see more than one tenant, and each is a door in the wall. The design question is not whether they exist but how narrow, visible and temporary their access is.

The auditor u-auditor-1 reads audit records for all units and writes nothing. That is a standing, read-only, cross-boundary grant, and it is acceptable because it is named, limited to one action (audit.read, rule R-AZ-10) and itself audited.

The platform administrator u-admin-1 has no standing access at all. To act on a tenant's data, the administrator requests a just-in-time elevation with an approval and an expiry, and every action under it is recorded (rule R-AZ-11; see Privileged access). A support engineer's "look at this broker's quote" is the same: a time-bound grant for one tenant, not a superuser connection.

Service accounts are the doors people forget. A reporting job, a backup job, a search indexer and a migration tool each connect with a credential, and each is usually given more than one tenant "for convenience". Guideline (OWASP Multi-Tenant cheat sheet): cross-tenant administrative paths must be "explicit, separately authorized, and auditable"; "Do not serve ordinary tenant-scoped requests through a privileged connection"; classify asynchronous work "as global, tenant-scoped, or explicitly cross-tenant", and for tenant-scoped work derive the tenant "from the authenticated producer" and re-establish it at the consumer.

PrincipalTenants it can reachStanding or temporaryHow it is narrowed
brokerown tenantstandingtenant on the subject, checked on every record
auditorall units, read-onlystandingone action, audit records only, itself audited
platform administratornone, until elevatedtemporaryJIT elevation with approval and expiry
reporting jobone tenant per runper runtenant set per transaction, role subject to FORCE
migration or backup toolallstanding, privilegedseparate credential, never used for requests, every use logged
What this is not. Granting and removing these accounts over time (joiners, movers, leavers, reviews) is identity governance, on Governance. This page covers what each account can reach once it exists.

A model never writes the tenant filter#

The underwriting agent and the broker portal's assistant both search documents. A retrieval request is a natural place for a model to "help" with the filter: it reads a passage, decides it needs broader context, and proposes {"tenant": "*"}. If the retrieval service applied filters proposed by the model, the model would be choosing which tenants' data reach it, and a prompt injection in one tenant's attachment could ask for another tenant's.

In the example, the retrieval service builds the filter from the verified identity and ignores any filter a model proposes. This site's own case UW-A13 checks it. The snippet demonstrates it for the broker: the model asks for every tenant, the service ignores it. A successful run proves the proposed filter had no effect on these results; retrieval mechanics are on the RAG chapter.

import retrieval
from clock import START_EPOCH_S as NOW
from directory import RECORDS, subject_for

broker = subject_for("u-broker-n1", now=NOW)
flt = retrieval.build_filter(broker, RECORDS)                 # from the verified identity
print("filter:", flt["kinds"], flt["submission_ids"])
r = retrieval.search("filter_first", flt, llm_filter={"tenant": "*"})
print("llm_filter_ignored:", r["llm_filter_ignored"], "| leaked:", r["leaked"])
print("tenants returned:", sorted({x["tenant"] for x in r["results"]}))
filter: ['attachment'] ['SUB-1004', 'SUB-1007']
llm_filter_ignored: True | leaked: []
tenants returned: ['brk-north']

The filter names only brk-north's submissions, because the broker's subject says brk-north. The proposed filter is recorded as ignored, nothing leaked, and only one tenant's chunks came back.

Diagram: The model proposes, the service filters · the tenant boundary stays in code (UW-A13)

Read left to right. The model proposes a search with its own filter, here every tenant. The retrieval service ignores that filter and builds its own from the verified subject: tenant brk-north, its submissions. Only chunks that pass reach the model. A prompt injection can change what the model asks for; it cannot change which tenant the service filters on.

  1. Model output (untrusted)
    1. search request: The model writes a query and proposes a filter. Its text may be influenced by injected content.
  2. Retrieval service (deterministic)
    1. filter from the verified subject: Built from the validated identity and the directory, never from the query or the model.
    2. proposed filter ignored: The model's filter is recorded as ignored and has no effect on which records are searched.
  3. What reaches the model
    1. own-tenant chunks only: Results come only from the broker's own tenant; a cross-tenant test asserts nothing else ever does.

The rule generalizes: whether a model writes SQL, a search filter or tool arguments, deterministic code adds the tenant boundary from the verified subject, outside the model's reach. The model suggests an action; deterministic code decides whether it may run, and on which tenant's data. A tenant condition inside the model's query is untrusted text. Defenses against the injection itself are on Guardrails Engineering.

In a coding agent. A coding agent asked to "fix the slow tenant report" must not get a database credential that spans tenants, and its sandbox has no production database credential at all. It proposes a change to the query in a pull request; a cross-tenant test in CI runs that query for two tenants and fails if either sees the other's rows; a person reviews and merges. See Coding agents.

Data residency#

Some brokerages, or the law that governs them, require their data to stay in one jurisdiction. Data residency is a constraint on where a tenant's data is stored and processed. A tiny example: a brokerage in one country requires that its quotes, attachments and their backups never leave that country's region.

Residency is not authorization, and it does not replace isolation. It answers "where may these bytes be", not "who may read them". But it shapes the isolation model, because a tenant whose data must stay in one region cannot share a table, an index or a backup with tenants stored elsewhere. In practice residency pushes a tenant towards a database (or a whole deployment) per region.

The hard part is the copies. The primary database is the easy one to place; the leaks are in what copies data out of it:

Copy of tenant dataResidency question
backups and replicaswhich region holds them, and who can restore them
search and vector indexesbuilt in the tenant's region, or in a shared one
cachesregional, with the tenant in every key
logs and decision recordsdo they carry quote content or only ids
a model provider or LLM gatewaywhich region processes prompts that contain the tenant's text
support toolingcan an operator in another region open the data

This site's recommendation: record each tenant's residency requirement as an attribute the platform enforces at placement time (which database, which index, which model endpoint), keep logs and decision records to identifiers rather than content, and route a tenant's model calls through an LLM gateway in the allowed region. The documentation read for this page gives no product-specific residency guarantees, and none are claimed here. Model-provider routing is on Model providers.

Choosing an isolation design#

SituationSimplest credible designGrow whenAlternatives
New B2B SaaS, a few tenantsShared schema; object check in the service; tenant predicate from the verified context in the repository; cross-tenant testsmany code paths query the same tablesan ORM-level global filter
Many services and jobs on shared tablesAdd row-level security, forced, with a non-owner application role and SET LOCALa tenant needs its own extensions or migrations paceschema per tenant
A tenant with contract or residency demandsDatabase (or deployment) per tenant for that tenant only; hybrid for the restmost tenants need itdatabase per tenant for everyone
Agents and retrieval over tenant dataFilter built from the verified subject; model-proposed filters ignored; revalidation against the sourceshared indexes across many tenantsan index per tenant

Underneath every row: the tenant comes from the verified identity, and every principal that can cross it is named and audited.

Security notes#

Monday checklist#

Exercises#

Exercise 1. The reporting job from the opening is fixed by adding FORCE ROW LEVEL SECURITY. A month later the team migrates the database and the job starts returning all tenants again. Name two likely causes.

AnswerA superuser or a recreated table

The job now connects as a superuser (or a role with BYPASSRLS) in the new environment, which bypasses even FORCE; or the migration recreated the table without the FORCE and policy statements. A deploy-time check that queries relforcerowsecurity and runs a zero-rows test as the application role catches both.

Exercise 2. Why does the example answer 404, not 403, when broker u-broker-s1 asks for Q-5531?

AnswerA 403 confirms that the quote exists

A 403 tells the caller that Q-5531 exists and belongs to someone else, which leaks another brokerage's activity. A 404 answers the same way for a missing quote and for another tenant's quote. The status rules are on Authorization.

Exercise 3. A product manager asks for the agent to "search all brokerages' past decisions to find better precedents". What is the tenant-safe version of this feature?

AnswerInsurer-side precedents, inside the caller's boundary, never broker content

Precedents are the insurer's own decisions, searched inside the caller's business unit (rule R-AZ-06), and never return a brokerage's attachments or rationale to another brokerage. If cross-unit learning is needed, it is a separate, explicitly authorized, anonymized dataset with its own owner, not a wider filter on the live index.

Advanced perspective#

Connection pools and tenant contextState on a connection outlives the request that set it

A connection pool hands the same physical connection to many requests in turn. A session-level setting (SET app.tenant = 'brk-north' without LOCAL, a changed search_path, a SET ROLE) stays on that connection until something resets it, so the next request on the connection inherits the previous tenant. Three defenses, best combined: set tenant context with SET LOCAL inside an explicit transaction, so it ends with the transaction; have the pool run a reset on every checkout; and make "no tenant set" mean zero rows (the demo's current_setting('app.tenant', true) is NULL when unset). Then test it as the OWASP sheet suggests: two tenants alternating over one reused connection, asserting each sees only its own rows. With a transaction-mode external pooler, session state is especially fragile; transaction-local settings are the shape that survives it.

Schema per tenant: the search path is part of the boundaryA user can reach any schema they have privileges on

Product (PostgreSQL 18, as documented on 2026-11-18): "Unlike databases, schemas are not rigidly separated: a user can access objects in any of the schemas in the database they are connected to, if they have privileges to do so", while "A client connection to the server can only access data in a single database". So schema-per-tenant isolation is only as strong as the grants: one role per tenant with USAGE on its own schema only. The search path is security-relevant too: "adding a schema to search_path effectively trusts all users having CREATE privilege on that schema." Revoke CREATE on public from PUBLIC (the page says "In PostgreSQL 15 and later, the default configuration supports" the secure pattern, while databases upgraded from 14 or earlier still grant it), set the search path explicitly per transaction, and qualify names in shared functions. The operational cost is migrations: a schema change runs once per tenant, and a half-applied migration leaves tenants on different schemas, which is drift of a different kind.

Isolation beyond confidentialityNoisy neighbours, deletion and restore

Tenant isolation is usually discussed as "no one reads another tenant's data", but contracts often mean more. Performance isolation: one tenant's bulk import should not slow another's quotes, which shared tables cannot promise without rate limits per tenant. Deletion: when a brokerage leaves, its rows, attachments, index entries, cache entries and backups must go, and in a shared table that is a careful delete across many stores, while a database per tenant is a drop plus backup expiry. Restore: restoring one tenant from a shared backup must not bring back another tenant's deleted data or give the operator sight of it; the OWASP sheet's advice is to test exactly that with two tenants. These are the triggers that move a tenant to its own database more often than read isolation does.

In one breath#

A tenant here is a brokerage, and tenant isolation means no principal acting for one brokerage reaches another's data on any path. The service decides on the record, the repository adds the tenant from the verified subject, and row-level security can filter beneath both, as long as the connection's role is not an owner without FORCE, a superuser or a BYPASSRLS role. Schemas and separate databases move the boundary into grants and credentials, and only help if the jobs and people with wider access are named, narrow and audited. Cross-tenant tests with valid tokens prove it on every path, and a model never writes the filter.

The wall between brokerages now holds, and the principals who may cross it are few and named. But who are they this week? The peer underwriter changed units on Monday, a contractor left on Friday, and the reporting job's service account has no owner. Governance follows identities through joining, moving and leaving, and the reviews that keep this page's tables true.