Multi-Tenancy Architecture
Relevant source files
The following files were used as context for generating this wiki page:
- packages/core/src/lib/tenant/tenant.entity.ts
- packages/mcp-server/src/lib/schema.ts
- packages/core/src/lib/core/context/request-context.ts
- packages/core/src/lib/tenant/tenant.controller.ts
- packages/core/src/lib/export-import/export/export.service.ts
- packages/core/src/lib/integration-tenant/integration-tenant.entity.ts
- packages/core/src/lib/warehouse/warehouse.entity.ts
- packages/plugins/job-proposal/src/lib/proposal/proposal.entity.ts
The Gauzy platform is designed with a multi-tenant architecture, allowing a single instance of the application to serve multiple client organizations while keeping their data isolated and secure. This is achieved through a hierarchical data model centered around Tenant and Organization entities, with data segregation enforced at the database and application layers.
The core principle is that every piece of organization-specific data is associated with a tenantId and often an organizationId. This ensures that when a user makes a request, the system can retrieve and manipulate only the data belonging to the tenant and organization they are currently operating within. This model supports both SaaS deployments and on-premise installations for large enterprises with multiple subdivisions.
Core Data Models
The multi-tenancy model is built upon a two-level hierarchy: Tenant and Organization. A Tenant is the highest-level container, representing a single customer or entity. Each Tenant can contain one or more Organization entities, which represent distinct business units, departments, or companies within that tenant.
Entity Relationship Diagram
This diagram illustrates the fundamental relationship between Tenants, Organizations, and other tenant-scoped entities.
Tenant Entity
The Tenant is the root entity for data isolation. It represents a customer account.
| Field | Type | Description |
|---|---|---|
id | string | Unique identifier for the tenant. |
name | string | The name of the tenant. |
logo | string | URL for the tenant's logo. |
standardWorkHoursPerDay | number | Standard work hours per day for the tenant. Defaults to 8. |
organizations | IOrganization[] | A one-to-many relation to all organizations belonging to this tenant. |
rolePermissions | IRolePermission[] | Tenant-specific role permissions. |
featureOrganizations | IFeatureOrganization[] | Tenant-specific feature flags. |
Sources: packages/core/src/lib/tenant/tenant.entity.ts:16-92
Tenant-Scoped Base Entities
To enforce data segregation, most data entities in the application extend from base classes that include tenantId and organizationId. The Zod schemas in packages/mcp-server/src/lib/schema.ts clearly define this pattern.
TenantBaseSchema: IncludestenantId.TenantOrganizationBaseSchema: ExtendsTenantBaseSchemaand addsorganizationId.
Almost all business-logic entities, such as Employee, Project, Task, Invoice, and Warehouse, are based on the TenantOrganizationBaseSchema, ensuring they are always tied to a specific tenant and organization.
// Example from packages/mcp-server/src/lib/schema.ts
const TenantBaseSchema = BaseEntitySchema.extend({
tenantId: z.string().uuid().readonly(),
tenant: z.lazy(() => OrganizationRefSchema).optional()
});
const TenantOrganizationBaseSchema = TenantBaseSchema.extend({
organizationId: z.string().uuid().readonly(),
organization: z.lazy(() => OrganizationRefSchema).optional()
});
Sources: packages/mcp-server/src/lib/schema.ts:160-170
The corresponding TypeORM entities, like IntegrationTenant or Warehouse, extend TenantOrganizationBaseEntity.
// Example from packages/core/src/lib/integration-tenant/integration-tenant.entity.ts
@MultiORMEntity('integration_tenant', { mikroOrmRepository: () => MikroOrmIntegrationTenantRepository })
export class IntegrationTenant extends TenantOrganizationBaseEntity implements IIntegrationTenant {
// ... entity fields
}
Sources: packages/core/src/lib/integration-tenant/integration-tenant.entity.ts:13-15
Request Handling and Context
Data isolation is enforced at runtime for every API request using a RequestContext. This context holds the tenantId, organizationId, and user for the duration of a single request, making this information available throughout the application services without needing to pass it through every function call.
RequestContext
The RequestContext class uses Continuation-Local Storage (cls-hooked) to create a request-scoped context. A middleware initializes this context for each incoming HTTP request, populating it with the current user, tenant, and organization identifiers.
Key static methods include:
RequestContext.currentTenantId(): Returns the ID of the tenant for the current request.RequestContext.currentOrganizationId(): Returns the ID of the organization for the current request.RequestContext.currentUser(): Returns the user object for the current request.
// packages/core/src/lib/core/context/request-context.ts
export class RequestContext extends Context {
// ...
static currentTenantId(): string {
const request = RequestContext.currentRequest();
if (request) {
const user = request.user as IUser;
if (user) {
return user.tenantId;
}
}
return;
}
// ...
}
Sources: packages/core/src/lib/core/context/request-context.ts:114-123
API Request Flow
The following diagram shows how an API request is processed to ensure tenant data isolation.
This mechanism is demonstrated in services like ExportService, which explicitly uses RequestContext.currentTenantId() to filter records before exporting them.
// packages/core/src/lib/export-import/export/export.service.ts
async getAsCsv(item: IRepositoryModel, where: { tenantId: string }, organizationId?: string): Promise<any> {
const conditions: FindManyOptions = {};
if (item.isTenantBased !== false) {
conditions['where'] = {
tenantId: where['tenantId']
};
}
// ...
}
Sources: packages/core/src/lib/export-import/export/export.service.ts:101-108
Tenant Management API
The platform provides a dedicated API for managing tenants, secured to be accessible only by users with the SUPER_ADMIN role.
Endpoints
The TenantController exposes the following endpoints:
| Method | Path | Description | Required Role |
|---|---|---|---|
GET | / | Retrieves the tenant record for the currently authenticated user. | Any authenticated user |
POST | / | Creates a new tenant. The creating user becomes the super admin. | SUPER_ADMIN |
PUT | / | Updates the current tenant's information. | SUPER_ADMIN |
DELETE | / | Deletes the current tenant and all associated data. | SUPER_ADMIN |
Sources: packages/core/src/lib/tenant/tenant.controller.ts:28-111
Onboarding a New Tenant
Creating a new tenant is handled by the onboardTenant method in TenantService. This process is restricted and typically performed during initial setup.
Summary
Gauzy's multi-tenancy architecture effectively isolates data for different customers using a Tenant and Organization hierarchy. This separation is enforced through tenantId and organizationId foreign keys on nearly all data tables. At the application level, the RequestContext ensures that every operation is automatically scoped to the correct tenant, providing a secure and scalable foundation for a multi-tenant SaaS application. Management of tenants is a privileged operation restricted to super administrators.