Design a schema for a multi-tenant system that efficiently handles data isolation

Instruction: Explain your approach to designing a database schema for a multi-tenant application, ensuring data isolation and security between tenants.

Context: This question assesses the candidate's understanding of database schema design in the context of software as a service (SaaS) applications, focusing on multi-tenancy and data isolation.

Updated

Official answer

Choose the isolation level from the threat model and operational requirements: separate databases, separate schemas or shared tables. Shared tables can simplify migrations, but tenant identity must participate in keys, references and authorization.

This PostgreSQL schema illustrates tenant-scoped identities and relationships; it is not a complete access-control implementation:

CREATE TABLE tenants (
  tenant_id bigint PRIMARY KEY
);
CREATE TABLE projects (
  tenant_id bigint NOT NULL REFERENCES tenants,
  project_id bigint NOT NULL,
  name text NOT NULL,
  PRIMARY KEY (tenant_id, project_id)
);
CREATE TABLE tasks (
  tenant_id bigint NOT NULL,
  task_id bigint NOT NULL,
  project_id bigint NOT NULL,
  title text NOT NULL,
  PRIMARY KEY (tenant_id, task_id),
  FOREIGN KEY (tenant_id, project_id)
    REFERENCES projects (tenant_id, project_id)
);

The composite foreign key prevents a task from referencing a project outside its declared tenant. It does not establish that a caller is entitled to declare that tenant. Derive tenant context from authenticated, authorized membership, and enforce it on reads and writes, including background jobs, exports and caches.

PostgreSQL row-level security can add database enforcement with suitable USING and WITH CHECK policies. Test the actual application role: superusers and BYPASSRLS roles bypass policies, and table owners normally bypass them unless forced. An arbitrary client-supplied session setting is not trusted identity. Ensure pooled connections cannot carry stale tenant context.

Include tenant identity in cache keys, unique business constraints and relevant access paths. Test cross-tenant reads, inserts, updates, foreign-key attempts and connection reuse, plus tenant-specific recovery and deletion. Encryption and a WHERE clause alone are insufficient proof of isolation; separate-database designs also need correct permissions and routing.

Related Questions