Multi-tenancy is usually introduced as a database question: one database or many? That is the decision people argue about, and it is the least permanent one. The decision that actually ages well or badly is whether your application knows, at every moment, which tenant it is working for, and whether that knowledge survives the trip into queues, caches, schedulers and file storage.
This article follows one request through a Laravel SaaS application, from the hostname it arrives on to the job it leaves behind, and names the place at each step where tenants leak into each other. The isolation model matters, and we will choose one. But the piece that keeps every model honest, and lets you change your mind later, is a small metadata store most teams build too late: the tenant-routing registry.
Isolation is not a database layout. It is a property of every code path that runs while a tenant is active, and of every code path that runs after.
Three Isolation Models and the Bill Each Sends
There are three ways to separate tenant data in a relational database, and each one moves cost to a different place:
Shared tables, tenant_id column | Schema per tenant (PostgreSQL) | Database per tenant | |
|---|---|---|---|
| Isolation strength | Logical only; one missing where clause exposes everyone | Separated by search_path; a wrong path still reads the wrong tenant | Strongest; separate credentials possible |
| Migrations | One run | One run per schema | One run per database |
| Restore one tenant | Hard: rows are interleaved with everyone else's | Moderate: dump and restore one schema | Easy: restore one database |
| Cross-tenant reporting | A plain query | A union across schemas | An ETL job |
| Noisy neighbours | Share everything | Share the server | Can be moved to their own server |
| Where it strains | Very large tenants, per-tenant compliance demands | Thousands of schemas: catalog size and migration time | Connection counts and operational overhead per tenant |
For most B2B products with many small and mid-sized customers, shared tables are the right start: cheapest to run, simplest to migrate, and analytics come free. Database-per-tenant earns its overhead when contracts demand it, when one customer is large enough to deserve its own hardware, or when data residency puts tenants in different regions.
The useful realisation is that you rarely have to pick one forever. A pooled tier on shared tables plus a dedicated tier for the customers who pay for it is a common and sensible end state. What makes that hybrid possible is not the database. It is the registry.
The Registry That Knows Where Every Tenant Lives
The tenant-routing registry is a small "landlord" database, separate from tenant data, that answers one question for every request: given this hostname or token, which tenant is it, and where does that tenant's data live? It holds per-tenant connection details, and the application uses it to route each request to the right schema or database.
create table tenants (
id uuid primary key,
slug text unique not null,
status text not null, -- active, suspended, migrating, archived
tier text not null, -- pooled, dedicated
db_host text not null,
db_name text not null,
db_schema text, -- null for database-per-tenant
db_secret_ref text, -- pointer to the credential, not the credential
region text not null,
schema_version text, -- last migration applied to this tenant
created_at timestamptz not null default now()
);
create table tenant_domains (
host text primary key, -- acme.app.example.com or portal.acme.com
tenant_id uuid not null references tenants(id)
);Three columns in that table do more work than they appear to:
db_host,db_name,db_schemaare an indirection. Because no code hard-wires where a tenant lives, moving a tenant from the pooled cluster to a dedicated database is a data copy plus a one-row update. Without the registry, it is a code change.statuslets you suspend a tenant for non-payment, freeze writes during a move, or archive a churned customer without touching application code paths one by one.schema_versionrecords which migrations each tenant has received, which you will need the first time a migration fails halfway through your tenant list.
Store a reference to credentials, not the credentials themselves: an entry in a secrets manager, or at minimum a value encrypted with Laravel's encrypted casts. The registry is read on every request, so it is also cached, and every write to it must invalidate that cache.
From Hostname to Connection in One Middleware
A request arrives on acme.app.example.com, on a customer's own domain, or on an API endpoint carrying a token. Resolution turns any of those into a tenant, then activates that tenant for the rest of the request:
final class TenantRegistry
{
public function forHost(string $host): ?Tenant
{
return Cache::remember("tenant:host:{$host}", 300, fn () =>
Tenant::on('landlord')
->whereRelation('domains', 'host', $host)
->where('status', '!=', 'archived')
->first()
);
}
}
final class ResolveTenant
{
public function __construct(
private TenantRegistry $registry,
private TenantContext $context,
) {}
public function handle(Request $request, Closure $next): Response
{
$tenant = $this->registry->forHost($request->getHost()) ?? abort(404);
if ($tenant->status === 'suspended') {
return response()->view('tenant.suspended', status: 402);
}
$this->context->activate($tenant);
return $next($request);
}
}Activation is where the routing happens. For schema-per-tenant and database-per-tenant, it rewrites the tenant connection from the registry row and purges the old one so Laravel reconnects:
public function activate(Tenant $tenant): void
{
config(['database.connections.tenant' => array_merge(
config('database.connections.pgsql'),
[
'host' => $tenant->db_host,
'database' => $tenant->db_name,
'search_path' => $tenant->db_schema ?? 'public',
'password' => $this->secrets->get($tenant->db_secret_ref),
],
)]);
DB::purge('tenant');
DB::setDefaultConnection('tenant');
$this->current = $tenant;
}Two placement details cause most of the early bugs. The middleware must run before anything that touches the database, including the session and authentication guards if user records live inside tenant data; that means high in the middleware priority, not appended at the end of a route group. And API requests should resolve the tenant from the authenticated token, never from a header the client chose, or any user can address any tenant by editing a request.
Packages such as Tenancy for Laravel (stancl/tenancy) and spatie/laravel-multitenancy implement this resolve-and-activate cycle, along with bootstrappers for cache, filesystem and queues. They are good, and using one is usually right. The point of seeing the mechanism is knowing what the package is doing for you, so you can tell when your own code steps outside it.
Every Query Carries the Tenant, or None Do
With shared tables, isolation is enforced by a filter on every query. In Laravel that is a global scope applied by a trait, plus a creating hook so new rows are stamped automatically:
trait BelongsToTenant
{
protected static function bootBelongsToTenant(): void
{
static::addGlobalScope('tenant', function (Builder $query) {
$query->where(
$query->getModel()->qualifyColumn('tenant_id'),
app(TenantContext::class)->id()
);
});
static::creating(function (Model $model) {
$model->tenant_id ??= app(TenantContext::class)->id();
});
}
}A global scope covers Eloquent and nothing else. These are the paths that skip it in practice:
- Query builder and raw SQL.
DB::table('invoices')knows nothing about models or scopes. Reporting code is where this usually appears. withoutGlobalScopes(), added once to debug something and never removed.- Joins. The scope filters the model's own table; the joined table is unfiltered unless you filter it too.
- Uniqueness. A unique index on
emaillets one tenant's user block another tenant's signup. Unique indexes in a shared schema almost always become composite:(tenant_id, email).
Because the application layer will eventually be wrong somewhere, PostgreSQL row-level security makes a good second wall. Each request sets a session variable; a policy on every tenant table compares against it:
alter table invoices enable row level security;
alter table invoices force row level security;
create policy tenant_isolation on invoices
using (tenant_id = current_setting('app.tenant_id')::uuid);Three conditions make this real rather than decorative. The application must connect as a role that does not own the tables and is not a superuser, because owners bypass policies unless force row level security is set and superusers bypass them always. The variable must be set on every connection the request uses. And behind a transaction-pooling proxy such as PgBouncer, a plain set can outlive your request on a shared server connection; use set local inside a transaction, or reset it explicitly at the end of every request.
The Request Ends; the Tenant Must Not Leak Into the Next One
Traditional PHP forgot everything between requests, which quietly protected a lot of sloppy tenancy code. Laravel Octane and long-running queue workers do not forget. If TenantContext is bound as a singleton, the second request served by a worker inherits the first request's tenant until something overwrites it.
Bind it with $this->app->scoped(TenantContext::class) instead: scoped instances are flushed when Octane starts a new request and when a queue worker starts a new job. Then walk every surface that outlives a request:
| Surface | What leaks if you forget | What to do |
|---|---|---|
| Queued jobs | The job runs with no tenant, or with the previous job's tenant | Add the tenant id to every payload with Queue::createPayloadUsing, and re-activate it in a JobProcessing listener before the job body runs |
| Cache | Tenant B is served tenant A's cached dashboard | Prefix every key with the tenant id, or use a tenant-scoped cache store |
| File storage | Uploads land in one shared folder; a guessed path reads another tenant's file | A per-tenant path prefix or disk root, and signed temporary URLs for downloads |
| Scheduled commands | The command runs once, for no tenant | Iterate active tenants from the registry and activate each before doing work |
| Broadcast channels | Clients subscribe to another tenant's channel by name | Include the tenant id in channel names and authorise against it |
| Logs and errors | An incident cannot be tied to a customer | Add the tenant id to log context on activation |
| Outbound mail | Tenant A's branding or reply-to address on tenant B's email | Resolve sender and templates from the active tenant at render time |
The queue row deserves emphasis. A job dispatched from a tenant request and processed later by a worker is the classic cross-tenant bug, because it works perfectly in local development, where only one tenant exists.
Running One Migration Across Many Databases
With shared tables, a migration runs once. With schemas or databases per tenant, it runs hundreds or thousands of times, and some of those runs will fail. The sequence that keeps that manageable:
- Migrate the landlord database first, since the registry itself may need new columns.
- Deploy code that works against both the old and new schema. Tenants are migrated over minutes, not instantly, so for a while some are on each version. Expand first (add the column, backfill), contract later (drop the old one) in a separate release.
- Migrate tenants in batches with bounded concurrency, recording each tenant's
schema_versionin the registry as it succeeds. - Let one failure stop one tenant, not the run. A tenant whose migration fails is flagged and skipped; the rest continue; someone looks at the flagged list.
- Query the registry to finish. "Which tenants are not on the latest version?" should be a single query, not a log search.
Noisy Neighbours and the Tenant Who Outgrows the Pool
Scaling a multi-tenant system is mostly about stopping one tenant's load from becoming everyone's latency. Three controls cover most of it:
- Per-tenant rate limits. Key Laravel's rate limiter on the tenant id, not just the user or IP, so one customer's integration script cannot saturate the API for others.
- Queue fairness. One tenant importing a large file should not delay another tenant's password reset email. Separate queues by priority, and cap per-tenant concurrency on heavy jobs;
Redis::funnelkeyed on the tenant id is a straightforward way to do it. - Relocation. When a tenant is simply too large for the pool, move it.
Relocation is where the registry pays for itself. Moving a tenant becomes a procedure rather than a project:
- Set the tenant's status to
migrating; the application serves it read-only. - Copy its data to the target database or schema, and verify row counts and checksums.
- Update
db_host,db_name,db_schemaandtierin the registry row. - Invalidate the registry cache for that tenant's hosts.
- Set the status back to
active, and keep the old copy until the tenant has run cleanly for a while.
Copying out of shared tables means filtering every table by tenant_id, which is one more reason to keep that column on every tenant-owned table, including the ones that "obviously" belong to a parent row.
Where Access Control and Billing Plug In
Tenancy answers whose data is this? It does not answer which person inside that tenant may do what. That is authorisation, and in a multi-tenant system every role grant includes the tenant; a user can be an admin in one workspace and a viewer in another. We cover that model in depth in our article on role-based access control in SaaS.
The tenant is also the unit that pays. Plan, seat limits and feature entitlements hang off the tenant record, and the registry's status is where a failed payment eventually becomes a suspension. How plans become entitlements, and entitlements become gates, is the subject of our subscription and billing reference. And when you add AI features, the same discipline extends to embeddings and retrieval: an index that is not filtered by tenant will happily answer one customer's question with another customer's documents, a problem we work through in adding AI features to existing SaaS products.
Tests That Prove Tenant A Cannot See Tenant B
Isolation is a claim, and claims need tests. The suite we put into every multi-tenant build is small and unglamorous:
- Two tenants in every test database, never one. Most leaks are invisible with a single tenant.
- A cross-tenant request test per resource: authenticate as a user of tenant A, request tenant B's record by id, and expect a 404. Route model binding through a scoped model makes this pass by default; the test catches the routes that bypass it.
- A queued-job test that dispatches from tenant A, processes the job in a fresh context, and asserts it ran against tenant A's data.
- A raw-query lint that flags
DB::tableandwithoutGlobalScopesin code review, so each use is a decision someone made deliberately.
None of this is exotic, and that is the point. Multi-tenant Laravel applications rarely fail because the isolation model was wrong. They fail because one code path forgot which tenant it was serving.
This is the kind of foundation our web application development work starts from. If you are planning a SaaS build or untangling tenancy in an existing one, talk to us about the architecture.
Frequently Asked Questions
Which multi-tenancy model should a Laravel SaaS use?
For most B2B products with many small and mid-sized customers, shared tables with a tenant_id column are the right start: cheapest to run, simplest to migrate, and cross-tenant analytics come free. Database-per-tenant earns its overhead when contracts demand it, when one customer is large enough for its own hardware, or when data residency puts tenants in different regions. Many products end up running both tiers.
What is a tenant-routing registry?
A tenant-routing registry is a small "landlord" database, separate from tenant data, that answers for every request which tenant a hostname or token belongs to and where that tenant's data lives. Because it holds each tenant's host, database, schema, status and schema version, moving a tenant to a dedicated database becomes a data copy plus a one-row update instead of a code change.
Is a Laravel global scope enough to isolate tenant data?
No. A global scope covers Eloquent and nothing else, so query-builder and raw SQL calls, withoutGlobalScopes(), joined tables and single-column unique indexes can all get around it. PostgreSQL row-level security makes a good second wall, provided the application connects as a role that neither owns the tables nor is a superuser, and the tenant variable is set on every connection the request uses.
How do tenants leak between requests in Laravel Octane and queue workers?
Octane and long-running queue workers keep state between requests, so a TenantContext bound as a singleton lets the next request inherit the previous tenant. Bind it as scoped instead, which is flushed on each new request or job. Then carry the tenant into every surface that outlives a request: queued job payloads, cache keys, file paths, scheduled commands, broadcast channels, logs and outbound mail.
How do you run migrations across hundreds of tenant databases?
Migrate the landlord database first, deploy code that works against both the old and new schema, then migrate tenants in batches with bounded concurrency, recording each tenant's schema version in the registry as it succeeds. A tenant whose migration fails is flagged and skipped while the rest continue, and a single registry query shows which tenants are not yet on the latest version.
