Prompt
multi tenant saas architecture auth billing observability
Latest observation
Here’s a practical multi-tenant SaaS architecture view of auth, billing, and observability.
1) Core architecture shape
A common layout:
- Frontend
- API Gateway / BFF
- Auth service / identity provider
- Tenant service (tenant metadata, plans, limits)
- Core app services (business logic)
- Billing service
- Observability stack
- Shared infrastructure
- DB(s)
- cache
- message bus
- object storage
Key concept: every request should resolve to:
- who is the user?
- which tenant are they in?
- what can they do?
- is the tenant allowed to use this feature?
2) Multi-tenancy models
A. Shared DB, shared schema
- All tenants share the same tables.
- Every row has
tenant_id.
Pros
- Cheapest
- Easiest to operate initially
- Great for many small tenants
Cons
- Strong need for tenant isolation in code
- Harder to do per-tenant performance tuning
- Risk of accidental data leakage if queries miss
tenant_id
B. Shared DB, separate schema
- Each tenant gets its own schema.
Pros
- Better isolation than row-based
- Easier tenant-specific migrations than separate DBs sometimes
Cons
- More operational overhead
- Schema migrations become more complex
C. Separate DB per tenant
- Strong isolation, best for enterprise or regulated customers.
Pros
- Best isolation
- Easier compliance story
- Easier noisy-neighbor control
Cons
- Operationally expensive
- Harder migrations at scale
Recommended default
For most SaaS products:
- start with shared DB +
tenant_id - design abstraction so you can later move high-value tenants to dedicated DBs
3) Authentication and authorization
Authentication
Use an IdP such as:
- Auth0
- Clerk
- Cognito
- Azure AD / Entra ID
- Keycloak
Typical flow:
- User logs in via IdP
- App receives JWT / session
- Backend validates token
- Backend resolves tenant membership
Authorization
You need two layers:
A. Tenant-level authorization
- Is the user part of tenant X?
- What role do they have in tenant X?
Examples:
owneradminmemberbilling_adminread_only
B. Resource-level authorization
- Can this user access this project/document/invoice within the tenant?
Best practice
Store membership like:
userstenantstenant_memberships(user_id, tenant_id, role)
If users can belong to multiple tenants, this is essential.
Token design
JWT should usually contain:
- user id
- auth context
- maybe current tenant id
- maybe roles/scopes
But avoid stuffing too much tenant-specific data into JWT if membership changes frequently.
Tenant resolution
Choose one:
- subdomain:
acme.app.com - path:
/t/acme/... - header:
X-Tenant-ID - domain mapping:
acme.com
Subdomain is common and clean.
4) Billing architecture
Billing should be a separate bounded context.
Billing responsibilities
- plan definitions
- subscription lifecycle
- usage metering
- invoicing
- payment processing
- tax handling
- dunning / failed payments
- entitlements
Core objects
plansubscriptioninvoicepayment_methodusage_recordentitlement
Flow
- Tenant subscribes to a plan
- Billing service creates subscription with Stripe/Paddle/etc.
- Billing service stores tenant’s plan/limits
- App checks entitlements on each request or caches them
- Usage events are emitted asynchronously
- Billing aggregates usage and bills accordingly
Important design choice: billing vs entitlements
Do not make every app request call the billing provider.
Instead:
- billing provider = source of truth for payments
- entitlement service/cache = source of truth for what tenant can use right now
Common billing patterns
Flat-rate SaaS
- simpler
- just check active subscription
Usage-based SaaS
- track meter events
- aggregate usage daily/hourly
- send to billing provider
Hybrid
- base subscription + usage overage
Practical advice
Use a payment processor like:
- Stripe Billing
- Paddle
- Chargebee
And keep your own internal:
- tenant plan state
- entitlements
- usage ledger
5) Observability
Observability should be tenant-aware.
Three pillars
- logs
- metrics
- traces
Required tags/labels
Every signal should include:
tenant_iduser_idif applicablerequest_idtrace_idserviceenvironment
Logs
Use structured logs:
{
"level": "info",
"tenant_id": "t_123",
"user_id": "u_456",
"request_id": "req_789",
"message": "Invoice generated"
}
Metrics
Track:
- requests per tenant
- latency per tenant
- error rate per tenant
- active users per tenant
- billing usage per tenant
- queue lag per tenant
Be careful: high-cardinality labels like tenant_id can explode metric cost.
Use:
- top tenants only
- sampled metrics
- aggregated buckets
- separate dashboards for enterprise tenants
Traces
Include tenant context in trace attributes:
tenant.iduser.idsubscription.plan
Alerting
Useful alerts:
- spike in 5xx for one tenant
- payment failures
- usage quota nearing limit
- auth failures
- data pipeline lag
- tenant-specific latency regression
6) Data isolation and security
Must-haves
- row-level tenant filtering in every query
- automated tests for tenant isolation
- RLS if using Postgres
- encryption at rest
- secrets isolation
- audit logs for sensitive actions
Good patterns
- enforce tenant scope in data access layer
- never trust client-provided tenant_id alone
- resolve tenant from authenticated session + tenant membership
- use signed links or scoped tokens for tenant-specific resources
7) Recommended request flow
- User visits tenant subdomain
- Auth verifies identity
- Backend resolves tenant
- Backend checks membership and role
- Backend checks entitlements
- Request hits business service
- Service writes logs/traces with tenant context
- Async events go to billing/analytics pipeline
8) Suggested service boundaries
A clean split:
- Identity/Auth
- Tenant management
- Entitlements
- Billing
- Core product APIs
- Event ingestion / usage metering
- Observability / audit pipeline
9) Tech stack example
One possible setup:
- Frontend: Next.js
- API: Node.js / NestJS or Go
- Auth: Auth0 / Clerk / Keycloak
- DB: Postgres + RLS
- Cache: Redis
- Queue: SQS / RabbitMQ / Kafka
- Billing: Stripe
- Metrics: Prometheus + Grafana
- Logs: ELK / Loki
- Tracing: OpenTelemetry + Tempo/Jaeger
10) Pitfalls to avoid
- forgetting
tenant_idin queries - using billing provider as your app authorization source
- mixing auth and billing logic in the same service
- putting high-cardinality tenant IDs into every metric without control
- not modeling multi-tenant membership explicitly
- not designing for plan/entitlement changes
- relying only on frontend checks for access control
If you want, I can turn this into one of these:
- a reference architecture diagram
- a database schema
- a microservices vs monolith comparison
- a concrete AWS/GCP implementation
- a Stripe + Auth0 + Postgres design