Video in progress
In a multi-tenant SaaS, how do you ensure tenant isolation across services?
The tenant ID is carried from the entry point in a trusted context (a token claim), and every layer has a mandatory filter: in the DB row-level security or a separate schema/DB, in cache keys, topic messages, logs and metrics. The isolation level (shared table, schema, DB) is chosen by risk and cost.
📖 Answer
The most dangerous bug in a multi-tenant system is one tenant seeing another's data. A single forgotten WHERE tenant_id = ? is enough. So I put isolation on the infrastructure, not on a developer's memory.
Where the tenant comes from. Only from a verified token. Trusting an X-Tenant-Id header is a classic vulnerability. The gateway extracts it from the token, and internal services take it from an internally signed context.
The data layer has three options:
| Model | Isolation | Cost |
|---|---|---|
Shared table + tenant_id |
low, medium with RLS | cheap |
| Schema per tenant | medium | migrations run N times |
| DB per tenant | high | expensive, for big customers |
Often a hybrid: small tenants in the shared table, big enterprise customers in their own DB (they ask for this in the contract).
PostgreSQL RLS on a shared table:
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id')::uuid);
At the start of each transaction the application does SET LOCAL app.tenant_id = .... Now even if the WHERE is forgotten, other tenants' rows don't come out.
Don't forget the other places: cache keys (tenant:{id}:product:{id}), Kafka messages (a tenant header or key), file storage (a tenant prefix), the search index (a filter or a separate index), a tenant tag in logs and traces.
The noisy neighbor. One tenant starts a heavy report and slows everyone down. You need per-tenant rate limits, separate queues, or moving heavy tenants into a separate pool.
A separate check in tests: for every service, an automated test that creates two tenants and uses one's token to reach the other's resources. This catches the vulnerability before it reaches prod.
Sign up to mark studied questions and save your progress.