Multi-Tenancy Strategies
"There's no single solution that works for every scenario. The option that you choose depends on several factors and your tenants' requirements." — Microsoft, Architectural Approaches for Storage and Data in Multitenant Solutions, Azure Architecture Center
Summary: Multi-tenancy is the decision about how much of the stack each customer gets: a row, a schema, a database or a whole pod, and every step trades cost against isolation. Focus: The three models and the hybrid, PostgreSQL Row-Level Security done safely, noisy neighbours, per-tenant migrations, backups, offboarding, caching, quotas, analytics, sharding and testing. Learning goal: Pick a model per customer tier, make a forgotten WHERE tenant_id harmless, and prove it with a test instead of trusting it.
This page is the complete reference for serving many customers (tenants) from one application: shared schema with tenant_id, schema per tenant, database per tenant, the hybrid bridge or pod model, the four kinds of isolation (data, performance, security, compliance), PostgreSQL RLS (CREATE POLICY, FORCE ROW LEVEL SECURITY, current_setting, set_config, BYPASSRLS), composite indexes, LIST partitioning, connection routing, migrations across thousands of schemas, backup granularity, offboarding and GDPR erasure, tenant-aware caches, quotas, cross-tenant analytics, Citus, tenant sharding and rebalancing, the MySQL and SQL Server answers, per-tenant roles and keys, the stancl/tenancy and spatie/laravel-multitenancy packages, and how to test isolation. Neighbouring pages hold the details of what it builds on: Partitioning & Sharding in PostgreSQL, Connection Pooling, Zero-Downtime Schema Migrations, Backup, PITR & Disaster Recovery, Database Security and Encryption at Rest, in Transit & in Use.
Page map
| If you are looking for | Go to |
|---|---|
| Sources and history | Where it comes from |
| A table you can memorise in one minute | Everything in one minute |
| Why the models differ and what you pay for each | Why several models exist |
| Shared schema, schema per tenant, database per tenant, hybrid | The models, one by one |
| Noisy neighbours and the four kinds of isolation | Isolation and noisy neighbours |
CREATE POLICY, FORCE, set_config, BYPASSRLS, RLS speed | Mechanics: Row-Level Security in depth |
| Leading-tenant indexes, LIST partitions, routing | Indexes, partitions and routing |
| Migrations, backups, offboarding, caches, quotas, analytics | Solving the classic problems: operations per tenant |
| Citus, tenant sharding, rebalancing | Sharding by tenant |
| MySQL, SQL Server, Oracle, MongoDB, Redis answers | What each product offers |
| Roles and keys per tenant | Roles and encryption per tenant |
| Go middleware and Laravel code, packages | Go and Laravel |
| Tests that prove isolation | Testing tenant isolation |
| Which model for which customer | Choosing a model |
| Monolith to distributed | In architecture |
| Reproduce it, break it, measure it | Lab |
| Wrong beliefs, cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Where it comes from
The sources I read are vendor documentation rather than research papers. The Microsoft guide runs from a shared database with a tenant column to a separate database for each tenant, and it says plainly that none of these options wins everywhere. The database feature that makes the shared model safe is older and better documented. PostgreSQL added row-level security in version 9.5, released on 7 January 2016. The release notes describe it this way:
"This feature allows row-by-row control over which users can add, modify, or even see rows in a table. This is controlled by new commands CREATE/ALTER/DROP POLICY and ALTER TABLE ... ENABLE/DISABLE ROW SECURITY."
SQL Server has the same idea as security policies with filter and block predicates, and Microsoft describes the filter as "functionally equivalent to appending a WHERE clause". Citus, the PostgreSQL extension for distributed tables, built its multi-tenant guide around a tenant_id on every table. I did not find a primary source for who first used the term "multi-tenancy" in software. Treat any date you see for that elsewhere as unchecked.
Everything in one minute
The three models and the hybrid. Every row is unpacked in the models section.
| Model | Isolation boundary | Cost per tenant | Migration cost | Restore one tenant | Typical limit |
|---|---|---|---|---|---|
Shared schema (tenant_id column) | A row | Lowest | One ALTER | Hard (restore aside, copy rows) | One missing predicate leaks data |
| Schema per tenant (PostgreSQL schema) | A namespace in one database | Low | N ALTERs | Medium (pg_dump -n) | Catalog size, pg_dump time at thousands of schemas |
| Database per tenant | A whole database | High | N databases to keep in step | Easy (restore one database) | N pools, N connections, N monitors |
| Hybrid (bridge, pod, silo) | Chosen per tenant tier | Mixed | Routing by directory | Per tier | Needs a control plane and a router |
The four isolations. A model is judged on four axes, and they are not the same thing.
| Isolation | Question it answers | Weak in | Strong in |
|---|---|---|---|
| Data | Can tenant A read or write tenant B's rows? | Shared schema without RLS | Database per tenant |
| Performance | Can tenant A slow tenant B down? | Shared schema, shared pool | Dedicated database on dedicated hardware |
| Security | Can a bug, SQL injection or stolen credential cross tenants? | Shared role with a WHERE convention | Per-tenant role or database credentials |
| Compliance | Can I prove location, key ownership and deletion per tenant? | Shared everything | Regional silo with a tenant-owned key |
The five things to do.
| Situation | Do this |
|---|---|
| Starting a SaaS | Shared schema, tenant_id first in every key and index, RLS as the backstop |
| Any shared table | ENABLE and FORCE ROW LEVEL SECURITY, app role without BYPASSRLS, set_config(..., true) per transaction |
| One tenant becomes huge | Move it to its own database or shard (the hybrid), keep the same schema |
| Thousands of schemas | Automate migrations with a version table and a worker pool; watch catalog size |
| Compliance or contract demands it | Dedicated database, region and key for that tenant only |
Why several models exist
A tenant is a customer whose data must be kept apart from other customers' data while the same application serves all of them. The trouble is that "kept apart" has a price in money, in operations and in risk, and the price rises with every layer you duplicate.
| Duplicate less (shared) | Duplicate more (isolated) |
|---|---|
| One schema, one pool, one backup, one migration | One of each per tenant |
| Cheap per tenant, thousands fit on one server | Expensive per tenant, tens or hundreds per server |
| A bug or a heavy tenant reaches everyone | A bug or a heavy tenant stays inside one boundary |
Cross-tenant reports are one GROUP BY | Cross-tenant reports need fan-out or a warehouse |
| Per-tenant restore, region or key is hard | Per-tenant restore, region or key is normal |
An everyday picture, reused through the page. An office building offers three arrangements. A coworking floor has shared desks and one reception desk that signs people in, which is cheap but depends on the receptionist. A corridor of separate suites shares the building's lobby and power, but each company has its own locked door. A separate building for each company is the most expensive, and a fault in one building stays in that building. The receptionist's sign-in is the WHERE clause; the locked door is RLS, which still works when the receptionist forgets.
Three misunderstandings, up front.
- "Multi-tenancy is a database feature." It is an application and operations decision; PostgreSQL only gives you tools (schemas, roles, RLS, partitions).
- "RLS makes the shared model as safe as separate databases." It narrows the gap a lot, but owners, superusers and
BYPASSRLSroles walk through it, and one pool still shares CPU and I/O. - "Pick a model once." Customers differ. The mature answer is a hybrid where the same schema can live in a pooled database or a dedicated one, chosen by a directory.
The models, one by one
Shared schema (row-level) Must-know
In plain words: Everyone's rows live in the same tables. A tenant_id column says whose row it is, and every query must ask only for its own.
Common misunderstanding: "It is insecure by nature." It is exactly as secure as the layer that adds the predicate. Written by hand it is fragile; enforced by RLS it is a database guarantee with known limits.
Definition: One database, one schema, one set of tables, with a tenant discriminator column on every tenant-owned table, part of every primary key and every index that serves tenant queries.
Azure calls the alternative an antipattern: "When you work within a single database, avoid creating individual tables for each tenant." That is one table per tenant, a different thing from schema per tenant.
Request (tenant acme) Request (tenant globex)
1 GET /orders GET /orders
2 SELECT * FROM orders WHERE tenant_id = 'acme' SELECT * FROM orders -- developer forgot the WHERE
3 -> 2 rows, all acme -> every tenant's rows, globex sees acme's ordersReal scenarios: a B2B invoicing app with 20 000 small customers; a ticketing tool where the biggest customer has 400 times the rows of the median; an internal platform with 30 teams.
| What provides isolation | How | Strength |
|---|---|---|
Convention (WHERE tenant_id = ? by hand) | Every developer remembers | Weakest; one slip leaks |
| ORM global scope (Eloquent, GORM scopes) | Adds the predicate to model queries | Convenient; skipped by raw SQL and the query builder |
| RLS policy | PostgreSQL adds the predicate | Strong; bypassed by owners, superusers, BYPASSRLS |
| Per-tenant database role + RLS | Policy keyed on current_user | Strongest in this model |
Fix / how to use it:
CREATE TABLE orders (
tenant_id text NOT NULL,
id bigint GENERATED ALWAYS AS IDENTITY,
total_cents bigint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id)
);
CREATE INDEX orders_tenant_created ON orders (tenant_id, created_at);The Go and Laravel versions are in Go and Laravel.
Schema per tenant Important
In plain words: One database, but each customer gets its own folder (schema) with its own copy of every table.
Common misunderstanding: "A schema is a mini database." The PostgreSQL manual puts it plainly: "Schemas are analogous to directories at the operating system level, except that schemas cannot be nested." Tables are separated by name, but the database is still one unit for backups, WAL, connections and CPU.
Definition: CREATE SCHEMA tenant_acme plus the same tables inside it; the request sets search_path (or qualifies names) so unqualified table names resolve to that tenant's schema.
Request A (tenant acme) Request B (tenant globex), same pooled connection
1 SET search_path = tenant_acme; -- session setting, not reset by the pool
2 SELECT * FROM orders; -- acme rows
3 (request A returns the connection to the pool)
4 SELECT * FROM orders; -- still resolves to tenant_acme
5 -- globex reads acme's rows: the leak is a missing search_pathReal scenarios: a vertical SaaS with 200 mid-size customers who ask for per-customer restore; per-tenant customisation of a few tables (extra columns) without touching others; a legacy app that used one schema per customer from the start.
| Aspect | Schema per tenant | Shared schema |
|---|---|---|
| Name collisions | None, each schema has its own orders | One table |
| Per-tenant restore | pg_dump -n tenant_acme | Restore aside, copy rows |
| Migrations | Run once per schema | One ALTER |
| Catalog size | tenants x tables relations in pg_class | tables |
| Cross-tenant query | UNION ALL across schemas | One GROUP BY |
| Connection pooling | Safe only with transaction-local search_path | Safe with transaction-local set_config |
Fix / how to use it: set the path per transaction, never per session.
BEGIN;
SET LOCAL search_path = tenant_acme, public;
SELECT count(*) FROM orders;
COMMIT;SET LOCAL cannot take a bind parameter, so a dynamic schema name must be validated against the tenant directory and quoted with quote_ident() or format('%I', ...). Never concatenate it from request input.
Database per tenant Important
In plain words: Each customer has its own database, sometimes on its own server. Nothing is shared except the application code.
Common misunderstanding: "Then there is no noisy-neighbour problem." If many databases sit on one server they still share CPU, memory, disk I/O and the connection limit. Dedicated databases isolate data, not hardware, unless the server is dedicated too.
Definition: The router chooses a connection pool by tenant. Every tenant has the same schema (kept in step by migrations) in a separate database.
| Strength | Cost |
|---|---|
| A leak is structurally hard: the connection cannot see other tenants | N pools: N x pool size server connections |
| Per-tenant backup, restore, region, key, version | N migrations to run and verify |
Per-tenant sizing and ALTER SYSTEM-level tuning only on a dedicated server | N dashboards and N alerts |
Easy offboarding: DROP DATABASE | Cross-tenant analytics needs fan-out or a warehouse |
Real scenarios: enterprise customers who contractually require their own database; healthcare tenants with a region requirement; a dev tool where each organisation can export its database as a file (SQLite per tenant).
Routing is covered in Indexes, partitions and routing; a capped pool router is in the Go section.
Hybrid: bridge, pod and silo Must-know
In plain words: Small customers share a pooled database; a big or regulated customer gets its own. A directory says where each tenant lives, and the application code stays the same.
Common misunderstanding: "Hybrid means two codebases." It means one schema and one codebase, with the routing decision moved into data. The names vary: AWS calls the shared option the pool model and the dedicated option the silo model, and a mix the bridge model; Azure talks about deployment stamps and sharding. Treat the words as vendor vocabulary and describe your own topology in plain terms.
Definition: A control plane (often called the landlord database) stores tenant -> pod, dsn, tier, region. Each pod is a pooled database or a dedicated one. The router resolves the tenant on every request, with a short cache.
Tenant "acme" grows, ops decides to move it out of the pooled pod
1 directory: acme -> pod-a (pooled), state = active
2 create database acme on pod-b, apply the same migrations
3 copy acme's rows (logical replication with a row filter, or COPY)
4 catch up until lag is near zero
5 set directory state = moving -> writes for acme return 503 for seconds
6 final catch-up, verify counts and checksums
7 directory: acme -> pod-b (dedicated), state = active
8 after a grace period, delete acme's rows from pod-aReal scenarios: a free tier in a pooled pod with the paid enterprise tier in silos; an EU-only customer in an EU pod while the rest stay in a US pod; a customer that outgrows a pooled database and is "graduated" to its own.
| Pod type | Who goes there | Isolation | Cost |
|---|---|---|---|
| Pooled, shared schema + RLS | Free and standard tiers | Row (RLS) | Lowest |
| Pooled, schema per tenant | Mid tier needing per-tenant restore | Schema | Low |
| Silo, database per tenant | Enterprise, large data | Database | High |
| Regional silo with own key | Regulated, BYOK | Database + region + key | Highest |
Isolation and noisy neighbours
Noisy neighbours Must-know
In plain words: One loud customer uses so much of the shared machine that everyone else gets slow.
Common misunderstanding: "Fast indexes fix it." Indexes make each query cheaper; they do not stop one tenant from running a thousand of them, a huge report, or a long lock.
Definition: Azure's wording: "Multitenant data and storage services are susceptible to the noisy neighbor problem." Citus names the same goal, "isolating tenants from noisy neighbors", as one of the typical challenges.
Shared pooled database (pool of 20 connections)
1 tenant big : starts 20 concurrent exports, each 40 s of CPU
2 tenant small: GET /dashboard needs 1 connection -> waits for a free connection
3 tenant small: pool wait 12 s, request times out -> small tenant sees an outage it did not cause
4 fix: per-tenant concurrency cap + rate limit + move big to its own pool or databaseReal scenarios: a month-end report that scans one tenant's 80 million rows; an import that holds row locks for minutes; a tenant that triggers autovacuum pressure with huge UPDATEs; a bursty API client.
| Mitigation | Layer | Notes |
|---|---|---|
| Per-tenant rate limit and concurrency cap | Application | Cheapest; see Quotas |
statement_timeout, lock_timeout, idle_in_transaction_session_timeout per role | PostgreSQL | ALTER ROLE tenant_x SET statement_timeout = '5s' for tenant-specific roles |
ALTER ROLE ... CONNECTION LIMIT n | PostgreSQL | Caps connections for a tenant role |
Separate pool or pool_size per tenant | PgBouncer / app | Per-database or per-user pool settings |
| Move the tenant to a dedicated database or node | Topology | The hybrid answer; Citus isolate_tenant_to_new_shard |
| Separate replica for heavy readers | Replication | Replication, Read Replicas & Failover |
| Fair queueing for background jobs | Queues | One queue or weighted queues per tier |
Tenant isolation levels Important
In plain words: "Isolated" can mean four different things, and a customer's contract usually asks for one of them by name.
Common misunderstanding: "Isolation is yes or no." Data isolation can be strong while performance isolation is absent, and the reverse.
| Model | Data | Performance | Security | Compliance |
|---|---|---|---|---|
| Shared schema, convention only | Weak | None | Weak | None |
| Shared schema + RLS | Strong (with caveats) | None | Medium | Weak: no per-tenant key, region or restore |
| Schema per tenant | Medium | None (shared server) | Medium (per-schema grants) | Medium: per-schema dump, no per-tenant key |
| Database per tenant, shared server | Strong | Weak (shared hardware) | Strong (own credentials) | Medium to strong |
| Database per tenant, dedicated server or region | Strong | Strong | Strong | Strong |
Azure lists what pushes you towards isolation: tenants that bring their own encryption keys, tenants with individual backup policies, and tenants whose data must stay in a specific region. If none apply, the shared model is usually the right start.
Mechanics: Row-Level Security in depth
Why RLS exists Must-know
In plain words: RLS makes the database add "and this is your tenant" to every query, so a forgotten WHERE cannot leak rows.
Common misunderstanding: "I turned on RLS, so every connection is filtered." Only roles that are subject to it are filtered. The PostgreSQL manual: "Superusers and roles with the BYPASSRLS attribute always bypass the row security system when accessing a table. Table owners normally bypass row security as well, though a table owner can choose to be subject to row security with ALTER TABLE ... FORCE ROW LEVEL SECURITY."
Definition: ALTER TABLE ... ENABLE ROW LEVEL SECURITY turns the system on for a table; CREATE POLICY defines which rows a command may see or write. The manual states the default: "If no policy exists for the table, a default-deny policy is used, meaning that no rows are visible or can be modified."
Without RLS (forgotten WHERE) With RLS (app_user, policy on orders)
1 SELECT * FROM invoices; SELECT * FROM invoices;
2 -> planner scans all rows -> planner adds: AND tenant_id = current_setting('app.tenant_id', true)
3 -> returns every tenant's invoices -> returns only the current tenant's invoicesThe policy Must-know
In plain words: A policy is a named rule attached to a table: "this role may see rows where this expression is true, and may write rows where that expression is true".
Common misunderstanding: "USING and WITH CHECK are the same." USING filters rows that already exist (reads, and the old row of UPDATE and DELETE). WITH CHECK validates rows being written (INSERT, and the new row of UPDATE). A USING-only policy lets a tenant insert rows that belong to someone else, which then vanish from its own view.
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id', true))
WITH CHECK (tenant_id = current_setting('app.tenant_id', true));| Clause | Purpose | Applies to |
|---|---|---|
FOR ALL / SELECT / INSERT / UPDATE / DELETE | Limit a policy to one command | Default is ALL |
TO role | Limit a policy to certain roles | Default is PUBLIC |
USING (expr) | Which existing rows are visible or targetable | SELECT, UPDATE, DELETE |
WITH CHECK (expr) | Which new or changed rows are allowed | INSERT, UPDATE |
AS PERMISSIVE (default) | Policies combine with OR | Most tenant policies |
AS RESTRICTIVE | Must also pass, combined with AND | An extra "not soft-deleted" or "region" rule on top |
The manual says that multiple permissive policies are combined with OR, and restrictive ones with AND. Use one permissive tenant policy and add restrictive policies for extra rules; two permissive tenant policies would widen access instead of narrowing it.
Setting the tenant: set_config and current_setting Must-know
In plain words: The application tells the database "this transaction is for tenant acme" by writing a custom setting. The policy reads it back.
Common misunderstanding: "SET app.tenant_id = ... is the same as set_config." SET without LOCAL lasts for the whole session. On a pool that gives the same connection to different requests, one tenant's value rides into the next request. The manual says: "If you want the new value to apply for the rest of the current session, use false instead", so true (local to the transaction) is the safe argument.
Definition: set_config(name, value, is_local) is the function form of SET and takes bind parameters; SET LOCAL does not. current_setting(name, missing_ok) throws unless missing_ok is true, in which case it returns NULL. A policy expression that returns NULL hides the row, so a request that forgets to set the tenant sees nothing.
Request 1 (tenant acme) Request 2 (tenant globex), same pooled connection
1 BEGIN;
2 SELECT set_config('app.tenant_id','acme', false); -- session scope: the bug
3 ... COMMIT; (connection returned to the pool, setting stays)
4 BEGIN; (handler forgot to set the tenant)
5 SELECT * FROM orders; -- sees acme: leak
6 Fix: set_config('app.tenant_id','acme', true) inside the transaction; COMMIT clears it.Two details that bite in practice. First, after a custom setting has been set once in a session, current_setting('app.tenant_id', true) returns an empty string, not NULL, once the transaction ends. Comparing text to '' is simply false, but a policy that casts to uuid would raise an error on ''. Use NULLIF(current_setting('app.tenant_id', true), '')::uuid. Second, PgBouncer in transaction pooling mode is safe with set_config(..., true) because the setting lives and dies inside one transaction; session-level SET is exactly what transaction pooling cannot support. See Connection Pooling.
Who bypasses RLS Important
In plain words: RLS has doors that stay open for certain people and certain internal checks.
Common misunderstanding: "My migrations user and my app user are different, so I am fine." Only if the app user is not the table owner and not BYPASSRLS, and migrations did not grant it superuser rights.
| Who or what | Bypasses RLS? | How to close it |
|---|---|---|
| Superuser | Always | Never connect the app as superuser |
Role with BYPASSRLS | Always | ALTER ROLE app_user NOBYPASSRLS; audit with pg_roles.rolbypassrls |
| Table owner | Yes, unless FORCE ROW LEVEL SECURITY | FORCE, and use a non-owner app role |
| Referential integrity checks (FK, unique) | Always, by design | Include tenant_id in keys; watch for covert channels |
pg_dump | With row_security off it errors instead of silently dumping a filtered subset | Dump as a role meant to see all rows |
| Security-definer functions | Run with the definer's rights | Audit every SECURITY DEFINER function |
| Leakproof functions | May run before the policy check | Rarely a concern; keep tenant policy simple |
| Views owned by a privileged role | Run with the owner's rights by default | security_invoker = true on views (PostgreSQL 15+) |
The manual's note on referential checks: "Referential integrity checks, such as unique or primary key constraints and foreign key references, always bypass row security to ensure that data integrity is maintained." A tenant can sometimes learn that a key exists in another tenant by getting a unique violation. Prefix unique keys with tenant_id so uniqueness is per tenant and the probe finds nothing.
Performance of RLS Important
In plain words: RLS adds one more condition to each query. Whether that is free or slow depends on whether the planner can use an index for that condition.
Common misunderstanding: "RLS is slow." The manual explains the mechanism: the policy expression "will be evaluated for each row prior to any conditions or functions coming from the user's query" except for leakproof functions. A simple tenant_id = current_setting(...) comparison is a stable expression, so with tenant_id leading an index the planner can use an index condition. The slow cases are policies with sub-selects or joins, non-leakproof functions in your own WHERE that are held back until after the policy, and current_setting() evaluated per row.
| Policy shape | Expected cost | Why |
|---|---|---|
tenant_id = current_setting(...) with (tenant_id, ...) index | Close to the hand-written WHERE | Index condition, one lookup |
| Same policy, no tenant-leading index | Seq scan filtered per row | Policy cannot help the planner without an index |
tenant_id = (SELECT current_setting(...)) | Often faster on large scans | Evaluated once as an initPlan; check with EXPLAIN |
Policy with EXISTS (SELECT ... FROM memberships ...) | Per-row sub-select | The manual warns such policies are slower and can race |
Non-leakproof function in your WHERE | Applied after the policy | Fewer rows, but the planner may lose a better plan |
The manual's guidance: policy expressions that consider only the current row are "the simplest and best-performing case". Measure with the lab rather than guessing; the right numbers are the ones from your table and your hardware.
Policy design patterns Good to know
In plain words: Beyond "tenant equals setting", real systems need admin access, soft deletes and users who belong to many tenants.
Common misunderstanding: "One policy fits every table." Join tables, reference tables and audit tables each need an explicit decision.
| Need | Pattern |
|---|---|
| Support staff read any tenant | A separate role support_ro with BYPASSRLS on a read-only replica, audited |
| User belongs to many tenants | Setting is a list: tenant_id = ANY (string_to_array(current_setting('app.tenant_ids', true), ',')) |
| Soft delete | AS RESTRICTIVE policy deleted_at IS NULL for the app role |
| Per-tenant database role | Policy USING (tenant_id = current_user), no setting needed |
| Reference data shared by all | No RLS on that table; keep it read-only for the app role |
Child table without tenant_id | Add the column anyway (denormalise) and give it a policy; a sub-select policy is slower |
Indexes, partitions and routing
Indexes lead with the tenant Must-know
In plain words: If every query is "my tenant's rows, then something", the index should start with the tenant so the database jumps straight to that tenant's slice.
Common misunderstanding: "An index on created_at is enough." Without tenant_id first it must scan across all tenants' dates and filter.
Definition: The PostgreSQL manual on multicolumn B-tree indexes says the index "is most efficient when there are constraints on the leading (leftmost) columns." An index on (tenant_id, created_at) lets a tenant's date-range query seek to its own rows. Citus makes the same point at the key level: its tutorial turns the primary key into the composite PRIMARY KEY (company_id, id), because what it needs is "to ensure uniqueness on a per-tenant basis." The ID strategy that goes with this is in ID Generation at Scale; the general rules in Indexing.
| Query | Index that serves it | Index that does not |
|---|---|---|
WHERE tenant_id = ? ORDER BY created_at DESC LIMIT 50 | (tenant_id, created_at) | (created_at) |
WHERE tenant_id = ? AND status = 'open' | (tenant_id, status) or partial WHERE status = 'open' | (status) alone |
| Unique email per tenant | UNIQUE (tenant_id, lower(email)) | UNIQUE (email) (global, leaks existence) |
Cross-tenant job (WHERE status = 'pending') | Separate (status) partial index | (tenant_id, status) (cannot skip the leading column efficiently) |
EXPLAIN on a 30 M row orders table, tenant acme has 2 000 rows
1 WHERE tenant_id = 'acme' AND created_at > now() - interval '7 days'
2 index (created_at) -> Index Scan reads 7 days of ALL tenants, filters to acme (many pages)
3 index (tenant_id, created_at) -> Index Scan reads only acme's last 7 days (few pages)Per-tenant partitioning (LIST) Important
In plain words: Give each big tenant its own physical piece of the table, so dropping or moving it is a metadata operation, not a giant DELETE.
Common misunderstanding: "Partition by tenant for speed." Partitioning is mostly an operations tool here (offboarding, per-tenant storage, VACUUM scope); with a good (tenant_id, ...) index the speed gain is small, and thousands of partitions raise planning time and memory.
CREATE TABLE orders (
tenant_id text NOT NULL,
id bigint GENERATED ALWAYS AS IDENTITY,
total_cents bigint NOT NULL,
PRIMARY KEY (tenant_id, id)
) PARTITION BY LIST (tenant_id);
CREATE TABLE orders_acme PARTITION OF orders FOR VALUES IN ('acme');
CREATE TABLE orders_default PARTITION OF orders DEFAULT; -- small tenants share this one
-- Offboard acme without a long DELETE:
ALTER TABLE orders DETACH PARTITION orders_acme CONCURRENTLY;
DROP TABLE orders_acme; -- or pg_dump it first and archive| Choice | Good for | Cost |
|---|---|---|
| LIST per large tenant + DEFAULT for the rest | A few giant tenants | Create the partition when a tenant crosses a threshold |
| LIST per tenant for all tenants | Hundreds of tenants, strict per-tenant offboarding | Thousands of partitions slow planning; RLS policies need care |
HASH on tenant_id | Spreading load evenly | No per-tenant drop |
RANGE on time, tenant_id leading index | Time-series with retention | Per-tenant drop needs DELETE |
Policies defined on the parent table apply when you query the parent; when a partition is queried directly, the partition's own policies are what count, so give the application role access to the parent only. (This is practitioner knowledge, not text I found in the pages I saved; confirm it on your version.) The primary key must include the partition key, which is why tenant_id already belongs in it. Full mechanics of declarative partitioning, pruning and sharding are in Partitioning & Sharding in PostgreSQL.
Connection routing per tenant Must-know
In plain words: Before the first query, something must decide "which connection serves this tenant".
Common misunderstanding: "One pool per tenant scales like one pool." With N tenants times a pool of ten, you may exceed what the server accepts long before CPU is a problem.
| Model | What the router does | Connection count |
|---|---|---|
| Shared schema | One pool; sets app.tenant_id per transaction | One pool |
| Schema per tenant | One pool; sets search_path per transaction | One pool |
| Database per tenant | Picks a pool by tenant from a directory; caps open pools (LRU) | Up to N pools; use PgBouncer per database, small max_open per pool |
| Hybrid | Directory gives pod and DSN; then one of the above | Per pod |
Database-per-tenant router with a cap of 3 open pools
1 request tenant a -> open pool a (open: a)
2 request tenant b -> open pool b (open: a, b)
3 request tenant c -> open pool c (open: a, b, c)
4 request tenant d -> evict LRU (a), open d (open: b, c, d)
5 request tenant a -> evict LRU (b), reopen aThe Go section has a runnable router with this LRU cap. In Laravel the same idea is a tenant connection whose database is switched when a tenant becomes current, as spatie/laravel-multitenancy does with SwitchTenantDatabaseTask.
Solving the classic problems: operations per tenant
Migrations across thousands of schemas or databases Must-know
In plain words: Changing the table layout is easy once; with 5 000 tenants it is 5 000 changes, and some will fail.
Common misunderstanding: "Loop over tenants in a deploy script." A long serial loop blocks the deploy, leaves half the fleet on the old shape when one tenant fails, and gives you no way to resume.
Azure's advice: "plan how to deploy schema updates across your estate" and "Track the schema version that you use for each tenant". A table in the control plane does that:
CREATE TABLE tenant_schema_version (
tenant_id text PRIMARY KEY,
version int NOT NULL,
state text NOT NULL DEFAULT 'ok', -- ok, migrating, failed
updated_at timestamptz NOT NULL DEFAULT now(),
last_error text
); Rolling migration to version 42
1 claim a batch: SELECT tenant_id FROM tenant_schema_version WHERE version < 42 AND state = 'ok'
ORDER BY tenant_id LIMIT 50 FOR UPDATE SKIP LOCKED
2 for each tenant, in a worker pool of 8:
3 SET lock_timeout = '3s'; BEGIN; <DDL>; UPDATE tenant_schema_version SET version = 42; COMMIT;
4 on failure: ROLLBACK; state = 'failed', last_error = ...; continue with the next tenant
5 canary first: run 5 chosen tenants, wait, watch errors, then the rest
6 app runs "version N and N+1" compatible during the rollout (expand, migrate, contract)| Model | How migrations run | Failure mode |
|---|---|---|
| Shared schema | One migration; one lock | One long lock blocks everyone |
| Schema per tenant | Loop over schemas, SET search_path per transaction | Partial rollout; schema drift between tenants |
| Database per tenant | Fan-out with a worker pool and a version table | Same plus N connections during the job |
| stancl/tenancy | Tenant migrations live in database/migrations/tenant and run per tenant database | Per-tenant failure handling is yours |
| spatie/laravel-multitenancy | php artisan tenants:artisan "migrate --database=tenant" loops tenants | Same |
DDL on a busy table needs ACCESS EXCLUSIVE; follow the expand and contract recipe in Zero-Downtime Schema Migrations per tenant, with lock_timeout so one busy tenant fails fast instead of queueing everyone behind it. At tens of thousands of schemas two other costs appear: pg_class and pg_attribute hold tenants x tables x columns rows, and pg_dump locks every table it dumps, so a full dump needs a large max_locks_per_transaction. If you expect that scale, prefer the shared model with partitions, or databases grouped into pods.
Backup and restore granularity Important
In plain words: "Restore customer X to yesterday" is trivial with a database per customer and painful with shared tables.
Common misunderstanding: "Point-in-time recovery solves it." PITR restores the whole cluster to a moment. To bring back one tenant you restore to a side database and copy that tenant's rows over, in a shared design.
Azure puts it this way: "restoring a single tenant might require you to restore the database to a separate resource and selectively recover that tenant's data."
| Model | Restore one tenant | Backup unit |
|---|---|---|
| Shared schema | PITR to a side instance, then COPY (SELECT ... WHERE tenant_id = ...) and merge | The whole database |
| Schema per tenant | pg_dump -n tenant_acme for logical backup; PITR to side instance for a moment in time | Whole cluster (physical), schema (logical) |
| Database per tenant | pg_dump or PITR of that one database (per-database cluster for PITR) | A database or a cluster |
| Dedicated server per tenant | Normal PITR | A server |
Customer asks: "undo yesterday's mass delete" (shared schema)
1 PITR a copy of the cluster to 2026-11-24 09:00 as side instance
2 COPY (SELECT * FROM orders WHERE tenant_id = 'acme' AND ...) TO file -- on the side instance
3 review the diff with the customer's admin
4 in production: INSERT ... ON CONFLICT DO NOTHING from the file, inside the tenant's RLS contextTest the restore path before you need it. A per-tenant restore procedure that has never run is a hope.
Tenant offboarding, data export and GDPR Must-know
In plain words: When a customer leaves, you must hand over their data on request and then really delete it, including from places you forgot.
Common misunderstanding: "DELETE FROM ... WHERE tenant_id = ? finishes the job." Rows survive in backups, replicas, logs, caches, search indexes, object storage and the warehouse, and a huge DELETE bloats the table and holds locks.
GDPR Article 17 says "The data subject shall have the right to obtain from the controller the erasure of personal data concerning him or her without undue delay". The regulation says what must happen, not how a database does it; your design decides how hard it is. Talk to your legal contact for the real deadlines and exceptions; the table below is engineering only.
Offboarding tenant acme
1 contract ends -> state = 'suspended' (read-only, logins refused)
2 export: COPY per table WHERE tenant_id = 'acme' -> files -> encrypted archive -> customer
3 retention window (for example 30 days) for disputes and chargebacks
4 delete in batches: DELETE ... WHERE ctid IN (SELECT ctid ... LIMIT 5000), repeat, VACUUM
(or DETACH PARTITION + DROP, or DROP SCHEMA ... CASCADE, or DROP DATABASE)
5 purge caches (key prefix t:acme:*), search index, object storage, queue messages, warehouse rows
6 backups: wait for the retention cycle, or crypto-shred (delete the tenant's data key)
7 record the deletion in an audit log that holds no personal data| Model | Fast delete | Export |
|---|---|---|
| Shared schema | Batched DELETE plus VACUUM; or LIST partition drop | COPY per table filtered by tenant |
| Schema per tenant | DROP SCHEMA tenant_acme CASCADE | pg_dump -n |
| Database per tenant | DROP DATABASE | pg_dump |
| Per-tenant data key | Delete the key (crypto-shredding) makes backups unreadable | Decrypt, then export |
Crypto-shredding needs per-tenant keys; see Roles and encryption per tenant and Encryption at Rest, in Transit & in Use.
Tenant-aware caching Important
In plain words: If two tenants can produce the same cache key, one will read the other's data from the cache.
Common misunderstanding: "RLS protects the cache too." RLS lives in PostgreSQL. A value stored in Redis, Memcached or an HTTP cache under a key without a tenant is outside every policy.
Cache key bug
1 tenant acme : GET /settings -> cache key "settings" -> stored
2 tenant globex: GET /settings -> cache key "settings" -> HIT: globex receives acme's settings
3 fix: key = t:<tenant>:settings, built by one function that throws if no tenant is set| Where | Rule |
|---|---|
| Application cache (Redis, Memcached) | Prefix every key with the tenant; build keys in one helper; the Go helper is in quota.CacheKey, the Laravel one is TenantCache |
| HTTP or CDN cache | Vary on the tenant header or host; never cache authenticated tenant responses on a shared key |
| Redis ACL | ~t:acme:* key patterns in an ACL user for a dedicated cache user per tenant tier |
| Memoised values in a long-lived worker (Octane, Swoole, Go globals) | Reset per request; spatie's docs include a page on Octane for this reason |
Spatie PrefixCacheTask | Prefixes the cache for the current tenant when listed in switch_tenant_tasks |
Tenant quotas and rate limits Important
In plain words: A limit per tenant keeps one customer from using more than its plan allows, and keeps the others safe.
Common misunderstanding: "A global rate limit protects tenants from each other." A global limit is exhausted by the loudest tenant first. The limit key must be the tenant.
| What to limit | Mechanism |
|---|---|
| Requests per second | Token bucket per tenant (Go quota.Limiter, Laravel RateLimiter::for(...)->by($tenantId)) |
| Concurrent queries or exports | Semaphore per tenant |
| Rows or storage | Metered counters, pg_total_relation_size for dedicated tables, quota check on write |
| Background jobs | One queue per tier; per-tenant concurrency |
| Database time | statement_timeout per role; pg_stat_statements grouped by a tenant tag in the query comment |
Laravel's routing documentation shows RateLimiter::for('api', ...) returning Limit::perMinute(60)->by(...); passing the tenant (or user) as the key makes the limit per tenant.
Cross-tenant analytics Good to know
In plain words: Customers see their own data; you, the vendor, often want totals across all of them.
Common misunderstanding: "Run a BYPASSRLS query on the primary." That puts your reporting load on the same database as every tenant's checkout, and it is the exact credential you wanted to keep out of the app.
| Approach | When | Cost |
|---|---|---|
Read replica + BYPASSRLS reporting role | Occasional internal queries | Replica lag; the role is powerful |
| Warehouse / columnar store fed by CDC | Product analytics, billing | Pipeline to run; see OLTP vs OLAP & Columnar Storage |
| Materialised per-tenant aggregates | Dashboards | Refresh logic |
Fan-out query (postgres_fdw, app loop) over tenant databases | Database per tenant, few tenants | Slow at thousands of tenants |
| Citus distributed query | Distributed shared schema | Cross-shard queries are costlier than tenant-local ones |
Keep customer-facing analytics (inside RLS) and internal analytics (outside RLS) as different paths with different credentials.
Sharding by tenant
Citus: distribute by tenant_id Important
In plain words: Citus splits tables across servers by the tenant column, so each tenant's data lives together on one node.
Common misunderstanding: "Distribute by primary key." In a multi-tenant app the distribution column should be the tenant, so joins and transactions for one tenant stay on one shard.
Definition: Citus's guide says "every table in our schema has a column to clearly mark which tenant owns which rows" and that "it can be useful to denormalize tables with the addition of company id, whether it be for row-level security or for additional indexing." Primary and foreign keys include that column so checks run on one node.
-- Citus, as in its multi-tenant guide (tenant column: company_id)
SELECT create_distributed_table('companies', 'id');
SELECT create_distributed_table('campaigns', 'company_id');
SELECT create_distributed_table('clicks', 'company_id');
SELECT create_reference_table('geo_ips'); -- small lookup table copied to every node| Citus feature | What it does |
|---|---|
create_distributed_table(t, col) | Shards table t by col; same value means same shard |
| Co-location | Tables distributed on the same column keep a tenant's rows together, so tenant joins are local |
create_reference_table | Replicates a small table to every worker |
citus_rebalance_start() | Moves shards when you add nodes; the guide says Community edition 11.0 and above avoids downtime during rebalancing |
isolate_tenant_to_new_shard(...) | Gives one large tenant its own shard so it can be moved to a node of its own |
Tenant sharding and rebalancing Important
In plain words: When one server is not enough, assign groups of tenants to servers, and move a tenant when a server gets crowded.
Common misunderstanding: "Hash the tenant id and forget it." Hash placement balances counts, not size; one giant tenant makes one shard hot and hash placement cannot move it. A directory (tenant to shard) can.
| Placement | How | Rebalance | Notes |
|---|---|---|---|
| Directory (lookup) | Control-plane table tenant -> shard | Move one tenant, update one row | Flexible; the directory is a critical dependency |
| Hash / consistent hash | hash(tenant_id) picks a shard | Moves many tenants at once | See Consistent Hashing |
| Range | Tenant id ranges per shard | Split ranges | Hot ranges possible |
| Citus shards | Hash shards, isolate_tenant_to_new_shard for outliers | citus_rebalance_start | Managed by the extension |
Move tenant acme from shard 1 to shard 2 (directory model, PostgreSQL logical replication)
1 on shard 2: create the schema; CREATE SUBSCRIPTION ... (publication filters rows WHERE tenant_id = 'acme', PostgreSQL 15+)
2 wait for the initial copy and for lag < 1 s
3 directory: acme.state = 'moving'; routers hold new writes for acme (seconds)
4 wait for lag = 0; verify row counts and a checksum per table
5 directory: acme.shard = 2, state = 'active'; routers reload (cache TTL)
6 drop the subscription; after a grace period delete acme's rows on shard 1Partitioning & Sharding in PostgreSQL covers shard keys and Citus; Storage & Data Scaling covers when to shard at all.
What each product offers
MySQL, SQL Server, Oracle, MongoDB and others Important
In plain words: PostgreSQL has the most direct tool (RLS). Others reach the same goal with different mechanisms, or leave it to the application.
Common misunderstanding: "All databases have row-level security." MySQL and MariaDB do not.
| Product | Native row-level filter | What to do instead or additionally |
|---|---|---|
| PostgreSQL | Yes: CREATE POLICY (since 9.5) | Schemas, roles, partitions, Citus |
| MySQL / InnoDB | No | Views over tables with SQL SECURITY DEFINER filtered by a function that reads a session variable or CURRENT_USER(), per-tenant accounts, or enforcement in the application; separate databases per tenant are straightforward |
| MariaDB | No | Same as MySQL |
| SQL Server | Yes: CREATE SECURITY POLICY with filter and block predicates | SESSION_CONTEXT for the tenant; elastic pools for database per tenant |
| Oracle | Yes: Virtual Private Database (DBMS_RLS) | Pluggable databases per tenant |
| SQLite | No | One database file per tenant is natural |
| MongoDB | No | Database or collection per tenant, or a tenantId field enforced by the application |
| CockroachDB | Check your version's docs for RLS support | Multi-region tables, partitioning by tenant |
| Redis | No | Key prefix, ACL key patterns, separate instance for a strict tenant |
MySQL note: a view definition cannot refer to a user variable directly (error 1351), so the usual workaround is a stored function that reads the variable and is called from the view. This is practitioner knowledge, not something this page's sources show; test it on your version.
SQL Server example. Microsoft's row-level security page has a middle-tier example in which tenants share one SQL user and the application passes the identity in SESSION_CONTEXT. This sketch follows that pattern with a tenant id (the names are mine):
CREATE FUNCTION Security.tenant_predicate(@TenantId int)
RETURNS TABLE WITH SCHEMABINDING
AS RETURN SELECT 1 AS ok
WHERE @TenantId = CAST(SESSION_CONTEXT(N'TenantId') AS int);
CREATE SECURITY POLICY Security.tenant_filter
ADD FILTER PREDICATE Security.tenant_predicate(TenantId) ON dbo.Orders,
ADD BLOCK PREDICATE Security.tenant_predicate(TenantId) ON dbo.Orders AFTER INSERT
WITH (STATE = ON);
-- application, once per connection or request:
EXEC sp_set_session_context @key = N'TenantId', @value = 42, @read_only = 1;Filter predicates silently hide rows for reads, updates and deletes; block predicates stop writes that violate the rule. @read_only = 1 stops later code from changing the value on that connection.
Roles and encryption per tenant
Postgres roles per tenant Good to know
In plain words: Instead of one shared application login that is told which tenant it is, each tenant gets its own database login.
Common misunderstanding: "More roles is always safer." Thousands of roles cost catalog space and make pooling harder, because each role needs its own pool.
| Design | Mechanics | Fit |
|---|---|---|
One app role + set_config | Policy reads a setting | Many small tenants, one pool |
Role per tenant + policy on current_user | CREATE POLICY ... USING (tenant_id = current_user); app connects as the tenant role | Dozens to hundreds of tenants; strong credentials |
| Role per tenant, schema per tenant | ALTER ROLE tenant_acme SET search_path = tenant_acme; GRANT USAGE ON SCHEMA tenant_acme TO tenant_acme | Schema model with per-tenant grants |
| Database per tenant + role per tenant | REVOKE CONNECT ON DATABASE ... FROM PUBLIC, grant to one role | Strongest at the connection layer |
CREATE ROLE tenant_acme LOGIN PASSWORD '...' CONNECTION LIMIT 20;
CREATE SCHEMA tenant_acme AUTHORIZATION tenant_acme;
ALTER ROLE tenant_acme SET search_path = tenant_acme;
ALTER ROLE tenant_acme SET statement_timeout = '10s';
REVOKE ALL ON SCHEMA public FROM tenant_acme;Least privilege, authentication and auditing are covered in Database Security.
Encryption per tenant Good to know
In plain words: Give each tenant its own encryption key. Deleting the key then makes that tenant's data unreadable, backups included.
Common misunderstanding: "Disk encryption already gives per-tenant encryption." Disk or TDE encryption uses one key for everything; per-tenant keys need column or application-side encryption.
| Layer | Per-tenant key? | Use |
|---|---|---|
| Disk or TDE | No (one key per volume or database) | Stolen disks |
| Database per tenant + TDE | Yes, if each database has its own key | Compliance by tenant |
| Column encryption (pgcrypto) | Possible, key from the application | Searchable only with deterministic modes |
| Application envelope encryption with KMS | Yes: a data key per tenant, wrapped by a KMS key | BYOK, crypto-shredding |
Details of envelope encryption, deterministic versus randomised modes and homomorphic options are in Encryption at Rest, in Transit & in Use. The stancl/tenancy documentation lists a "Tenant attribute encryption" page for encrypting tenant model attributes; read it before relying on it for data columns.
Go
Before
The ListOrders handler adds the tenant predicate by hand. ListInvoices, added later, does not. Nothing in the compiler, the schema or the connection tells the two apart.
// Package before shows tenant isolation done by hand. Every query has to
// remember its own tenant_id predicate, and one handler forgets it.
package before
import (
"database/sql"
"encoding/json"
"net/http"
)
type Handlers struct {
DB *sql.DB
}
// ListOrders adds the tenant filter by hand. It is correct today.
func (h Handlers) ListOrders(w http.ResponseWriter, r *http.Request) {
tenant := r.Header.Get("X-Tenant-ID")
rows, err := h.DB.QueryContext(r.Context(),
`SELECT id, total_cents FROM orders WHERE tenant_id = $1 ORDER BY id LIMIT 100`,
tenant)
writePairs(w, rows, err)
}
// ListInvoices was added later by another developer. It forgets the WHERE
// clause, so every tenant receives every other tenant's invoices. Nothing in
// the compiler, the schema or the database stops it.
func (h Handlers) ListInvoices(w http.ResponseWriter, r *http.Request) {
rows, err := h.DB.QueryContext(r.Context(),
`SELECT id, amount_cents FROM invoices ORDER BY id LIMIT 100`)
writePairs(w, rows, err)
}
func writePairs(w http.ResponseWriter, rows *sql.Rows, err error) {
if err != nil {
http.Error(w, "query failed", http.StatusInternalServerError)
return
}
defer rows.Close()
type pair struct {
ID int64 `json:"id"`
Value int64 `json:"value"`
}
var out []pair
for rows.Next() {
var p pair
if err := rows.Scan(&p.ID, &p.Value); err != nil {
http.Error(w, "scan failed", http.StatusInternalServerError)
return
}
out = append(out, p)
}
if err := rows.Err(); err != nil {
http.Error(w, "read failed", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(out)
}After
The middleware opens a transaction and sets app.tenant_id for it only. Handlers read from the transaction in the request context and never mention tenant_id. The policy SQL sits in the package comment, because it belongs to the schema, not to the handler.
// Package after moves tenant isolation into PostgreSQL. The middleware opens a
// transaction and sets app.tenant_id for that transaction only. Row-Level
// Security policies on each table then decide which rows are visible, so
// handlers never write a tenant_id predicate.
//
// Policy SQL, run once per table by the table owner:
//
// ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
// ALTER TABLE orders FORCE ROW LEVEL SECURITY;
// CREATE POLICY tenant_isolation ON orders
// USING (tenant_id = current_setting('app.tenant_id', true))
// WITH CHECK (tenant_id = current_setting('app.tenant_id', true));
//
// The second argument of current_setting is missing_ok. When the setting is
// unset it returns NULL, and a NULL comparison hides every row. The
// application must connect as a role that is not the table owner, or use FORCE
// as above, because owners bypass RLS by default.
package after
import (
"context"
"database/sql"
"net/http"
)
type ctxKey struct{}
// TxFrom returns the tenant-scoped transaction placed on the request context
// by Tenant. Handlers must use it instead of the *sql.DB.
func TxFrom(ctx context.Context) (*sql.Tx, bool) {
tx, ok := ctx.Value(ctxKey{}).(*sql.Tx)
return tx, ok
}
// statusWriter records the status code so the middleware can roll back when
// a handler fails.
type statusWriter struct {
http.ResponseWriter
status int
}
func (s *statusWriter) WriteHeader(code int) {
if s.status == 0 {
s.status = code
}
s.ResponseWriter.WriteHeader(code)
}
func (s *statusWriter) Write(b []byte) (int, error) {
if s.status == 0 {
s.status = http.StatusOK
}
return s.ResponseWriter.Write(b)
}
// Tenant returns middleware that runs the wrapped handler inside a transaction
// in which app.tenant_id is set. The tenant comes from a header only to keep
// the example short. In production it must come from verified credentials.
func Tenant(db *sql.DB) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tenantID := r.Header.Get("X-Tenant-ID")
if tenantID == "" {
http.Error(w, "missing tenant", http.StatusBadRequest)
return
}
tx, err := db.BeginTx(r.Context(), nil)
if err != nil {
http.Error(w, "database unavailable", http.StatusServiceUnavailable)
return
}
// Rollback after a successful Commit returns sql.ErrTxDone, which is
// harmless. It also covers panics and early returns.
defer tx.Rollback()
// SET LOCAL cannot take a bind parameter, so it cannot receive the
// tenant ID safely. set_config is the function form of SET; with
// is_local = true it lasts only until COMMIT or ROLLBACK.
if _, err := tx.ExecContext(r.Context(),
`SELECT set_config('app.tenant_id', $1, true)`, tenantID); err != nil {
http.Error(w, "tenant setup failed", http.StatusInternalServerError)
return
}
sw := &statusWriter{ResponseWriter: w}
next.ServeHTTP(sw, r.WithContext(context.WithValue(r.Context(), ctxKey{}, tx)))
// Commit only when the handler did not fail. The status is already
// on the wire, so a rollback is the only way to keep writes out.
if sw.status >= http.StatusInternalServerError {
return
}
_ = tx.Commit()
})
}
}The handler is short because the database does the filtering:
package after
import (
"encoding/json"
"net/http"
)
// ListOrders contains no tenant predicate. The RLS policy on orders adds one
// inside the database, and a forgotten WHERE clause here cannot leak rows.
func ListOrders(w http.ResponseWriter, r *http.Request) {
tx, ok := TxFrom(r.Context())
if !ok {
http.Error(w, "no tenant transaction", http.StatusInternalServerError)
return
}
rows, err := tx.QueryContext(r.Context(),
`SELECT id, total_cents FROM orders ORDER BY id LIMIT 100`)
if err != nil {
http.Error(w, "query failed", http.StatusInternalServerError)
return
}
defer rows.Close()
type pair struct {
ID int64 `json:"id"`
Value int64 `json:"value"`
}
var out []pair
for rows.Next() {
var p pair
if err := rows.Scan(&p.ID, &p.Value); err != nil {
http.Error(w, "scan failed", http.StatusInternalServerError)
return
}
out = append(out, p)
}
if err := rows.Err(); err != nil {
http.Error(w, "read failed", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(out)
}Database per tenant: a capped pool router
For the database-per-tenant model, a router maps a tenant to a pool and closes the least recently used pool when the cap is reached. Resolving the DSN and opening the pool happen outside the lock.
// Package router maps a tenant to its own *sql.DB pool for the
// database-per-tenant model. The number of open pools is capped, because every
// pool holds server connections and N tenants times a pool of ten can exceed
// max_connections on the server long before the application runs out of CPU.
package router
import (
"container/list"
"context"
"database/sql"
"errors"
"sync"
"time"
)
// ErrUnknownTenant is returned when the directory has no entry for the tenant.
var ErrUnknownTenant = errors.New("router: unknown tenant")
// Directory resolves a tenant to a DSN. In production this is the control-plane
// database (the "landlord"), usually cached with a short TTL.
type Directory interface {
DSN(ctx context.Context, tenantID string) (string, error)
}
// Opener opens a pool for a DSN. It is a parameter so a test can pass a fake.
type Opener func(dsn string) (*sql.DB, error)
type entry struct {
tenant string
db *sql.DB
}
// Router keeps at most max pools open and closes the least recently used one
// when a new tenant needs room.
type Router struct {
dir Directory
open Opener
max int
perMax int
mu sync.Mutex
pools map[string]*list.Element
lru *list.List
}
// New returns a Router. perPool caps open connections inside each pool.
func New(dir Directory, open Opener, maxPools, perPool int) *Router {
return &Router{
dir: dir,
open: open,
max: maxPools,
perMax: perPool,
pools: make(map[string]*list.Element),
lru: list.New(),
}
}
// DB returns the pool for the tenant, opening it on first use.
func (r *Router) DB(ctx context.Context, tenantID string) (*sql.DB, error) {
r.mu.Lock()
if el, ok := r.pools[tenantID]; ok {
r.lru.MoveToFront(el)
db := el.Value.(*entry).db
r.mu.Unlock()
return db, nil
}
r.mu.Unlock()
// Resolve and open outside the lock; both can be slow.
dsn, err := r.dir.DSN(ctx, tenantID)
if err != nil {
return nil, err
}
db, err := r.open(dsn)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(r.perMax)
db.SetMaxIdleConns(1)
db.SetConnMaxIdleTime(5 * time.Minute)
r.mu.Lock()
defer r.mu.Unlock()
// Another goroutine may have opened the same tenant meanwhile.
if el, ok := r.pools[tenantID]; ok {
_ = db.Close()
r.lru.MoveToFront(el)
return el.Value.(*entry).db, nil
}
r.pools[tenantID] = r.lru.PushFront(&entry{tenant: tenantID, db: db})
for r.lru.Len() > r.max {
last := r.lru.Back()
old := last.Value.(*entry)
r.lru.Remove(last)
delete(r.pools, old.tenant)
// Close waits for in-flight queries on that pool to finish.
go func() { _ = old.db.Close() }()
}
return db, nil
}
// Close closes every pool.
func (r *Router) Close() {
r.mu.Lock()
defer r.mu.Unlock()
for _, el := range r.pools {
_ = el.Value.(*entry).db.Close()
}
r.pools = make(map[string]*list.Element)
r.lru.Init()
}Quotas and tenant-aware cache keys
// Package quota holds two small tenant-aware helpers: a per-tenant rate
// limiter (token bucket) and a cache-key builder that cannot forget the tenant.
package quota
import (
"strings"
"sync"
"time"
)
// Limiter is a token bucket per tenant. A big tenant exhausts its own bucket,
// not the shared one, which is the cheapest defence against a noisy neighbour
// at the application layer.
type Limiter struct {
rate float64 // tokens added per second
burst float64 // bucket size
mu sync.Mutex
buckets map[string]*bucket
now func() time.Time
}
type bucket struct {
tokens float64
last time.Time
}
// NewLimiter allows rate requests per second per tenant with bursts up to burst.
func NewLimiter(rate, burst float64) *Limiter {
return &Limiter{rate: rate, burst: burst, buckets: make(map[string]*bucket), now: time.Now}
}
// Allow reports whether the tenant may proceed and consumes one token if so.
func (l *Limiter) Allow(tenantID string) bool {
l.mu.Lock()
defer l.mu.Unlock()
now := l.now()
b, ok := l.buckets[tenantID]
if !ok {
b = &bucket{tokens: l.burst, last: now}
l.buckets[tenantID] = b
}
b.tokens += now.Sub(b.last).Seconds() * l.rate
if b.tokens > l.burst {
b.tokens = l.burst
}
b.last = now
if b.tokens < 1 {
return false
}
b.tokens--
return true
}
// CacheKey builds "t:<tenant>:<parts...>". Every cache read and write goes
// through it, so a key without a tenant cannot be constructed. Colons in the
// parts are escaped so tenant "a" key "b:c" never collides with tenant "a:b" key "c".
func CacheKey(tenantID string, parts ...string) string {
esc := strings.NewReplacer(`\`, `\\`, ":", `\:`)
var sb strings.Builder
sb.WriteString("t:")
sb.WriteString(esc.Replace(tenantID))
for _, p := range parts {
sb.WriteByte(':')
sb.WriteString(esc.Replace(p))
}
return sb.String()
}The Go angle
The standard library gives you everything except the policy. database/sql describes DB as "a database handle representing a pool of zero or more underlying connections", so the middleware must not use the handle for tenant queries, or a query could run on a connection that was never given a tenant. *sql.Tx is the unit that carries the setting. BeginTx takes the request context, and the manual says "The provided context is used until the transaction is committed or rolled back."
The middleware uses set_config with a placeholder because SET does not take one: the SET grammar accepts constants and identifiers, not bind parameters. set_config is documented as corresponding "to the SQL command SET" and takes its value as an argument. A ctxKey unexported type keeps the transaction out of other packages' reach. The Tenant middleware rolls back on a 5xx response, because http.ResponseWriter cannot take back a status once it has been sent.
| Go decision | Why |
|---|---|
One *sql.Tx per request on the context | Keeps set_config(..., true) and every query on one connection |
SELECT set_config($1...) not SET LOCAL | SET cannot bind parameters |
Handlers receive *sql.Tx, not *sql.DB | A bare DB could take a connection with no tenant |
| Router with an LRU cap | Open pools are connections you pay for |
quota.CacheKey | A key without a tenant cannot be built |
Laravel
Before
OrderController::index adds the tenant predicate by hand, and show does not. The second method returns any tenant's order to any authenticated user who guesses the id.
<?php
// app/Http/Controllers/OrderController.php, before tenancy was enforced.
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final class OrderController extends Controller
{
// Correct only while every developer remembers the tenant predicate.
public function index(Request $request): JsonResponse
{
$tenantId = $request->user()->tenant_id;
return response()->json(
Order::where('tenant_id', $tenantId)->latest('id')->limit(100)->get()
);
}
// Written later without the predicate. Any authenticated user can read any
// tenant's order by guessing its id, and no test in the codebase notices.
public function show(int $order): JsonResponse
{
return response()->json(Order::findOrFail($order));
}
}After
Three pieces. A trait adds the tenant scope and sets tenant_id on create. A middleware resolves the tenant from the subdomain and wraps the request in a transaction in which set_config is called. The controller then has no tenant code at all.
The trait:
<?php
// app/Models/Concerns/BelongsToTenant.php
//
// Usage on any model that holds tenant data:
//
// final class Order extends Model
// {
// use BelongsToTenant;
// }
namespace App\Models\Concerns;
use App\Models\Tenant;
use App\Tenancy\CurrentTenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
trait BelongsToTenant
{
// Laravel calls boot{TraitName} for each trait a model uses. The Eloquent
// documentation does not describe this convention, so treat it as framework
// behaviour that could change.
protected static function bootBelongsToTenant(): void
{
// Global scope: every query on the model gets WHERE tenant_id = current.
// It fails closed, because CurrentTenant::id() throws when no tenant is set.
static::addGlobalScope('tenant', function (Builder $builder): void {
$builder->where(
$builder->getModel()->qualifyColumn('tenant_id'),
app(CurrentTenant::class)->id(),
);
});
// Creating hook: always overwrite tenant_id, so a client that sends its
// own tenant_id in the request cannot write into another tenant.
static::creating(function (Model $model): void {
$model->setAttribute('tenant_id', app(CurrentTenant::class)->id());
});
}
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
}The current-tenant holder, registered as a singleton:
<?php
// app/Tenancy/CurrentTenant.php
//
// Register it as a singleton so the middleware and the global scope share one
// instance: $this->app->singleton(CurrentTenant::class);
namespace App\Tenancy;
use App\Models\Tenant;
use RuntimeException;
final class CurrentTenant
{
private ?Tenant $tenant = null;
public function set(Tenant $tenant): void
{
$this->tenant = $tenant;
}
public function id(): string
{
if ($this->tenant === null) {
throw new RuntimeException('No tenant resolved. Refusing to run a tenant-scoped query.');
}
return (string) $this->tenant->getKey();
}
}The middleware:
<?php
// app/Http/Middleware/ResolveTenant.php
//
// Attach it to the tenant route group only. Central routes (sign-up, billing)
// must not use it.
namespace App\Http\Middleware;
use App\Models\Tenant;
use App\Tenancy\CurrentTenant;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;
final class ResolveTenant
{
public function __construct(private CurrentTenant $current) {}
public function handle(Request $request, Closure $next): Response
{
// acme.app.example.com -> acme. An unknown subdomain gives a 404.
$subdomain = explode('.', $request->getHost())[0];
$tenant = Tenant::query()->where('subdomain', $subdomain)->firstOrFail();
$this->current->set($tenant);
// The whole request runs in one transaction, so the RLS policies see the
// setting. set_config(..., true) is SET LOCAL with a bound value. Its
// effect ends at COMMIT or ROLLBACK, so the next request that reuses this
// pooled connection starts with no tenant set.
return DB::transaction(function () use ($request, $next, $tenant): Response {
DB::select("SELECT set_config('app.tenant_id', ?, true)", [(string) $tenant->getKey()]);
return $next($request);
});
}
}The controller:
<?php
// app/Http/Controllers/OrderController.php, after tenancy was enforced.
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
final class OrderController extends Controller
{
public function index(): JsonResponse
{
// No tenant predicate here. The BelongsToTenant global scope adds one,
// and the RLS policy checks it again in PostgreSQL.
return response()->json(
Order::query()->latest('id')->limit(100)->get()
);
}
// A foreign id raises ModelNotFoundException, which Laravel renders as a 404.
public function show(int $order): JsonResponse
{
return response()->json(Order::query()->findOrFail($order));
}
}Tenant-aware cache
<?php
// app/Tenancy/TenantCache.php
//
// Every tenant-owned cache entry goes through this class, so a key without a
// tenant cannot be built by accident. Use a Redis or Memcached store; the same
// prefix rule applies to any shared cache.
namespace App\Tenancy;
use Closure;
use Illuminate\Support\Facades\Cache;
final class TenantCache
{
public function __construct(private CurrentTenant $current) {}
public function key(string $name): string
{
// CurrentTenant::id() throws when no tenant is set, so this fails closed.
return 't:' . $this->current->id() . ':' . $name;
}
// Cache::remember(key, ttl, callback) is the documented read-through helper.
public function remember(string $name, int $seconds, Closure $callback): mixed
{
return Cache::remember($this->key($name), $seconds, $callback);
}
public function forget(string $name): bool
{
return Cache::forget($this->key($name));
}
}The Laravel angle
Global scopes are the Laravel feature for this. The Eloquent documentation says "Global scopes allow you to add constraints to all queries for a given model," and it allows closures as well as classes. The trait uses a closure, so the tenant is read when the query runs, not when the model boots. The scope fails closed because CurrentTenant::id() throws when no tenant has been set.
The creating event is documented as: "When a new model is saved for the first time, the creating and created events will dispatch." The trait always overwrites tenant_id there, so the client cannot choose another tenant. The trait uses a closure on the model event; the Observers feature is an equivalent place to put the same hook.
DB::transaction and DB::select are the documented way to run the set_config call on the same connection as the controller's queries. Subdomain routing (Route::domain('{account}.example.com')) is the route-level alternative to parsing the host in middleware, and the docs say subdomains "may be assigned route parameters just like route URIs".
Packages: stancl/tenancy and spatie/laravel-multitenancy
Two community packages cover the same ground with more machinery. stancl/tenancy (the Composer package; its GitHub repository is archtechx/tenancy) names two types, "single-database tenancy" and "multi-database tenancy", and says it "focuses more on multi-database tenancy". Its introduction also notes that for simple per-user scoping "there's no need to use a multi-tenancy package". spatie/laravel-multitenancy is more minimal: its introduction says "The philosophy of this package is that it should only provide the bare essentials to enable multitenancy." It "works for multitenancy projects that need to use one or multiple databases."
| Aspect | stancl/tenancy 3.x | spatie/laravel-multitenancy 4.x |
|---|---|---|
| Install | composer require stancl/tenancy, php artisan tenancy:install, php artisan migrate | composer require spatie/laravel-multitenancy, publish the config |
| Requires | Laravel 9 or higher (installation page) | PHP 8.3+ and Laravel 12 or 13 |
| Identification | Middleware: InitializeTenancyByDomain, ...BySubdomain, ...ByPath, ...ByRequestData | A TenantFinder class in tenant_finder; NeedsTenant middleware |
| Single database | BelongsToTenant trait on models; DB facade queries are not scoped; withoutTenancy() to bypass | Tenants table plus your own scoping; the package does not scope queries for you |
| Multi-database | HasDatabase, HasDomains, creates and migrates databases via a JobPipeline | Two connections (landlord, tenant) and SwitchTenantDatabaseTask; you create databases yourself |
| Migrations | database/migrations/tenant, run per tenant | php artisan tenants:artisan "migrate --database=tenant" |
| Queues | Queue bootstrapper (queues page in its docs) | queues_are_tenant_aware_by_default stores the tenant on jobs; the TenantAware and NotTenantAware interfaces override it per job |
| Cache | Cache tenancy bootstrapper (tenancy bootstrappers page) | PrefixCacheTask |
| Fan-out helper | Tenant::all()->runForEach(fn) | tenants:artisan, Tenant::current(), makeCurrent(), forgetCurrent() |
<?php
// stancl/tenancy 3.x, shown against the pages cited in the references:
// the Quickstart (multi-database mode) and Single-database tenancy.
//
// Setup, from the Quickstart:
// composer require stancl/tenancy
// php artisan tenancy:install // creates migrations, config, routes/tenant.php, a service provider
// php artisan migrate
// Register App\Providers\TenancyServiceProvider in bootstrap/providers.php and set
// 'tenant_model' => \App\Models\Tenant::class in config/tenancy.php.
namespace App\Models;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\Concerns\BelongsToTenant;
use Stancl\Tenancy\Database\Concerns\HasDatabase;
use Stancl\Tenancy\Database\Concerns\HasDomains;
use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;
use Illuminate\Database\Eloquent\Model;
// Multi-database mode: one database per tenant, created and migrated by the
// package's JobPipeline when a tenant is created.
class Tenant extends BaseTenant implements TenantWithDatabase
{
use HasDatabase, HasDomains;
}
// Single-database mode: the same package, a tenant_id column and a global scope.
// Direct DB:: queries are NOT scoped, as the package documentation warns.
class Invoice extends Model
{
use BelongsToTenant;
}
// routes/tenant.php (tenant routes are reachable only on tenant domains):
//
// Route::middleware([
// 'web',
// InitializeTenancyByDomain::class,
// PreventAccessFromCentralDomains::class,
// ])->group(function () {
// Route::get('/', fn () => 'Tenant id: ' . tenant('id'));
// });
//
// Other identification middleware named in the docs: InitializeTenancyBySubdomain,
// InitializeTenancyByDomainOrSubdomain, InitializeTenancyByPath and
// InitializeTenancyByRequestData.
// Provisioning and fan-out, as in the Quickstart (run from tinker or a command):
//
// $tenant = Tenant::create(['id' => 'acme']);
// $tenant->domains()->create(['domain' => 'acme.localhost']);
//
// // Run a closure inside every tenant's database, one after another.
// Tenant::all()->runForEach(function () {
// // here the default connection points at the current tenant's database
// });
//
// Tenant migrations live in database/migrations/tenant. To bypass the scope on
// purpose in single-database mode, add ->withoutTenancy() to the query.<?php
// spatie/laravel-multitenancy v4 (requires PHP 8.3+ and Laravel 12 or 13).
// Everything below is taken from the package's own installation and basic-usage
// pages. The package is deliberately small: it finds the current tenant and runs
// "tasks" when a tenant becomes current. It does not create databases for you.
//
// composer require spatie/laravel-multitenancy
// php artisan vendor:publish --provider="Spatie\Multitenancy\MultitenancyServiceProvider" --tag="multitenancy-config"
use Spatie\Multitenancy\Models\Tenant;
// config/multitenancy.php, multi-database mode. Two connections are needed:
// "landlord" (holds the tenants table) and "tenant" (database set to null in
// config/database.php, filled in by the task below).
return [
'tenant_finder' => App\Tenancy\HostTenantFinder::class, // extends Spatie\Multitenancy\TenantFinder\TenantFinder
'switch_tenant_tasks' => [
Spatie\Multitenancy\Tasks\SwitchTenantDatabaseTask::class,
Spatie\Multitenancy\Tasks\PrefixCacheTask::class, // tenant-aware cache keys
],
'tenant_database_connection_name' => 'tenant',
'landlord_database_connection_name' => 'landlord',
'queues_are_tenant_aware_by_default' => true, // jobs remember their tenant
];
// Working with the current tenant (documented API):
//
// Tenant::current(); // current tenant or null
// Tenant::checkCurrent(); // bool
// $tenant->makeCurrent(); // runs every switch_tenant_tasks task
// Tenant::forgetCurrent();
//
// Route protection (bootstrap/app.php): the docs say to put NeedsTenant first,
// then EnsureValidTenantSession, so one tenant's session cannot be replayed on
// another tenant's domain.
//
// $middleware->group('tenant', [
// \Spatie\Multitenancy\Http\Middleware\NeedsTenant::class,
// \Spatie\Multitenancy\Http\Middleware\EnsureValidTenantSession::class,
// ]);
//
// Migrations across all tenants (documented command):
//
// php artisan tenants:artisan "migrate --database=tenant"
// php artisan tenants:artisan "migrate --path=database/migrations/tenant --database=tenant"Pick by how much automation you want, and read the docs before adopting either one. Neither package replaces RLS: the single-database scoping in both is application-level and does not stop a raw query. Add the PostgreSQL policy underneath, and test it (next section).
Testing tenant isolation
Prove it, do not trust it Must-know
In plain words: A test logs in as tenant A, runs a deliberately careless query, and checks it sees only A's rows. Then it checks that writing for B fails.
Common misunderstanding: "My tests pass, so isolation works." Tests that connect as the table owner, a superuser or a BYPASSRLS role pass for the wrong reason because RLS never ran. The test must use the application's role.
| Test | Expected | What it catches |
|---|---|---|
Query with no WHERE, as tenant A | Only A's rows | Missing policy, wrong role |
| Same query with no tenant set | Zero rows | Policy that fails open |
INSERT with another tenant's id | SQLSTATE 42501 | Missing WITH CHECK |
UPDATE another tenant's id | Zero rows affected | Policy covers only SELECT |
| Two requests on one pooled connection | Second request sees no leftover tenant | set_config(..., false) bug |
| Catalogue audit (below) | No tenant table without FORCE | A new table added without a policy |
| Role audit | App role not super, not BYPASSRLS, not owner | Privilege creep |
-- Tenant tables without RLS enabled and forced (run in CI against the migrated schema)
SELECT c.relname, c.relrowsecurity AS rls, c.relforcerowsecurity AS forced
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p')
AND EXISTS (SELECT 1 FROM pg_attribute a
WHERE a.attrelid = c.oid AND a.attname = 'tenant_id' AND NOT a.attisdropped)
AND NOT (c.relrowsecurity AND c.relforcerowsecurity);
-- Roles that can walk through every policy
SELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolsuper OR rolbypassrls;The Go test (skips unless TENANT_TEST_DSN is set; the DSN must name the application role):
// Package isolation proves tenant isolation against a real PostgreSQL. The
// tests skip unless TENANT_TEST_DSN is set, and the DSN must name the
// application role (not the table owner, not a superuser, not BYPASSRLS),
// otherwise the test proves nothing. See the lab on the page for the schema.
package isolation
import (
"context"
"database/sql"
"errors"
"os"
"testing"
"github.com/jackc/pgx/v5/pgconn"
_ "github.com/jackc/pgx/v5/stdlib"
)
func openApp(t *testing.T) *sql.DB {
t.Helper()
dsn := os.Getenv("TENANT_TEST_DSN")
if dsn == "" {
t.Skip("TENANT_TEST_DSN not set")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Close() })
return db
}
// asTenant runs fn in a transaction where app.tenant_id is set (or left unset
// when tenant is empty) and always rolls back, so tests leave no rows behind.
func asTenant(t *testing.T, db *sql.DB, tenant string, fn func(tx *sql.Tx)) {
t.Helper()
ctx := context.Background()
tx, err := db.BeginTx(ctx, nil)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback()
if tenant != "" {
if _, err := tx.ExecContext(ctx, `SELECT set_config('app.tenant_id', $1, true)`, tenant); err != nil {
t.Fatal(err)
}
}
fn(tx)
}
// The query below deliberately has no WHERE clause: that is the bug being simulated.
func TestForgottenWhereSeesOnlyOwnRows(t *testing.T) {
db := openApp(t)
for _, tenant := range []string{"acme", "globex"} {
asTenant(t, db, tenant, func(tx *sql.Tx) {
rows, err := tx.Query(`SELECT DISTINCT tenant_id FROM orders`)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var got string
if err := rows.Scan(&got); err != nil {
t.Fatal(err)
}
if got != tenant {
t.Fatalf("tenant %q saw a row of tenant %q", tenant, got)
}
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
})
}
}
func TestNoTenantSeesNothing(t *testing.T) {
db := openApp(t)
asTenant(t, db, "", func(tx *sql.Tx) {
var n int
if err := tx.QueryRow(`SELECT count(*) FROM orders`).Scan(&n); err != nil {
t.Fatal(err)
}
if n != 0 {
t.Fatalf("with no tenant set, %d rows were visible", n)
}
})
}
func TestCannotWriteAnotherTenantsRow(t *testing.T) {
db := openApp(t)
asTenant(t, db, "acme", func(tx *sql.Tx) {
_, err := tx.Exec(`INSERT INTO orders (tenant_id, total_cents) VALUES ('globex', 1)`)
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) || pgErr.Code != "42501" {
t.Fatalf("want SQLSTATE 42501 (WITH CHECK violation), got %v", err)
}
})
}The Laravel feature test:
<?php
// tests/Feature/TenantIsolationTest.php
//
// Run it against a real PostgreSQL with the lab schema, connected as the
// application role (not the table owner, not a superuser, not BYPASSRLS).
// A test that connects as a privileged role passes for the wrong reason.
namespace Tests\Feature;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
final class TenantIsolationTest extends TestCase
{
private function asTenant(string $tenant, callable $fn): void
{
DB::beginTransaction();
try {
DB::select("SELECT set_config('app.tenant_id', ?, true)", [$tenant]);
$fn();
} finally {
DB::rollBack(); // leave no rows behind
}
}
public function test_a_query_without_where_sees_only_own_rows(): void
{
foreach (['acme', 'globex'] as $tenant) {
$this->asTenant($tenant, function () use ($tenant): void {
// Deliberately no where('tenant_id', ...): this is the bug being simulated.
$seen = DB::table('orders')->distinct()->pluck('tenant_id')->all();
$this->assertSame([$tenant], $seen);
});
}
}
public function test_no_tenant_means_no_rows(): void
{
DB::beginTransaction();
try {
$this->assertSame(0, DB::table('orders')->count());
} finally {
DB::rollBack();
}
}
public function test_cannot_insert_for_another_tenant(): void
{
$this->asTenant('acme', function (): void {
try {
DB::table('orders')->insert(['tenant_id' => 'globex', 'total_cents' => 1]);
$this->fail('WITH CHECK should have rejected the row');
} catch (QueryException $e) {
// 42501 = insufficient_privilege, raised by a WITH CHECK violation.
$this->assertSame('42501', (string) $e->getCode());
}
});
}
}Choosing a model
| Situation | Recommended model | Extra technique | Reason |
|---|---|---|---|
| New B2B SaaS, unknown growth | Shared schema | RLS with FORCE, tenant_id first in keys | Cheapest, one migration, easiest analytics |
| Thousands of tiny tenants | Shared schema | LIST DEFAULT partition, per-tenant rate limits | Schemas per tenant would bloat the catalog |
| 50 to 500 mid-size tenants wanting per-tenant restore | Schema per tenant | Version table, worker-pool migrations | Dump and restore per schema |
| Enterprise contract: own backup, region or key | Database (or server) per tenant | Control-plane directory, BYOK, regional pod | Compliance isolation, not just data isolation |
| One tenant is 50 percent of load | Hybrid: move that tenant out | Logical replication with a row filter | Noisy-neighbour fix without touching others |
| Many tenants and one database is full | Shard by tenant (directory or Citus) | tenant_id in every key and index | Tenant-local joins stay on one shard |
| MySQL stack, no RLS | Database per tenant or app-enforced shared | Per-tenant accounts, tests | No native row filter |
| Regulated data (health, finance) | Database per tenant in a regional silo | Per-tenant keys, audit logs | Contract and law ask for provable boundaries |
In architecture: from a single process to a distributed system
Monolith (one process, one database)
One Laravel or Go application and one PostgreSQL. Use the shared schema: tenant_id on every table, (tenant_id, ...) indexes, RLS with FORCE, an app role that is not the owner, and a middleware that sets app.tenant_id in the request transaction. Add the catalogue audit and the isolation test to CI. This is enough for years and for thousands of tenants.
Modular monolith / multiple databases
Modules own their tables, and each table carries tenant_id. The tenant context travels through one place (the request transaction and CurrentTenant), never through function arguments scattered across modules. If a module has a different isolation need (for example a billing module with stricter audit), it can use its own schema or database while the rest stay shared. A central control-plane database (the landlord) holds tenants, domains, plans and the tenant-to-database directory.
Microservices
The tenant id must cross every boundary. Put it in the verified identity (a JWT claim, a signed header between services), never in a field the caller supplies. Each service sets its own database context, and every message carries the tenant in its envelope so consumers can set RLS or pick the right pod; see Messaging Security and the envelope guidance in Message Design & Schema Evolution.
Order placed across services (tenant acme)
1 gateway : verifies JWT, tenant = acme, forwards header X-Tenant (signed) to orders
2 orders : BEGIN; set_config('app.tenant_id','acme',true); INSERT order; INSERT outbox row (tenant in payload); COMMIT
3 relay : publishes the event with envelope {tenant: acme, type: OrderPlaced}
4 billing : consumer reads tenant from the envelope, opens its own tenant transaction, writes an invoice
5 cache : billing's cache key t:acme:invoice:1001
6 failure : a consumer that cannot find the tenant in the envelope sends the message to the DLQ, never to "default"There are no cross-service transactions; use a saga and the outbox. Per-tenant ordering and fairness matter in queues: one hot tenant can fill a shared queue, so partition by tenant or use weighted queues.
Distributed data (replicas, caches, sharded databases, multi-region)
| Component | Tenant concern |
|---|---|
| Read replica | The same RLS policy must exist (it replicates) and the replica connection must set the tenant too; replica lag breaks read-your-writes for a tenant after a write |
| Cache | Every key carries the tenant; invalidation per tenant (prefix delete) on offboarding |
| Sharded database or Citus | tenant_id in every key; the router must know the shard; cross-tenant queries fan out |
| Multi-region | Data residency: a tenant's pod lives in its region; the directory is replicated read-mostly |
| Search index, object storage | Index per tenant or a tenant filter that cannot be omitted; per-tenant bucket prefix and IAM |
| Warehouse | Tenant column kept; deletion on offboarding must reach it |
Scaling path
| Stage | Tenants | Topology | What changes |
|---|---|---|---|
| 1x | 1 to 1 000 | One database, shared schema + RLS | Add the isolation test and the catalogue audit |
| 10x | 1 000 to 10 000 | Shared schema, partitions for the largest tenants, read replica, PgBouncer | Per-tenant rate limits, noisy-neighbour dashboard (queries by tenant) |
| 100x | 10 000 and up, a few giants | Hybrid: pooled pods plus silos, directory in a control plane | Tenant move tool (logical replication with row filter), per-tier SLAs |
| Global | Regulated, multi-region | Regional pods, tenant-owned keys, regional control-plane replica | Residency tests, deletion across regions |
Each step is a tenant-by-tenant move, never a flag day. The structure that makes it possible is tenant_id on every row and a directory in front of every connection.
Lab
This lab needs PostgreSQL 15 or newer and two sessions. The commands below were written against the PostgreSQL manual and not executed on the machine that built this page, so read the comments as expectations and compare with your own output.
1. Setup (as a superuser).
CREATE ROLE app_user LOGIN PASSWORD 'app' NOBYPASSRLS;
CREATE DATABASE tenantlab OWNER postgres;
\c tenantlab
CREATE TABLE orders (
tenant_id text NOT NULL,
id bigint GENERATED ALWAYS AS IDENTITY,
total_cents bigint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id)
);
INSERT INTO orders (tenant_id, total_cents)
SELECT t, (random() * 10000)::bigint
FROM unnest(ARRAY['acme','globex','initech']) AS t, generate_series(1, 100000);
ANALYZE orders;
GRANT SELECT, INSERT, UPDATE, DELETE ON orders TO app_user;2. Forget the WHERE on purpose, without RLS.
SET ROLE app_user;
SELECT tenant_id, count(*) FROM orders GROUP BY 1 ORDER BY 1;
-- acme 100000, globex 100000, initech 100000 <- every tenant's rows: the leak
RESET ROLE;3. Add the policy and repeat.
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id', true))
WITH CHECK (tenant_id = current_setting('app.tenant_id', true));
SET ROLE app_user;
SELECT count(*) FROM orders; -- 0: no tenant set, default is closed
BEGIN;
SELECT set_config('app.tenant_id', 'acme', true);
SELECT tenant_id, count(*) FROM orders GROUP BY 1; -- only acme, 100000
INSERT INTO orders (tenant_id, total_cents) VALUES ('globex', 1);
-- ERROR: new row violates row-level security policy for table "orders" (SQLSTATE 42501)
ROLLBACK;
SELECT current_setting('app.tenant_id', true); -- '' (empty) after the transaction: LOCAL did its job
RESET ROLE;4. Show the two bypasses.
-- the owner is subject to RLS only because of FORCE; try without it:
ALTER TABLE orders NO FORCE ROW LEVEL SECURITY;
SELECT count(*) FROM orders; -- as the owner: 300000, owner bypasses
ALTER TABLE orders FORCE ROW LEVEL SECURITY;
SELECT count(*) FROM orders; -- as the owner: 0, FORCE applies the policy to the owner
ALTER ROLE app_user BYPASSRLS;
SET ROLE app_user; SELECT count(*) FROM orders; -- 300000: BYPASSRLS ignores policies
RESET ROLE; ALTER ROLE app_user NOBYPASSRLS;5. Measure RLS overhead. Compare the same tenant query three ways: hand-written WHERE as the owner without RLS, policy with the plain current_setting form, and policy with the sub-select form.
CREATE INDEX orders_tenant_created ON orders (tenant_id, created_at);
-- A: no RLS (owner, NO FORCE, or a copy of the table without policy)
ALTER TABLE orders NO FORCE ROW LEVEL SECURITY;
EXPLAIN (ANALYZE, BUFFERS)
SELECT count(*), sum(total_cents) FROM orders WHERE tenant_id = 'acme';
-- B: RLS, plain current_setting
ALTER TABLE orders FORCE ROW LEVEL SECURITY;
SET ROLE app_user;
BEGIN; SELECT set_config('app.tenant_id','acme',true);
EXPLAIN (ANALYZE, BUFFERS) SELECT count(*), sum(total_cents) FROM orders;
ROLLBACK; RESET ROLE;
-- C: RLS, sub-select form (evaluated once)
DROP POLICY tenant_isolation ON orders;
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = (SELECT current_setting('app.tenant_id', true)))
WITH CHECK (tenant_id = (SELECT current_setting('app.tenant_id', true)));
SET ROLE app_user;
BEGIN; SELECT set_config('app.tenant_id','acme',true);
EXPLAIN (ANALYZE, BUFFERS) SELECT count(*), sum(total_cents) FROM orders;
ROLLBACK; RESET ROLE;
-- Expect: all three use an index scan on (tenant_id, ...) and finish in the same order of magnitude.
-- Differences you may see: an extra "Filter" or an InitPlan line in C. Record actual time and buffers in a table.
-- Then drop the index and repeat B: the plan becomes a Seq Scan with a Filter, which is the real RLS cost.6. Two-connection leak test (session versus local).
-- connection 1
SELECT set_config('app.tenant_id', 'acme', false); -- session scope: the bug
-- connection 1, later, a different "request" on the same connection
SELECT current_setting('app.tenant_id', true); -- still 'acme'
-- repeat with is_local = true inside BEGIN ... COMMIT: the value is gone after COMMIT.7. Run the language tests. In docs/snippets/database/multi-tenancy/go, set TENANT_TEST_DSN='postgres://app_user:app@localhost/tenantlab' and run go test ./isolation/. Then try it with the owner's DSN and watch the first test fail: that proves the test checks the role.
Common misconceptions
| Belief | Reality |
|---|---|
| "RLS replaces the tenant logic in the application." | The application still sets app.tenant_id in every transaction; owners and superusers bypass the policy unless forced, and referential checks skip it. |
| "A Laravel global scope is a security boundary." | It is a convenience on Eloquent queries. withoutGlobalScope removes it and raw queries ignore it. The database policy holds when application code is wrong. |
| "Schema-per-tenant gives database-level isolation." | Schemas share one database, one WAL stream, one backup unit and one connection limit. They separate names, not infrastructure. |
| "Database per tenant means no noisy neighbours." | Many databases on one server still share CPU, memory, I/O and max_connections. |
"SET app.tenant_id and set_config(..., true) behave the same." | SET without LOCAL lasts for the session and leaks across pooled requests; true ends at COMMIT or ROLLBACK. |
| "RLS is too slow to use." | A simple tenant comparison with a tenant-leading index is close to a hand-written WHERE; sub-select policies and missing indexes are what hurt. Measure. |
"An index on created_at serves per-tenant date queries." | Without tenant_id first it scans all tenants. |
"DELETE FROM ... WHERE tenant_id is a full offboarding." | Backups, replicas, caches, search indexes and the warehouse still hold the data. |
| "The cache is covered by RLS." | A key without a tenant is outside every policy. |
| "Pick a model once and keep it." | Real systems are hybrids that move tenants between pooled and dedicated placement. |
| "MySQL can do RLS with views." | Views can approximate it with definer functions or per-tenant accounts; there is no native CREATE POLICY. |
"Hash by tenant_id rebalances tenants." | Hashing balances counts. Moving one giant tenant needs a directory or isolate_tenant_to_new_shard. |
Cheat sheet
| Topic | What to remember |
|---|---|
| Starting point | Shared schema, tenant_id in every key, RLS with FORCE, app role not owner and not BYPASSRLS |
| Setting the tenant | SELECT set_config('app.tenant_id', $1, true) inside the request transaction |
| Reading it | current_setting('app.tenant_id', true) (NULL when unset, '' after a prior LOCAL set) |
| Policy | USING for what you see, WITH CHECK for what you write; restrictive policies add rules |
| Bypasses | Superuser, BYPASSRLS, owner without FORCE, referential checks |
| Indexes | (tenant_id, ...), composite primary key, unique per tenant |
| Schema per tenant | SET LOCAL search_path, version table, pg_dump -n, mind catalog size |
| Database per tenant | Router with LRU cap, PgBouncer, N migrations, easy restore and drop |
| Hybrid | Directory in a control plane; move a tenant by logical replication with a row filter |
| Noisy neighbour | Rate limit and concurrency per tenant, role timeouts, move the tenant out |
| Offboarding | Export, retention window, batched delete or drop, purge caches and warehouse, crypto-shred backups |
| Citus | create_distributed_table(t, 'tenant_id'), reference tables, isolate_tenant_to_new_shard |
| MySQL | No RLS: definer views, per-tenant accounts, app enforcement, or database per tenant |
| SQL Server | CREATE SECURITY POLICY, filter and block predicates, SESSION_CONTEXT |
| Testing | Test as the app role; no-WHERE query, no-tenant query, cross-tenant insert, catalogue and role audits |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What are the four kinds of tenant isolation, and which model is weakest on each? Important
Answer
Answer: Data, performance, security and compliance. Shared schema is weakest on all four unless RLS, quotas, per-tenant credentials and per-tenant keys or regions are added; a dedicated server in the tenant's region is strongest.
2 — Why must set_config use true as the third argument in a pooled application? Important
Answer
Answer: true makes the setting local to the transaction, so it is cleared at COMMIT or ROLLBACK. With false the value stays on the connection for the session, and the next request that reuses the connection can inherit another tenant's id.
3 — A table has ENABLE ROW LEVEL SECURITY and a correct policy, yet the application sees all rows. Name three causes. Important
Answer
Answer: The application connects as the table owner without FORCE ROW LEVEL SECURITY, as a superuser, or as a role with BYPASSRLS. Another cause is a view or security-definer function that runs with the owner's rights.
4 — What is the difference between USING and WITH CHECK? Must-know
Answer
Answer: USING filters rows that already exist (reads and the old row of updates and deletes). WITH CHECK validates rows being written (inserts and the new row of updates). Without WITH CHECK a tenant can write rows that belong to another tenant.
5 — Why does an index on (tenant_id, created_at) beat one on (created_at) for per-tenant queries? Must-know
Answer
Answer: A multicolumn B-tree is most efficient when constraints are on its leading columns. With tenant_id first the query seeks to one tenant's slice; with created_at first it reads that period for every tenant and filters.
6 — How do you roll out a schema change to 5 000 tenant schemas? Important
Answer
Answer: Keep a per-tenant version table, run a worker pool with lock_timeout, canary a few tenants first, record failures and continue, keep the application compatible with two versions during the rollout, and re-run for failed tenants.
7 — Why is DELETE FROM ... WHERE tenant_id = ? not enough for offboarding? Important
Answer
Answer: The data also lives in backups, replicas, caches, search indexes, object storage and the warehouse; a huge DELETE also bloats the table. Use partition drops or schema and database drops, purge the other stores, and crypto-shred or wait out backup retention.
8 — When would you move one tenant out of a pooled database, and how? Good to know
Answer
Answer: When it dominates CPU or I/O, has a contract requiring isolation, or needs its own region or key. Copy its rows with logical replication using a row filter, catch up, briefly hold its writes, flip the directory entry, verify and delete the old rows.
9 — What does MySQL offer instead of RLS? Important
Answer
Answer: Nothing native. Use views with definer functions, per-tenant accounts, application enforcement, or a database per tenant.
10 — What must a tenant-isolation test never do? Must-know
Answer
Answer: Connect as the table owner, a superuser or a BYPASSRLS role, because RLS would not run and the test would pass for the wrong reason.
Glossary
| Term | Meaning |
|---|---|
| Tenant | A customer whose data must be separated from other customers |
| Multi-tenancy | One application serving many tenants |
| Shared schema | All tenants in the same tables, separated by a tenant_id column |
| Schema per tenant | One PostgreSQL schema per tenant inside one database |
| Database per tenant | One database per tenant, possibly on its own server |
| Hybrid / bridge model | Mix of pooled and dedicated placement chosen per tenant |
| Pod | A deployable unit of application and database that hosts a set of tenants |
| Silo | A dedicated stack or database for one tenant |
| Pool model | Many tenants sharing the same resources |
| Control plane / landlord | The database that stores tenants, domains, plans and placement |
| Directory | Table that maps a tenant to its pod, shard or DSN |
| Noisy neighbour | A tenant whose load slows other tenants |
| RLS (Row-Level Security) | Database feature that filters rows per query by policy |
CREATE POLICY | PostgreSQL command that defines a row-security rule |
FORCE ROW LEVEL SECURITY | Makes the table owner subject to its policies |
BYPASSRLS | Role attribute that ignores all policies |
current_setting | Function that reads a configuration value, such as app.tenant_id |
set_config | Function form of SET; with is_local = true the value ends at COMMIT |
| Permissive / restrictive policy | Combined with OR / with AND |
search_path | Schema lookup list that resolves unqualified table names |
| LIST partitioning | Partitions by explicit values, such as one tenant per partition |
| Leading-column index | A composite index whose first column is the common filter, here tenant_id |
| Crypto-shredding | Deleting an encryption key so the data it protects becomes unreadable |
| BYOK | Bring your own key: the tenant controls the key that encrypts its data |
| Co-location | Keeping related rows (one tenant's tables) on the same shard |
| Reference table | A small table replicated to every Citus worker |
isolate_tenant_to_new_shard | Citus function that gives one tenant its own shard |
| Rebalancing | Moving shards or tenants to even out load |
| Security policy (SQL Server) | Object that applies filter and block predicates to a table |
SESSION_CONTEXT | SQL Server per-connection key-value store used to carry the tenant id |
| Tenant-aware cache key | A cache key that always includes the tenant |
| Token bucket | Rate limiting algorithm that refills tokens at a fixed rate |
| Offboarding | Export and deletion of a tenant's data when it leaves |
| Data residency | Requirement that data stays in a given region |
References
- PostgreSQL 19 Documentation, Row Security Policies
- PostgreSQL 19 Documentation, CREATE POLICY
- PostgreSQL 19 Documentation, SET and Configuration Settings Functions
- PostgreSQL 19 Documentation, Schemas and Multicolumn Indexes
- PostgreSQL 9.5 Release Notes, Add row-level security control
- Microsoft, Architectural Approaches for Storage and Data in Multitenant Solutions
- Microsoft, Row-Level Security (SQL Server)
- Citus Data, Multi-tenant Apps
- GDPR, Article 17: Right to erasure
- Go documentation,
database/sql - Laravel 13 documentation, Eloquent: Global Scopes, Database: Transactions, Routing: Subdomain Routing and Rate Limiting
- Tenancy for Laravel, Introduction (v3), Installation (v3), Quickstart (v3), Single-database tenancy (v3) and Tenant identification (v3)
- Spatie, laravel-multitenancy v4: Introduction, Base installation, Using multiple databases and Working with the current tenant