Implement a multi-tenant database architecture using SQL.
Instruction: Describe how you would design and implement a database schema that supports multiple tenants in a SaaS application, ensuring data isolation among tenants.
Updated
Official answer
Choose a tenant model from the requirements for isolation, recovery, cost, scale and operational ownership. Shared tables, separate schemas and separate databases each have tradeoffs; a schema name alone is not an access-control boundary.
For shared PostgreSQL tables, give each tenant-owned row a required tenant_id. Use composite unique keys and foreign keys containing tenant_id so child rows cannot point to another tenant's parent. Derive the tenant from authenticated authorization, and apply a reviewed row-security policy with the actual application role. Owners and privileged roles have special bypass behavior that must be accounted for.
For separate schemas, provision ownership and privileges deliberately, restrict untrusted object creation, and use safely quoted trusted schema identifiers. Do not concatenate a user-supplied tenant name into SQL or assume changing search_path enforces isolation. A role that can access every schema can still cross the boundary.
Test cross-tenant reads/writes, jobs, exports, cache keys, administrative tools and pooled-connection reuse. Coordinate tenant provisioning and migrations. Prove tenant-specific recovery with a restore exercise: sharing a database can complicate recovery to one tenant's earlier state. Monitor noisy-neighbor effects and define an operational path for tenants requiring stronger isolation. Encryption supports the design but does not establish authorization by itself.