Multi-tenancy
Overview
The Rhesis backend implements a robust multi-tenancy model that ensures complete data isolation between different organizations. This is achieved through a combination of database design, explicit parameter passing, and organization filtering in CRUD operations.
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:
Key advantages of this approach:
- No SET LOCAL overhead: Eliminates PostgreSQL session variable management
- Better performance: Reduces database round trips
- Explicit parameters: Makes tenant context visible in function signatures
- Easier debugging: Tenant context is explicit in stack traces
- Transparent transactions: Automatic commit/rollback handling
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
- Client makes a request to a protected endpoint
- Authentication middleware validates the request
- Current user and organization are extracted from the authentication context
- Tenant context is set in the database session
- Database queries automatically filter data based on the tenant context
- After the request completes, tenant context is cleared
Benefits of This Approach
- Security: Data isolation is enforced at the database level
- Simplicity: Application code doesn’t need to filter by organization
- Performance: Database indexes can be optimized for tenant-based queries
- Compliance: Helps meet data segregation requirements for regulatory compliance
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.