# Multi-Tenancy

High-performance multi-tenant support with zero-allocation context and RLS integration.

## Isolation Strategies

### Row-Level Security (RLS)

Database-enforced filtering. Best performance, shared schema.

### Schema-Based

Separate schema per tenant. Good isolation, more complex migrations.

### Database-Based

Separate database per tenant. Maximum isolation, highest overhead.

## Zero-Allocation Tenant Context

Use task-local storage for zero-heap-allocation tenant propagation in async code.

## PostgreSQL Row-Level Security

Best performance option. Database handles all filtering automatically.

## Sharded Tenant Cache

High-concurrency LRU cache with reduced lock contention.

## Per-Tenant Connection Pools

Isolated connection resources per tenant.

## Statement Caching

Reuse prepared statements across requests for better performance.

## Performance Comparison

Strategy | Isolation | Performance | Complexity
--- | --- | --- | ---
RLS | Good | Excellent | Low
Schema-Based | Better | Good | Medium
Database-Based | Maximum | Good | High

## Best Practices

### ✅ Do

- Derive tenant ID from auth tokens server-side
- Use RLS for PostgreSQL when possible
- Cache tenant lookups with TTL
- Test tenant isolation thoroughly

### ❌ Don't

- Trust client-provided tenant IDs
- Skip RLS policy verification
- Share connections across tenants without RLS