One morning, Sunset Coffee's admin opens the dashboard (the summary page) of their cashier app. In the "Newest customers" widget, a small box on that dashboard, there are two unknown names: Rina and Dewi, with their phone numbers. They're customers of Morning Coffee, another café renting the same app. There's no error. Just one query that forgot one filter.
An app like this uses multi-tenancy: one app serves many organisations at once. Each organisation's data is kept apart, and one organisation must never see another's data. Each organisation is called a tenant. Picture an apartment block. The building and its lift are shared, but every flat has its own key: whoever lives in flat 3 can't walk into flat 7. The building is the app, each flat is one tenant's data, and the key is how the app keeps the tenants' data apart.
The tables we're using
Sunset Coffee's cashier app sold well, and it's now rented out to other shops. Sunset Coffee becomes tenant 1, Morning Coffee tenant 2. The simplest way: every tenant uses the same tables, and every row gets a tenant_id column, the number of the tenant that owns the row:
CREATE TABLE tenants (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
tenant_id INTEGER NOT NULL REFERENCES tenants(id),
name TEXT NOT NULL,
phone TEXT
);
CREATE INDEX customers_tenant_id_index ON customers (tenant_id);
INSERT INTO tenants VALUES (1, 'Sunset Coffee'), (2, 'Morning Coffee');
INSERT INTO customers VALUES
(1, 1, 'Budi', '07700 900111'),
(2, 1, 'Siti', '07700 900555'),
(3, 2, 'Dewi', '07700 900444'),
(4, 1, 'Andi', '07700 900777'),
(5, 2, 'Rina', '07700 900666');
Every query must filter on its tenant, tenant 1 for example:
SELECT * FROM customers WHERE tenant_id = 1; -- Budi, Siti, Andi
An index on tenant_id is a must too, because that column is in the WHERE of almost every query.
One query forgets the scope
The Customers page is written correctly ($tenantId holds the number of the tenant that is logged in). The dashboard widget was written in a hurry, and gets the 5 customers with the highest id:
// the Customers page: correct
Customer::where('tenant_id', $tenantId)->get();
// the "Newest customers" widget: forgot the tenant filter
Customer::latest('id')->take(5)->get();
The widget sends this SQL, and here is the result:
SELECT * FROM customers ORDER BY id DESC LIMIT 5;
| id | tenant_id | name | phone |
|---|---|---|---|
| 5 | 2 | Rina | 07700 900666 |
| 4 | 1 | Andi | 07700 900777 |
| 3 | 2 | Dewi | 07700 900444 |
| 2 | 1 | Siti | 07700 900555 |
| 1 | 1 | Budi | 07700 900111 |
Rina and Dewi, Morning Coffee's customers, appear on Sunset Coffee's dashboard, with their phone numbers. There's no error at all, the query "worked". This is the most dangerous bug in a multi-tenant app, because it produces a data leak: one tenant's data is seen by another tenant.
Global scope: a filter you can't forget
Don't rely on every developer to remember where('tenant_id', ...). Put the filter on the model once through a global scope: a filter Eloquent adds to every query of that model automatically:
trait BelongsToTenant
{
protected static function bootBelongsToTenant(): void
{
static::addGlobalScope('tenant', function (Builder $query) {
$query->where('tenant_id', auth()->user()->tenant_id);
});
static::creating(function (Model $model) {
$model->tenant_id ??= auth()->user()->tenant_id;
});
}
}
class Customer extends Model
{
use BelongsToTenant;
}
- Laravel automatically calls the method named
boot+ the trait's name (bootBelongsToTenant) the first time the model is used. auth()->user()->tenant_idis the tenant number of the user who is logged in.addGlobalScope('tenant', ...)addsWHERE tenant_id = ?to everyCustomerquery. The widget now sendsSELECT * FROM customers WHERE tenant_id = 1 ORDER BY id DESC LIMIT 5.creatingruns just before a new customer is saved.??=fills in that new customer'stenant_id, if it's still empty.
A global scope has the same gaps as the deleted_at filter in the Soft Delete & Archiving lesson: both only work in Eloquent. DB::table('customers') and raw SQL skip it, and so does withoutGlobalScope('tenant'), which turns off the tenant scope on purpose.
Three multi-tenancy strategies
A tenant_id column in shared tables is just one of three ways. The three differ in isolation, meaning how far apart the tenants' data is kept:
- Shared tables (one database, tables everyone shares, a
tenant_idcolumn). This is like one big cupboard for every resident, each box labelled with its owner's name. The cupboard is the table, a box is a row, and the label istenant_id. It's the simplest and the cheapest way: one migration for every tenant, and a new tenant is a single row intenants. The risk: one query forgets the filter, and data leaks. - Separate schema (a schema per tenant): one database, but each tenant has its own schema. This schema is not the one from the Types of Database lesson (the shape of the tables). In PostgreSQL, a schema is a folder of tables inside one database:
sunset_coffee.customersandmorning_coffee.customersare two different tables. For a request from Morning Coffee, the app runsSET search_path TO morning_coffee;. After that, a table name without a schema, such ascustomers, is looked up in themorning_coffeeschema, so queries no longer needtenant_id. The isolation is better, but every migration runs once per schema. - Separate database (a database per tenant): each tenant has its own database, and on each request the app picks the connection to that tenant's database. The isolation is the strongest: even a query that forgets the filter can only see that tenant's data, because the other tenants' data isn't in that database. Backing up one tenant (making a spare copy), or restoring it, only takes its own database. The downside is the highest cost: hundreds of databases to maintain, migrations per database, and connections per database.
| Shared tables | Separate schema | Separate database | |
|---|---|---|---|
| Isolation | Low | Medium | High |
| Adding a tenant | 1 row in tenants |
CREATE SCHEMA + migrations |
CREATE DATABASE + migrations |
| Migrations | Once for everyone | Once per schema | Once per database |
| Backing up one tenant | Hard, filtered table by table | Per schema | Just its database |
| Cost | Cheapest | Medium | Most expensive |
In the exercise, the rule follows the table's "Isolation" row. An isolation need of "low" becomes "shared tables", "medium" becomes "separate schema", "high" becomes "separate database", and anything else "shared tables". An example of high isolation: a clinic or a bank whose contract requires its data to be stored separately.
In the Lab, a database per tenant is imitated with one SQLite database file per tenant. The Lab keeps the Indonesian names: Sunset Coffee is Kedai Senja, and Morning Coffee is Kopi Pagi. Kopi Pagi's request opens only the file kopi_pagi.db (with ATTACH, the SQLite command that opens another database file). So even SELECT * FROM customers without a filter can't touch Kedai Senja's customers.
📌 Row Level Security in PostgreSQL
PostgreSQL can enforce the tenant filter at the database level, so even a query that forgets its WHERE stays safe. This feature is called Row Level Security. You create a policy, a rule for which rows may be read:
ALTER TABLE customers ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON customers
USING (tenant_id = current_setting('app.tenant_id')::int);
current_setting('app.tenant_id') reads the setting named app.tenant_id, and ::int turns it into a number. So only the rows whose tenant_id equals that setting are visible. Each request picks its tenant inside a transaction, and the database itself filters the rows:
BEGIN;
SET LOCAL app.tenant_id = '1';
SELECT * FROM customers; -- Budi, Siti, Andi
COMMIT;
Do not forget LOCAL. A plain SET lasts as long as the connection to the database stays open. But persistent connections (kept open) and pools (connections used in turn, with PgBouncer for example) are reused by the next request, which can come from another tenant. A SET LOCAL value ends with the transaction, so a request that forgets to pick a tenant fails with an error, instead of using the previous request's tenant. In Laravel, run DB::select("SELECT set_config('app.tenant_id', ?, true)", [(string) $tenantId]) inside DB::transaction(): the argument true means the same as LOCAL.
Watch out: the database account that owns the table bypasses this policy unless you also add ALTER TABLE customers FORCE ROW LEVEL SECURITY;. Superusers and other accounts given BYPASSRLS always bypass it, even with FORCE. Laravel packages (extra libraries) can also pick the tenant for each request: stancl/tenancy for all three strategies, spatie/laravel-multitenancy for one shared database and for a database per tenant.
⚠️ Gaps that leak a tenant's data
- One query forgets
WHERE tenant_id. No error, and data leaks. Use a global scope, don't rely on memory. DB::table(), raw SQL, orwithoutGlobalScope(). They all skip the global scope. Write the filter yourself in queries like those.- Queued jobs and artisan commands. In a queued job (a task that runs in the background) or an artisan command, nobody is logged in, so
auth()->user()isnull. Set the tenant yourself inside the job. - Forgetting the index on
tenant_id. Every query reads every tenant's rows before it filters. - The text in the exercise. Return exactly
"shared tables","separate schema"or"separate database". ThetenantCountparameter doesn't affect the result.
TL;DR: Multi-tenancy: one app serves many organisations (tenants) with their data kept apart. The simplest way is shared tables: one database, a tenant_id column (the number of the tenant that owns the row) in every table, and every query must have WHERE tenant_id = ?. One query that forgets the filter leaks another tenant's data without any error. So put a global scope on the model, a filter Eloquent adds to every query of that model automatically. Separate schema gives each tenant its own schema, its own set of tables inside one database: how far apart the data is kept (the isolation) is medium. Separate database gives each tenant its own database: the strongest isolation and easy per-tenant backups, but the most expensive to maintain.
⚡ One app, many tenants
Write:
SELECT * FROM customers WHERE tenant_id = 1; -- Budi, Siti, Andi
Meaning: Multi-tenancy means one app serves many organisations (tenants) with their data kept apart. The simplest way: one database, a tenant_id column (the number of the tenant that owns the row) in every table, and every query must filter on its tenant.
⚡ One query forgets the filter
Write:
SELECT * FROM customers ORDER BY id DESC LIMIT 5;
Guess first: the customers table holds the customers of Sunset Coffee (tenant 1) and Morning Coffee (tenant 2). Sunset Coffee's dashboard runs this query, with no WHERE tenant_id. Is there an error?
No error at all. Rina and Dewi, Morning Coffee's customers, appear too, with their phone numbers. The data leaks.
Meaning: Put a global scope on the model. A global scope is a filter Eloquent adds to every query of that model automatically, so WHERE tenant_id = ? can't be forgotten.
⚡ Three strategies
Meaning: Shared tables (one database, tables everyone shares with a tenant_id column) are the cheapest, but their isolation (how far apart the tenants' data is kept) is low. Separate schema gives each tenant its own schema, its own set of tables inside one database: medium isolation. Separate database gives each tenant its own database: the strongest isolation, but the most expensive to maintain.
In the exercise, return exactly "shared tables", "separate schema" or "separate database".