Course contentsShow
← Databases & SQL
Lesson 1915 of 1,95318. Application Integration PatternsFree lesson

Multi-tenant Schema Strategies

Choose between shared-schema, row-level security, and database-per-tenant architectures for SaaS applications.

In this lesson, you will learn how to structure your database architecture to support multiple isolated clients, or "tenants," within a single SaaS application.

When building for multi-tenancy, you must balance isolation, operational complexity, and resource costs. There are three primary patterns to consider:

1. Database-per-Tenant

This approach provides the strongest isolation. Each tenant has their own dedicated database instance or schema.

  • Pros: Data is physically separated, making it easy to perform per-tenant backups or restorations and eliminating the risk of "noisy neighbor" queries affecting other tenants.
  • Cons: Extremely high management overhead. Migrating a schema requires running scripts against hundreds or thousands of databases, and you face significant connection pooling constraints.

2. Shared-Schema (Discriminator Columns)

In this pattern, all tenants reside in the same tables, identified by a tenant_id column.

  • Pros: Highly scalable and simple to manage. You run one set of migrations and share a single connection pool.
  • Cons: You must strictly enforce filtering at the application layer. One missing WHERE tenant_id = ? clause can lead to a catastrophic data leak.

3. Row-Level Security (RLS)

Often used in modern PostgreSQL deployments, RLS acts as a safety net for the Shared-Schema approach. Instead of relying solely on the application code to filter data, the database engine itself enforces row visibility.

-- Example: Defining an RLS policy in PostgreSQL
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation_policy ON orders
USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

By setting the session variable app.current_tenant_id at the start of a transaction, you ensure that even if a developer forgets to include tenant_id in a query, the database will return zero results rather than leaking data from other tenants.

When deciding between these, consider your compliance requirements and the scale of your tenant base. If you need absolute logical separation, Database-per-tenant is safer but expensive; if you need rapid iteration and cost efficiency, Shared-schema with RLS is the industry standard for modern SaaS architectures.

Key Takeaway: Choose between the physical isolation of Database-per-tenant for high-security compliance or the operational efficiency of Shared-schema with RLS for large-scale multi-tenant SaaS.