Skip to content
Aditya Bhalsod
← Web
WebAdvanced

Routing Read Replicas in a Schema-Per-Tenant Django App

How django-multi-tenant sends tenant reads to PostgreSQL replicas safely, by syncing the replica's schema, pinning writes to the primary and routing migrations.

  • #django
  • #postgresql
  • #multi-tenancy
  • #read-replicas
Contents
  1. How a request picks a schema
  2. A replica does not know which tenant it serves
  3. Some reads must stay on the primary
  4. Migrations and tasks follow the same rules
  5. Where this stops working

django-multi-tenant is a Django starter for SaaS projects where every customer gets their own PostgreSQL schema. It is built on django-tenants and comes with Celery, Docker Compose, a REST API and fourteen step-by-step guides. The repository is new, so read it as a documented starting point, not as something with a history behind it.

The basic schema-per-tenant setup is mostly configuration. The part that needed real code is read replicas, because tenant isolation depends on state that lives on one database connection, and a replica is a second connection.

How a request picks a schema

Each tenant is a row in the public schema with a schema_name, and each hostname is a Domain row that points at a tenant. TenantMiddleware extends django-tenants' TenantMainMiddleware. The parent class resolves the host and switches the connection to that tenant's schema with SET search_path. My subclass then returns a 403 if the tenant is suspended. After that, ordinary ORM queries only see the current tenant's tables. The example Project model has no tenant_id column and no filter to forget.

Which tables exist where is decided by two lists in settings:

Python
# Apps whose tables live ONLY in the "public" schema.
SHARED_APPS = [
    "django_tenants",  # must be first
    "apps.tenants",  # Tenant + Domain models
    "apps.core",
    "apps.analytics",  # global data; may be routed to its own database
    # ... contrib apps and admin
    "apps.users",  # platform staff accounts (public.users_user)
    # ... rest_framework, drf_spectacular, corsheaders
]

# Apps whose tables are created in EVERY tenant schema.
TENANT_APPS = [
    # ... contrib apps, admin
    "apps.users",  # tenant's own users (<schema>.users_user)
    "rest_framework.authtoken",
    "apps.projects",  # example business app, copy this pattern
]

users appears in both lists. The public schema holds platform staff, and each tenant schema holds that tenant's own users, so the same email can exist in two tenants as two separate accounts.

A replica does not know which tenant it serves

Replicas are switched on with one variable, DATABASE_REPLICA_URLS. config/databases.py registers each URL as replica_1, replica_2 and so on, and gives them the django-tenants backend too, so a schema can be applied to them. The router then sends reads to a random replica.

The catch is that the tenant is not part of the query. It is part of the connection's session, and the middleware set it on the primary connection only. So before a replica query runs, the router copies the primary's tenant across:

Python
def db_for_read(self, model, **hints):
    label = model._meta.app_label
    if label in self.app_routes:
        return self.app_routes[label]
    if not self.replicas or is_primary_pinned() or label in self.PRIMARY_ONLY_APPS:
        return PRIMARY
    alias = random.choice(self.replicas)
    self._sync_tenant(alias)
    return alias

@staticmethod
def _sync_tenant(alias: str) -> None:
    primary, replica = connections[PRIMARY], connections[alias]
    if replica.tenant is primary.tenant and replica.schema_name == primary.schema_name:
        return
    replica.set_tenant(primary.tenant, include_public=primary.include_public_schema)

_sync_tenant returns early when the replica already points at the same tenant and schema, so repeated reads in one tenant do not keep re-issuing the switch. The replica simply follows whichever schema is active on the primary at the moment of the query.

Some reads must stay on the primary

Three kinds of read skip the replicas.

Routed apps go to their own database. DATABASE_APP_ROUTES can send an app such as the example analytics app to a separate database that is not tenant-aware. If the route points at an alias that is not configured, build_databases drops it and the app falls back to the primary.

Tenant metadata always comes from the primary. PRIMARY_ONLY_APPS covers tenants, sessions, authtoken, auth and contenttypes. The comment in the router gives the reason: a lagging replica could otherwise resolve a domain to a tenant that was just deleted.

Requests that write are pinned. A row you just inserted may not have reached the replica yet, so apps/core/db.py keeps a flag in a ContextVar:

Python
_pinned: ContextVar[bool] = ContextVar("primary_db_pinned", default=False)

def is_primary_pinned() -> bool:
    return _pinned.get()

@contextmanager
def use_primary() -> Iterator[None]:
    token = _pinned.set(True)
    try:
        yield
    finally:
        _pinned.reset(token)

PrimaryPinningMiddleware wraps every POST, PUT, PATCH and DELETE in use_primary(), so every query in those requests, reads included, goes to the primary. A ContextVar keeps the flag isolated per thread and per asyncio task, and reset(token) restores the previous value, so nested blocks behave.

Migrations and tasks follow the same rules

Python
DATABASE_ROUTERS = [
    "config.db_routers.MultiDatabaseRouter",  # replicas + dedicated databases
    "django_tenants.routers.TenantSyncRouter",  # shared vs tenant apps
]
# ...
# Switch the schema on every tenant-aware connection, replicas included.
CELERY_TASK_TENANT_DATABASES = ("default", *DATABASE_REPLICAS)

My router runs first. Its allow_migrate refuses replicas, limits a routed app to its own alias, refuses every other app on an extra database, and returns None for the rest. None means "no opinion", so TenantSyncRouter still decides whether an app's tables go to the public schema or into every tenant schema. make migrate runs migrate_schemas and then a small migrate_extra command for the separate databases. In tests, each replica is marked as a mirror of default, so Django does not try to create a test database for it.

Celery uses CeleryApp from tenant-schemas-celery, which puts the current schema name into each task's headers. The worker switches to that schema before the task runs. CELERY_TASK_TENANT_DATABASES extends the switch to every replica, so a task queued from Acme's request reads Acme's tables wherever its queries land.

To try it locally, start the Compose replica profile, which clones the primary with pg_basebackup and runs it as a hot standby, then point DATABASE_REPLICA_URLS at the db-replica service.

Where this stops working

Replicas are optional. With DATABASE_REPLICA_URLS empty, db_for_read returns the primary for everything except routed apps, so a single-database project pays nothing for this code. When you do turn them on, a few limits are worth knowing.

Pinning lasts for one request. After a POST that redirects, the following GET is not pinned and can read from a replica that has not caught up. If that matters, I would add a short-lived cookie that pins the next few seconds after a write.

The replica is picked with random.choice. The router does not look at replication lag or replica availability, so a replica that falls behind keeps receiving its share of reads.

The users app is not in PRIMARY_ONLY_APPS, so on a GET the user behind a session is loaded from a replica. I would revisit that if deactivating an account has to take effect immediately.

The lesson carries beyond this repo: in a schema-per-tenant setup, any per-connection state such as search_path has to be copied to every connection that serves the request, or isolation quietly ends at the first replica.

Found this useful? Share it with your team.

Keep reading

More from Web and beyond