Multi-tenancy with apartment gem

9307
0

SaaS applications serving multiple customers (tenants) need data isolation to prevent cross-tenant data leaks. The apartment gem provides schema-based multi-tenancy for PostgreSQL where each tenant gets a separate schema, ensuring complete database-level isolation. Tenant switching happens via Apartment::Tenant.switch(tenant_name), typically in a middleware or controller concern that extracts the tenant from subdomain or request headers. Migrations run across all tenant schemas automatically. This approach provides strong isolation with reasonable performance overhead. The alternative—row-based tenancy with a tenant_id column—is simpler but requires perfect discipline in all queries to avoid accidental cross-tenant data exposure. Schema-based tenancy makes mistakes obvious.