Tenant Isolation Plan for Shared Databases
Executive Summary
In a multi-tenant SaaS architecture using shared databases (e.g., PostgreSQL, MySQL, or similar), tenant isolation ensures data privacy, performance fairness, and resource equity. This plan focuses on three pillars: Row-Level Security (RLS) for data access control, Quotas for resource limits, and Hotspots mitigation for performance stability.
Assumptions:
- Database: PostgreSQL (native RLS support; adaptable to others like SQL Server or CockroachDB).
- Architecture: Shared schema with
tenant_id (UUID or integer) on all tables.
- Access via connection-pooled app servers (e.g., PgBouncer) with middleware setting tenant context.
- Monitoring: Prometheus + Grafana for observability.
Risks Addressed:
- Data leakage.
- Noisy neighbor (one tenant DoS-ing others).
- Compliance (GDPR, HIPAA via isolation proofs).
Implementation Timeline: 4-6 weeks (design 1w, PoC 2w, prod rollout 1-2w).
1. Row-Level Security (RLS)
RLS enforces "data silos" at the row level, invisible to tenants.
Design
-
Schema Changes:
ALTER TABLE orders ADD COLUMN tenant_id UUID NOT NULL;
ALTER TABLE users ADD COLUMN tenant_id UUID NOT NULL;
-- Index for perf: CREATE INDEX idx_orders_tenant ON orders (tenant_id, id);
-
Tenant Context:
- Use
SET LOCAL tenant_id = 'uuid-here'; in app middleware (e.g., Node.js/Express or Go middleware).
- Or session variables:
pg_catalog.current_setting('app.tenant_id').
-
RLS Policies (PostgreSQL-native):
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id')::UUID)
FOR ALL; -- SELECT, INSERT, UPDATE, DELETE
-- Admin bypass: CREATE POLICY admin_access ON orders FOR ALL USING (auth_role() = 'admin');
- Modes:
| Operation | Policy Scope |
|---|
| SELECT | tenant_id = current_tenant() |
| INSERT | NEW.tenant_id = current_tenant() (triggers enforce) |
| UPDATE | OLD.tenant_id = current_tenant() AND NEW.tenant_id = current_tenant() |
| DELETE | tenant_id = current_tenant() |
-
Enforcement Layers:
- App Layer: Validate
tenant_id on ingress.
- DB Triggers:
CREATE OR REPLACE FUNCTION enforce_tenant_id()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.tenant_id != current_setting('app.tenant_id')::UUID THEN
RAISE EXCEPTION 'Tenant mismatch';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_orders_tenant BEFORE INSERT OR UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION enforce_tenant_id();
- Connection Pooling: Tenant-aware pooling (e.g., PgBouncer with
SET commands per connection).
-
Testing:
- Cross-tenant queries fail with 403-like errors.
- Audit logs:
log_statement = 'all' filtered by tenant.
-
Edge Cases:
- Superuser/admin: Role-based bypass.
- Migrations: Bulk
UPDATE with temp policy disable.
2. Quotas
Prevent resource exhaustion with hard/soft limits.
Quota Types & Limits (Per Tenant, Daily/Monthly)
| Resource | Soft Limit | Hard Limit | Unit |
|---|
| Storage | 80% of 10GB | 10GB | Rows/GB |
| Queries | 1M qps | 1.2M qps | Queries |
| Data Ingress | 100GB | 120GB | Bytes |
| Compute (CPU) | 20% | 25% | % of pool |
Implementation
-
Storage Quotas (pgQuota extension or custom):
-- Install pg_quota: CREATE EXTENSION pg_quota;
SELECT create_schema_quota('tenant_schema', '10GB'); -- Or table-level
-- Custom trigger for row-level:
CREATE TABLE tenant_quotas (tenant_id UUID PRIMARY KEY, max_rows BIGINT DEFAULT 1000000);
CREATE FUNCTION check_row_quota() RETURNS TRIGGER AS $$ ... COUNT(*) > quota ... $$;
-
Query Rate Limits:
- Database:
pg_stat_statements + extension like hypopg for planning.
- Proxy: PgBouncer max_client_conn=per-tenant + app-side Redis rate limiter (e.g., 1000 req/min).
- External: API Gateway (Kong/Envoy) with tenant-keyed buckets.
-
Enforcement:
- Triggers/Views: Block INSERT/UPDATE if quota exceeded.
- Jobs: Cron (every 5min) scans
pg_stat_user_tables:
SELECT tenant_id, pg_size_pretty(pg_total_relation_size(oid)) AS size
FROM pg_class c JOIN tenant_tables t ON c.oid = t.table_oid
WHERE size > quota;
- Graceful Degradation: Soft: Warn/throttle; Hard: Reject with 429.
-
Billing Tie-In: Quota = plan tier; auto-upgrade prompts.
3. Hotspots Mitigation
Hotspots: Skewed queries/indexes/index scans monopolizing CPU/IOPS.
Detection
- Monitoring Queries:
-- pg_stat_statements + tenant grouping
SELECT query, calls, total_time, mean_time,
(SELECT tenant_id FROM active_sessions WHERE pid = pid LIMIT 1) AS tenant_id
FROM pg_stat_statements ORDER BY total_time DESC LIMIT 10;
- Tools: pgBadger logs, EXPLAIN ANALYZE dashboards, New Relic DB agent.
- Alerts: >5s latency spikes per tenant, CPU >80% sustained.
Mitigation Strategies
| Hotspot Type | Prevention | Remediation |
|---|
| Index Miss | Auto-index on (tenant_id, frequent_cols); Partial indexes: WHERE tenant_id = current_tenant(). | pg_squeeze for reorganize. |
| Seq Scans | VACUUM ANALYZE nightly per tenant; Query hints. | Materialized views per tenant. |
| Lock Contention | Advisory locks with tenant prefix. | Short transactions; SKIP LOCKED. |
| Connection Storm | PgBouncer: reserve_pool_per_tenant; App: Circuit breakers. | Auto-scale pool; Kill long queries (>30s). |
| Write Amplification | Partition tables by tenant_id (e.g., range or hash). | Sharding trigger if >1M rows/tenant. |
Rollout & Operations
- PoC: 2 tenants, load test (pgbench multi-tenant).
- Migration: Add
tenant_id null-first, backfill, then NOT NULL + RLS.
- Fallback: Dedicated DBs for high-value tenants.
- Audits: Quarterly penetration tests; Data lineage proofs.
- Costs: +10-20% overhead (RLS perf hit mitigated by indexes).
This plan delivers logical isolation rivaling physical DB-per-tenant, at 1/10th cost. Questions? Let's deduce further. 🕵️