Saltar al contenido
Web Development

The Complete Guide to Multi-Tenant Django Applications

Ruslan Danelian 11 min de lectura
¡Copiado!
The Complete Guide to Multi-Tenant Django Applications

Building a multi-tenant application means serving multiple customers from a single codebase while keeping their data completely isolated. Whether you are building a SaaS platform, a white-label solution, or an internal tool serving multiple departments, tenant isolation is the most critical architectural decision you will make. Get it wrong and you face data leaks, performance degradation, and a codebase that grows increasingly difficult to maintain. This guide covers the three major isolation models, implementation details for each, and the trade-offs that should drive your decision.

Need help with django development? I provide django development for businesses ready to grow. Learn about my django development service or get in touch for a free consultation.

Key Takeaways
  • Understand why Tenant Isolation Matters More Than You Think
  • Row-Level Security in PostgreSQL
  • Background Task Isolation
  • Choosing the Right Model for Your Project

Why Tenant Isolation Matters More Than You Think

A data leak between tenants is not just a bug — it is a business-ending event. If customer A can see customer B's financial data, your SaaS company faces lawsuits, regulatory fines, and irreparable reputation damage. Beyond security, tenant isolation affects performance (one tenant's heavy query should not slow down others), customization (tenants may need different configurations, branding, or even features), and operations (you need to be able to back up, migrate, or delete a single tenant's data without affecting others).

Django does not provide multi-tenancy out of the box, but its ORM, middleware system, and signal framework give you the building blocks to implement any isolation model cleanly. The question is not whether Django can handle multi-tenancy — it is which isolation model fits your specific requirements. Having built several multi-tenant Django applications, I will walk through each approach with real code.

Three Isolation Models

📊 Illustration: infographic summarizing Three Isolation Models
Visual guide: Three Isolation Models

Each model offers a different balance of isolation strength, operational complexity, and resource efficiency.

Shared Database, Shared Schema (Row-Level Isolation)

All tenants share the same database and tables. A tenant_id column on every model filters data per tenant. This is the simplest to implement, the most resource-efficient, and the easiest to manage operationally. However, the isolation guarantee depends entirely on your application code — a missing filter in one query exposes all tenants' data. This model works best for applications with many small tenants (hundreds or thousands) where the data model is identical across tenants.

Shared Database, Separate Schemas (Schema-Per-Tenant)

Each tenant gets their own PostgreSQL schema within a shared database. Tables are physically separated, but database-level resources (connections, memory, CPU) are shared. This provides stronger isolation than row-level filtering because a missing WHERE clause cannot cross schema boundaries. The trade-off is migration complexity — when you add a column, you must migrate every schema. This model suits applications with dozens to low hundreds of tenants who need stronger data isolation without the cost of separate databases.

Separate Databases (Database-Per-Tenant)

Each tenant has their own database. This provides the strongest isolation, the simplest backup and restore story, and the ability to place high-value tenants on dedicated hardware. The cost is high: connection pooling becomes complex, migrations must run against every database, and you need infrastructure automation to provision new tenants. This model is for enterprise SaaS where tenants demand contractual data isolation guarantees or where regulatory requirements mandate it.

If customer A can see customer B's financial data, your SaaS company faces lawsuits, regulatory fines, and irreparable reputation damage.

Row-Level Security in PostgreSQL

For the shared schema model, PostgreSQL's Row-Level Security (RLS) adds a database-level safety net on top of your application filtering. Even if your Django code has a bug that omits a tenant filter, the database itself will refuse to return rows belonging to other tenants.

-- Enable RLS on a table
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;

-- Create a policy that filters by the current tenant
CREATE POLICY tenant_isolation ON orders
    USING (tenant_id = current_setting('app.current_tenant_id')::int);

-- Force RLS even for table owners (important for security)
ALTER TABLE orders FORCE ROW LEVEL SECURITY;

Your Django middleware sets the PostgreSQL session variable before any query runs:

# middleware.py
from django.db import connection

class TenantMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        tenant = getattr(request, "tenant", None)
        if tenant:
            with connection.cursor() as cursor:
                cursor.execute(
                    "SET app.current_tenant_id = %s", [tenant.id]
                )
        response = self.get_response(request)
        return response

This middleware approach means every database query in the request automatically inherits the tenant filter at the database level. ORM queries, raw SQL, and even queries from third-party packages are all filtered. It is defense in depth — your application code should still filter by tenant, but RLS catches mistakes. The only caveat is that management commands and background tasks must explicitly set the tenant context, since they run outside the request-response cycle.

Pro Tip

It is defense in depth — your application code should still filter by tenant, but RLS catches mistakes.

django-tenants vs django-multitenant

Two mature libraries handle the heavy lifting for schema-per-tenant isolation.

django-tenants is the most established option. It uses PostgreSQL schemas and routes tenants by subdomain (e.g., acme.yourapp.com). It provides a TenantMixin for your tenant model, a middleware that resolves the tenant from the request's hostname, and automatic schema switching. Shared data (plans, pricing) lives in the public schema; tenant-specific data lives in per-tenant schemas.

django-multitenant takes a different approach, using a TenantModel mixin that adds tenant_id to every model and automatically scopes all ORM queries. It supports composite primary keys and can distribute data across multiple database nodes using Citus. This library is better suited for applications with very large numbers of tenants or those running on distributed PostgreSQL.

For most new SaaS projects, I recommend django-tenants if you have fewer than 500 tenants and want schema-level isolation, or the row-level approach with RLS if you have thousands of tenants and need simplicity. For more on building the billing layer on top of either approach, see our guide on SaaS architecture with Django.

Migration Strategy for Schema-Per-Tenant

Schema-per-tenant introduces migration complexity. When you add a field, you are not running one migration — you are running it against every tenant schema. For 50 tenants, this takes 50 times as long. For 500 tenants, it can take hours.

# Run migrations for all tenants
python manage.py migrate_schemas --shared   # public schema first
python manage.py migrate_schemas --tenant   # all tenant schemas

# Run for a specific tenant only
python manage.py migrate_schemas --schema=acme_corp

Strategies for managing migration time at scale include running migrations in parallel (the --executor=parallel flag in django-tenants), scheduling migrations during maintenance windows, using zero-downtime migration patterns (adding nullable columns first, then backfilling, then adding constraints), and testing migrations against a representative sample of tenant schemas before running against all tenants in production.

Always run migrations against your largest tenant schema in a staging environment first. A migration that completes in milliseconds on an empty schema might lock a table with millions of rows for minutes. Use pglock monitoring and set lock timeout thresholds to prevent cascading failures.

Want expert help with this? Let's make it happen.

Get a Free Consultation

Background Task Isolation

🎯 Illustration: diagram illustrating Background Task Isolation
Visual guide: Background Task Isolation

Celery tasks run outside the request-response cycle, so your tenant middleware does not apply. Every Celery task that touches tenant data must explicitly set the tenant context. The cleanest pattern is a base task class that handles this automatically.

# tasks.py
from celery import Task
from django.db import connection

class TenantTask(Task):
    def __call__(self, *args, **kwargs):
        tenant_id = kwargs.pop("tenant_id", None)
        if tenant_id:
            # For django-tenants: switch schema
            from django_tenants.utils import schema_context
            with schema_context(self._get_schema(tenant_id)):
                return super().__call__(*args, **kwargs)
        return super().__call__(*args, **kwargs)

@app.task(base=TenantTask)
def send_invoice(invoice_id, tenant_id=None):
    invoice = Invoice.objects.get(id=invoice_id)
    # ... tenant context is already set by TenantTask

For Celery Beat scheduled tasks that run across all tenants, iterate over tenants and dispatch one task per tenant. Never process all tenants in a single task — if it fails partway through, you have no way to resume from the point of failure. Individual tasks per tenant give you retry semantics, monitoring, and parallelism for free.

Security Audit Checklist

💡 Illustration: conceptual illustration of Security Audit Checklist
Visual guide: Security Audit Checklist

Before launching a multi-tenant application, verify every item on this checklist. These are the issues I have seen cause real incidents in production systems.

  • ORM queries: Grep your codebase for any .objects.all() or .objects.filter() that does not include a tenant filter. In the shared schema model, every queryset must be scoped. Consider a custom manager that adds the filter automatically.
  • Admin interface: Django admin does not respect tenant isolation by default. Either disable admin for tenant data entirely or customize every ModelAdmin.get_queryset() to filter by tenant.
  • File uploads: Ensure uploaded files are stored in tenant-namespaced paths (media/{tenant_id}/invoices/). A flat media directory risks filename collisions and makes per-tenant cleanup impossible.
  • Cache keys: Prefix all cache keys with the tenant identifier. Without this, Tenant A's cached dashboard might be served to Tenant B.
  • Email templates: Verify that notification emails pull the correct tenant's branding and do not leak one tenant's data into another's email.
  • API endpoints: Every API endpoint, including search, autocomplete, and export, must respect tenant boundaries. Test explicitly by authenticating as Tenant A and trying to access Tenant B's resources via direct ID manipulation.
  • Management commands: Any command that processes data must accept a --tenant argument or iterate safely. A command that runs without tenant context against a shared database can corrupt or expose data.
  • Logging: Include tenant_id in your structured logs. When debugging a production issue, you need to filter logs by tenant immediately.

Choosing the Right Model for Your Project

The decision comes down to four factors: the number of tenants, the sensitivity of data, the complexity of per-tenant customization, and your operational capacity. For a new SaaS MVP, start with the shared schema model and RLS — it is the simplest to implement and operate, and you can always migrate to schema-per-tenant later if a customer demands it. For enterprise products where contracts specify data isolation, schema-per-tenant with django-tenants provides the right balance. Reserve database-per-tenant for the rare case where regulatory requirements or extreme performance isolation demands justify the operational overhead.

Whatever model you choose, build tenant isolation into your test suite from day one. Create fixtures with at least two tenants and assert that queries for Tenant A never return Tenant B's data. This is not a test you write once — it should run on every CI build, catching isolation regressions before they reach production. If you need help architecting a multi-tenant system, our SaaS platform development service includes tenant isolation design as a standard deliverable.

Related reading: PostgreSQL Full-Text Search vs Elasticsearch: A Practical Guide · Website Speed Optimization: Why Your Django Site Loads Slow · Modernizing Legacy Django: From 2.x to 6.1 Without a Rewrite

The Complete Guide to Multi-Tenant Django Applications infographic (English version)
The Complete Guide to Multi-Tenant Django Applications infographic (versión en español)
The Complete Guide to Multi-Tenant Django Applications infographic (версия на русском)
📌 Save this infographic for quick reference

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.

Ruslan Danelian
Ruslan Danelian

Desarrollador full-stack especializado en Django, automatización con IA y gestión de Google Ads. Construyo plataformas SaaS de producción y aplicaciones web personalizadas para empresas en todo EE.UU.

Lea a continuación

¿Tiene un proyecto en mente?

Cuénteme qué necesita. En un plazo de un día hábil le enviaré un plan con cronograma y precio fijo.

Year-end offer

20% off AI tools & custom CRM

AI chat assistants, DM bots, lead scoring and a CRM built around your business.

Claim 20% off