Backend & Full Stack Engineer Guide: Multi-Site & Multi-Tenant Django in One WSGI/ASGI Process

Running a separate Gunicorn or Uvicorn worker pool for every white-label customer domain or micro-site wastes gigabytes of RAM when each process loads an identical copy of Python, Django, and third-party libraries into memory. By routing incoming requests dynamically inside a single WSGI/ASGI process pool based on the validated Host header, one fleet of containers can serve dozens of distinct brand domains, custom URL hierarchies, and tenant themes at near-zero marginal memory cost. As a Senior Backend Engineer and Full Stack Engineer, here is how I architect high-density multi-site and multi-tenant Django deployments.

1. Dynamic request.urlconf Switching via Host-Routing Middleware

Django resolves URLs per request by checking getattr(request, "urlconf", settings.ROOT_URLCONF). A custom middleware placed immediately after SecurityMiddleware can inspect the normalized HTTP host and bind a domain-specific root URL configuration or tenant context before view resolution begins:

from django.http import HttpRequest, HttpResponseBadRequest
from django.core.cache import cache

HOST_URLCONF_MAP = {
    "aldianfazrihady.com": "afcom.urls",
    "www.aldianfazrihady.com": "afcom.urls",
    "docs.example-saas.com": "docs_portal.urls",
    "status.example-saas.com": "status_portal.urls",
}

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

    def __call__(self, request: HttpRequest):
        raw_host = request.get_host().split(":")[0].lower()
        urlconf = HOST_URLCONF_MAP.get(raw_host)

        if not urlconf:
            # Lookup custom white-label tenant domain in Redis with 5-minute TTL
            tenant_info = cache.get(f"tenant_domain:{raw_host}")
            if tenant_info is None:
                return HttpResponseBadRequest("Unrecognized domain host.")
            request.tenant_id = tenant_info["tenant_id"]
            request.urlconf = "tenant_portal.urls"
        else:
            request.tenant_id = "default"
            request.urlconf = urlconf

        response = self.get_response(request)
        response["Vary"] = "Host"
        return response

2. Preventing Cross-Site Cache Poisoning & Session Leakage

When multiple domains share a single Django process and Redis cache cluster, two subtle bugs can cause cross-site data leaks if not explicitly guarded:

  • Vary: Host Header for CDN & Reverse Proxies: Always emit Vary: Host (or configure CloudFront / Nginx cache keys to include $host) so that `/` on `docs.example-saas.com` never serves cached HTML from `/` on `status.example-saas.com`.
  • Tenant-Prefixed Cache Keys: Configure a custom KEY_FUNCTION in settings.CACHES that prepends the active host or tenant_id stored in a `contextvars.ContextVar`, ensuring `cache.get("homepage_stats")` is strictly isolated per domain.

3. Hire a Senior Backend & Full Stack Django Engineer

Consolidating multi-site infrastructure or building white-label B2B SaaS platforms? Explore my Backend Engineer Pillar Guide, review my Full Stack Engineer Guide, or book a 1-Day Django Architecture Sprint.


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 15+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs