SaaS Architecture in Django: Billing, Multi-Tenancy, and Scale
Building a SaaS platform is fundamentally different from building a standard web application. Multi-tenancy, billing integration, usage metering, and per-tenant feature flags introduce architectural complexity that ripples through every layer of your stack. Get the foundation wrong, and you'll spend months refactoring under pressure from paying customers.
Having built multiple multi-tenant Django platforms — from CRM systems to project management tools — I've refined an architecture that scales from first customer to thousands without requiring a rewrite. Here's the complete blueprint.
Need help with SaaS platform development? I provide SaaS platform development for businesses ready to grow. Learn about my SaaS platform development service or get in touch for a free consultation.
- Choosing Your Tenancy Model
- Plan Limit Enforcement
- Background Job Tenant Isolation
- Deployment and Migration Strategy
Choosing Your Tenancy Model
The first architectural decision is how to isolate tenant data. There are three approaches, each with distinct tradeoffs.
Shared database, shared schema stores all tenants in the same tables with a tenant_id foreign key on every row. This is the simplest to implement and cheapest to operate. Query performance depends on proper indexing — always create composite indexes with tenant_id as the leading column. The risk is accidental data leakage: a missing filter exposes one tenant's data to another. Mitigate this with a custom queryset manager that automatically scopes every query.
Shared database, separate schemas gives each tenant their own PostgreSQL schema within a single database. The django-tenants library implements this pattern well. Tenant isolation is enforced at the database level, reducing the risk of cross-tenant data leaks. The tradeoff is migration complexity: schema changes must be applied across all tenant schemas, and the migration process scales linearly with tenant count.
Separate databases per tenant provides the strongest isolation but the highest operational overhead. Each tenant gets their own database, which means independent backups, independent migrations, and a connection routing layer. Reserve this for enterprise customers with strict compliance requirements (healthcare, finance) or tenants who need dedicated infrastructure guarantees.
For most SaaS products, I recommend starting with shared schema and tenant_id scoping. It's the simplest to build, deploy, and monitor. You can always migrate high-value enterprise tenants to dedicated schemas or databases later.
Automatic Tenant Scoping in Django
The most dangerous bug in a multi-tenant system is showing one tenant's data to another. Prevent this architecturally, not just procedurally.
Create a base model and custom manager that every tenant-scoped model inherits from. The manager automatically filters by the current tenant, extracted from the request via middleware. This means developers can write Project.objects.all() and get only the current tenant's projects — no explicit filtering needed, no accidental leaks possible.
The middleware sets the current tenant based on the subdomain, a custom header, or a JWT claim — whatever your authentication strategy dictates. Store the tenant reference in thread-local storage or, better, in a ContextVar for async compatibility. Every queryset method on the custom manager reads this context and applies the filter transparently.
For admin access and cross-tenant operations (reporting, billing reconciliation), provide an explicit unscoped() method that bypasses the automatic filter. Restrict its usage to specific permission levels and log every invocation.
Shared database, shared schema stores all tenants in the same tables with a tenant_id foreign key on every row.
Stripe Billing Integration
Stripe is the standard for SaaS billing, and Django integrates with it cleanly through webhooks. The architecture has three components: subscription management, webhook processing, and entitlement enforcement.
Subscription management starts at signup. When a tenant creates an account, your backend creates a Stripe Customer, attaches the payment method, and creates a Subscription with the selected Price. Store the Stripe customer ID and subscription ID on your Tenant model. Never store card details — Stripe handles PCI compliance.
Webhook processing is where most implementations go wrong. Stripe sends events asynchronously, and your webhook handler must be idempotent — processing the same event twice should produce the same result. Key events to handle:
checkout.session.completed— activate the tenant's subscriptioninvoice.paid— extend the billing period, reset usage countersinvoice.payment_failed— enter grace period, notify tenant, restrict features after deadlinecustomer.subscription.updated— sync plan changes (upgrades, downgrades)customer.subscription.deleted— deactivate tenant, trigger data retention policy
Use a webhook processing queue (Celery with Redis) rather than processing synchronously in the HTTP handler. This prevents Stripe timeouts and allows automatic retries on failure. Store every raw webhook payload for debugging and audit trails.
Entitlement enforcement connects Stripe plan data to feature access. Maintain a plan-to-features mapping in your database. When a webhook updates a tenant's plan, recalculate their entitlements and cache them. Check entitlements at the view level (middleware or decorator) and at the API level (permission classes).
Never store card details — Stripe handles PCI compliance.
Plan Limit Enforcement
Every SaaS plan has limits: number of users, projects, API calls, storage, or other resources. Enforcing these limits must be both reliable and performant — you can't hit the database on every API request to check if the tenant has exceeded their quota.
The pattern I use: maintain a Redis hash per tenant with current usage counters. Increment counters atomically when resources are created. Check limits against the cached plan configuration before allowing resource creation. Periodically reconcile Redis counters with actual database counts to handle edge cases (direct database modifications, counter drift).
For soft limits (warning at 80%, blocking at 100%), use a middleware that checks usage ratios and injects warning headers or response metadata. The frontend reads these to display upgrade prompts at the right moment — not too early (annoying), not too late (surprising).
Usage Metering for Consumption-Based Billing
If your pricing includes consumption-based components (API calls, AI processing, storage), you need a metering pipeline that's accurate, durable, and doesn't add latency to the metered operations.
The architecture: operations emit usage events to a Redis stream (or Kafka for high volume). A background worker aggregates events into per-tenant, per-metric, per-period buckets. At billing time, report aggregated usage to Stripe via their Usage Records API.
Critical implementation details: use MULTI/EXEC transactions in Redis to prevent double-counting. Keep raw events in an append-only log for dispute resolution. Aggregate in time windows that align with your billing period. And always bill on server-side metrics, never client-reported usage — clients can be modified.
Want expert help with this? Let's make it happen.
Get a Free ConsultationFeature Flags per Tenant
Not every feature should be available to every plan, and you'll often want to beta-test features with specific tenants before general release. A per-tenant feature flag system solves both needs.
Store flags in a denormalized structure: a JSON field on the Tenant model for tenant-specific overrides, combined with plan-level defaults. The resolution order is: tenant override, then plan default, then global default. Cache the resolved flags in Redis with a TTL matching your acceptable staleness window (typically 60-300 seconds).
In templates and views, check flags through a consistent interface: tenant.has_feature('advanced_analytics'). This reads from cache first, falls back to database, and handles missing flags gracefully by returning the global default.
Background Job Tenant Isolation
Celery tasks in a multi-tenant system need the same scoping guarantees as web requests. The challenge: Celery workers don't have access to the HTTP request context that your middleware uses to identify the current tenant.
Pass the tenant ID explicitly as a task argument. Create a base task class that sets up the tenant context from this argument before executing the task body, and tears it down afterward. This ensures your auto-scoping queryset manager works correctly in background jobs.
For resource isolation, use separate Celery queues per plan tier. Free-tier tenants share a low-priority queue; paid tenants get higher-priority queues; enterprise tenants get dedicated workers. This prevents a free-tier tenant's bulk export from blocking a paid tenant's real-time notification.
Monitoring Per-Tenant Metrics
Standard application monitoring (response times, error rates, throughput) isn't enough for SaaS. You need per-tenant visibility to detect noisy neighbors, identify upgrade candidates, and enforce fair usage.
Instrument your middleware to emit metrics tagged with tenant_id: request count, response time percentiles, error rate, and active user count. Use these to build a tenant health dashboard showing resource consumption relative to plan limits.
Set up alerts for anomalies: a tenant suddenly generating 10x their normal API volume might be running a runaway script. A tenant with zero activity for 30 days is a churn risk. A tenant consistently hitting 90%+ of their plan limits is an upgrade opportunity — trigger an automated email or in-app prompt.
The monitoring layer also feeds back into your business forecasting: usage trends predict infrastructure costs, churn risk, and expansion revenue. This data is gold for SaaS operators.
Database Connection Routing
As you scale, database performance becomes your primary bottleneck. Django's database routing supports multiple databases out of the box. For multi-tenant applications, implement a router that directs reads to replicas and writes to the primary, with tenant-aware sharding when you outgrow a single primary.
Start with a simple primary/replica setup. Use Django's DATABASE_ROUTERS setting with a custom router that sends all reads to the replica and all writes to the primary. Add connection pooling via PgBouncer to handle connection overhead — Django's persistent connections help, but PgBouncer handles the thundering herd problem better at scale.
When a single database can't handle your write volume, shard by tenant. Route each tenant to a specific database server based on a consistent hash of their tenant ID. This is a significant architectural step — plan for it early even if you don't implement it until you need it.
Deployment and Migration Strategy
SaaS deployments must be zero-downtime. Your paying customers are using the platform 24/7, and any interruption directly impacts their business. Use rolling deployments with health checks: deploy new code to a subset of servers, verify health, then continue to the remaining servers.
Database migrations require extra care. Never run migrations that lock tables for extended periods. Use Django's AddIndex with CONCURRENTLY (via django.contrib.postgres) for index creation. For large data migrations, run them as background tasks rather than synchronous migration steps.
If you're building a SaaS product and want to get the architecture right from day one, I work with founders to design and implement scalable multi-tenant platforms. See why Django is the right foundation for business-critical applications, and explore our MCP integration demos to see how modern AI capabilities integrate into SaaS platforms.
Related reading: The Complete Guide to Multi-Tenant Django Applications · Why Django 6.1 Is Perfect for SaaS MVPs in 2027 · Modernizing Legacy Django: From 2.x to 6.1 Without a Rewrite



Frequently asked questions
How much does it cost to build a SaaS application?
An MVP with authentication, billing, basic features, and a landing page typically costs $15,000-50,000 with a freelance developer or small team, taking 2-4 months. A full-featured platform with multi-tenancy, advanced features, and integrations ranges from $50,000-200,000. Django reduces this by 30-40% compared to building from scratch in Node.js.
What is multi-tenancy and do I need it?
Multi-tenancy means one application instance serves multiple customers (tenants) with data isolation between them. You need it if you are building a B2B SaaS where each customer should only see their own data. Django supports three patterns: shared database with tenant column, separate schemas, or separate databases.
How do I add billing to a Django SaaS?
Use Stripe with django-stripe or dj-stripe for subscription billing. Implement: plan selection, checkout via Stripe Checkout or Elements, webhook handling for payment events, and a billing portal for customers to manage subscriptions. Stripe handles PCI compliance so you never touch card data directly.
Full-stack developer specializing in Django, AI automation, and Google Ads management. Building production SaaS platforms and custom web applications for businesses across the US.