Tenant Context Resolution and Middleware
Resolve the current tenant from subdomains or tokens and propagate context through every dependency.
Why Tenant Context Matters
In a multi-tenant SaaS, a single FastAPI process serves many customers. Every request must be scoped to exactly one tenant, and getting this wrong leaks data across organizations.
The core problem: by the time a query runs deep inside a service or repository, the code needs to know which tenant it is acting for. We solve this with tenant context resolution:
- Identify the tenant from the incoming request (subdomain or token).
- Validate that the tenant exists and is active.
- Propagate that identity so every downstream dependency can read it.
This lesson builds that pipeline step by step.
Two Resolution Strategies
There are two common ways to discover the tenant for a request:
- Subdomain-based:
acme.app.commaps to tenantacme. Read from theHostheader. Great for browser sessions and per-tenant branding. - Token-based: a JWT carries a
tenant_id(often as a claim). Ideal for API clients and mobile apps where there is no subdomain.
Mature systems support both, with a clear precedence rule. A common choice: trust the token claim first (it is signed), then fall back to the subdomain. Whatever you pick, document it and enforce it consistently.
All lessons in this course
- Tenant Isolation Strategies and Trade-offs
- Tenant Context Resolution and Middleware
- Row-Level Security and Data Partitioning
- Usage Metering, Quotas and Billing Hooks