Prompt
How do I handle multi-tenant data in PostgreSQL for a SaaS app?
Latest observation
For a SaaS app, PostgreSQL gives you a few solid multi-tenant patterns. The best choice depends on your isolation, scale, and operational needs.
Common multi-tenant approaches
1) Shared database, shared schema
All tenants share the same tables, with a tenant_id column on every tenant-owned row.
Example:
CREATE TABLE orders (
id bigserial PRIMARY KEY,
tenant_id bigint NOT NULL,
customer_id bigint NOT NULL,
total numeric(12,2) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX idx_orders_tenant_id ON orders (tenant_id);
Pros
- Simple to operate
- Cheapest to run
- Easy to scale early on
- Good for many small tenants
Cons
- Must be very careful to always filter by tenant
- Harder to do tenant-specific backups/restores
- Noisy-neighbor risk unless you add controls
Best practices
- Put
tenant_idin every tenant-owned table - Use composite unique keys, e.g.
UNIQUE (tenant_id, email) - Always index
tenant_id - Consider PostgreSQL Row-Level Security (RLS) to enforce isolation
2) Shared database, separate schema per tenant
Each tenant gets its own schema, like tenant_123.orders.
Pros
- Better logical separation than shared schema
- Easier tenant-specific customization
- Can be useful for enterprise customers
Cons
- More complex migrations
- Harder to manage at scale with many tenants
- Cross-tenant reporting becomes awkward
Best for
- Small number of large tenants
- Stronger isolation than shared-schema, without full DB-per-tenant overhead
3) Separate database per tenant
Each tenant has its own PostgreSQL database.
Pros
- Strong isolation
- Easy per-tenant backup/restore
- Easier compliance story
Cons
- More ops overhead
- More expensive
- Hard to manage many tenants
- Connection management becomes more complex
Best for
- High-value tenants
- Strict compliance requirements
- Larger enterprise deployments
Recommended default for most SaaS apps
Start with shared database + shared schema + tenant_id, and add Row-Level Security if you want database-enforced tenant isolation.
This gives the best balance of simplicity and scalability.
How to implement safely
1) Add tenant_id to every relevant table
CREATE TABLE tenants (
id bigserial PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE projects (
id bigserial PRIMARY KEY,
tenant_id bigint NOT NULL REFERENCES tenants(id),
name text NOT NULL
);
2) Use composite uniqueness
If names must be unique per tenant:
CREATE UNIQUE INDEX uniq_projects_tenant_name
ON projects (tenant_id, name);
3) Index for tenant access patterns
CREATE INDEX idx_projects_tenant_id ON projects (tenant_id);
CREATE INDEX idx_projects_tenant_created_at ON projects (tenant_id, created_at DESC);
4) Enforce isolation with Row-Level Security
RLS can prevent accidental cross-tenant access.
Example:
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON projects
USING (tenant_id = current_setting('app.tenant_id')::bigint);
Then in your app, set the tenant for each request/transaction:
SET app.tenant_id = '123';
Important:
Use transactions carefully so the tenant setting applies only where intended. Many apps set it at the start of each request.
Operational tips
Connection pooling
If you use PgBouncer or similar, be careful with session variables like app.tenant_id.
- Prefer transaction pooling with explicit
SET LOCAL - Or use app-side tenant filtering plus RLS
Migrations
For shared schema:
- Run one migration across all tenants at once
- Test carefully because every tenant uses the same schema
For schema-per-tenant:
- Build migration tooling that loops over schemas
Backups and restores
- Shared schema: restoring one tenant is harder
- If per-tenant restore matters, consider separate schema or database
Analytics/reporting
- Shared schema makes global reporting easy
- For huge tables, consider partitioning by
tenant_idor by time, depending on query patterns
When to use partitioning
Partitioning is not a replacement for multi-tenancy, but can help when tables get large.
Options:
- By tenant_id: useful if tenants are large and isolated access is common
- By time: useful for event or audit tables
- Sometimes both, but that increases complexity
Practical recommendation
A common progression is:
- Start with shared DB + shared schema
- Add
tenant_ideverywhere - Use composite indexes and constraints
- Add RLS if you want stronger safety
- Move special enterprise tenants to separate schemas or databases if needed
Rule of thumb
- Many small tenants → shared schema
- Fewer large tenants → schema per tenant or DB per tenant
- Strict compliance / enterprise → separate DB per tenant
If you want, I can also show:
- a concrete PostgreSQL schema design,
- an RLS setup example,
- or how to do tenant isolation in Rails/Django/Node.