Get started
← All posts

Multi-tenancy with PostgreSQL row-level security

In a multi-tenant CMS the worst bug is one tenant seeing another tenant's content. ByteContent defends against it twice.

Layer one: the application

Every request resolves a tenant from the session or API key. Services receive a tenant context and every query is scoped to it.

Layer two: the database

Each tenant-owned table has a row-level security policy, and the application connects as a role that cannot bypass it. Each transaction sets the current tenant; PostgreSQL then only returns and accepts rows for that tenant:

ALTER TABLE records ENABLE ROW LEVEL SECURITY;
ALTER TABLE records FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON records
  USING (app_rls_allows(tenant_id))
  WITH CHECK (app_rls_allows(tenant_id));

If a query forgets its WHERE tenant_id = …, the database still filters it. Our test suite checks this directly: it runs queries as the application role without a tenant and expects to see nothing.

Why not a database per tenant?

Separate databases isolate well but are expensive to migrate, back up and monitor at thousands of tenants. Row-level security keeps one schema and one migration path while giving strong isolation.