Multi-tenancy
Overview
Organizations are isolated by design: models carry organization_id, CRUD and queries take tenant arguments or rely on session context, and list/search paths must never return another org’s rows.
Multi-tenant Database Design
Organization Model
The foundation of multi-tenancy is the Organization model:
Organization References
Most models include a reference to the organization they belong to:
Direct Parameter Passing Architecture
The application uses direct parameter passing for tenant context instead of session variables, providing better performance and security.
Tenant Context Extraction
Tenant context is extracted from authenticated users and passed directly to CRUD operations:
CRUD Operations with Tenant Context
All CRUD operations accept organization_id and user_id parameters explicitly:
Query Filtering
Database queries include organization filtering to prevent data leakage:
Database Session Management
Simple Session Management
Database sessions are managed without tenant setup overhead:
FastAPI Dependencies
FastAPI dependencies provide both database sessions and tenant context:
Usage Patterns
For multi-entity operations (recommended):
For API request handling:
When to use each approach:
get_dbwith direct parameters: Multi-entity operations, background tasks, data migrations, initial data loading- Standard dependencies: Regular API endpoints where tenant context is set by authentication middleware
Authentication Integration
The multi-tenancy system integrates with authentication to set tenant context based on the authenticated user:
API Request Flow
Authenticated request → user/org from auth → tenant set on the session (where applicable) → queries respect RLS/org filters → context cleared after the request.
Superuser Access
Superusers can access data across organizations by bypassing the row-level security policies:
This feature is carefully controlled and only available to authenticated superusers.