# Multi-Tenant Data Flow {#multi-tenant-data-flow}


How requests are scoped to tenants throughout the stack.


## Request Flow {#request-flow}






```mermaid
sequenceDiagram
    Client->>API: Request + JWT
    API->>JWT: Decode tenantId
    JWT->>RequestContext: Set tenantId
    RequestContext->>Guard: TenantPermissionGuard
    Guard->>Service: tenantId filter active
    Service->>Repository: WHERE tenantId = :id
    Repository->>Database: Scoped query
    Database-->>Client: Tenant-specific data
```






## Layer-by-Layer {#layer-by-layer}



### 1. JWT Token {#1-jwt-token}


Every JWT contains the `tenantId`:

```json
{
  "id": "user-uuid",
  "tenantId": "tenant-uuid",
  "role": "ADMIN",
  "exp": 1735689600
}
```


### 2. RequestContext {#2-requestcontext}


`RequestContext` stores the current tenant in async local storage:

```typescript
RequestContext.currentTenantId(); // returns tenant UUID
```


### 3. Guard Layer {#3-guard-layer}


`TenantPermissionGuard` validates:

- Token contains valid `tenantId`
- Tenant exists and is active


### 4. Service Layer {#4-service-layer}


All services extend `TenantAwareCrudService` which auto-filters by tenant:

```typescript
// Automatically adds WHERE tenantId = :currentTenant
const tasks = await this.taskService.findAll();
```


### 5. Repository Layer {#5-repository-layer}


Query builders append tenant filter:

```sql
SELECT * FROM task
WHERE "tenantId" = 'tenant-uuid'
  AND "organizationId" = 'org-uuid'
```


## Cross-Tenant Access {#cross-tenant-access}


Only `SUPER_ADMIN` role can access data across tenants.


## Related Pages {#related-pages}


- [Tenant Isolation](https://sourcey-gauzy.pages.dev/security/tenant-isolation/index.md) — security deep dive
- [Multi-Tenancy](https://sourcey-gauzy.pages.dev/architecture/multi-tenancy/index.md) — architecture overview
- [Request Lifecycle](https://sourcey-gauzy.pages.dev/architecture/request-lifecycle/index.md) — full request flow
