← Back to Django, page 3

django-0046 · Hard senior

How do you use multiple databases in Django, for example a read replica, and what does a database router do?

Define several aliases in DATABASES and either pick one explicitly with .using("alias") and save(using=...), or add a router class in DATABASE_ROUTERS whose db_for_read, db_for_write, allow_relation and allow_migrate methods choose automatically. A common setup sends writes to the primary and reads to replicas, while keeping reads that must see a just-written row on the primary to avoid replication lag surprises.

Full answer

Settings:

python
DATABASES = {
    "default": {...},          # primary, read-write
    "replica": {...},          # read-only copy
}
DATABASE_ROUTERS = ["core.routers.PrimaryReplicaRouter"]

Manual selection:

  • Student.objects.using("replica").filter(...)
  • obj.save(using="default")
  • transaction.atomic(using="default")

A router is a plain class with up to four methods. Each returns an alias, True/False, or None to let the next router decide:

  • db_for_read(model, **hints)
  • db_for_write(model, **hints)
  • allow_relation(obj1, obj2, **hints): may these two objects be related?
  • allow_migrate(db, app_label, model_name=None, **hints): should this model's tables exist on this database?

Uses:

  1. Read replicas to spread read load.
  2. Splitting apps across databases, such as analytics tables on a separate server.
  3. A legacy database that Django reads but never migrates (allow_migrate returns False, model has managed = False).

Replication lag is the main trap. Replicas run behind the primary by milliseconds to seconds. A user who updates their profile and is redirected to a page reading from a replica may see old data. Fixes: route reads to the primary for a short window after a write (stored in the session or a context variable), or read from the primary inside the same request after writing. Inside transaction.atomic(), keep all queries on the primary.

Limits: Django does not support foreign keys or joins across databases. Each database also needs its own transaction handling. In tests, set databases = {"default", "replica"} on the test class, and configure the replica with TEST: {"MIRROR": "default"} so it points at the same test database.

python
import sys
import tempfile
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={
        "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": tempfile.mkdtemp() + "/primary.db"},
        "replica": {"ENGINE": "django.db.backends.sqlite3", "NAME": tempfile.mkdtemp() + "/replica.db"},
    },
    DATABASE_ROUTERS=["__main__.PrimaryReplicaRouter"],
)
django.setup()

import contextvars
from django.db import connections, models

stick_to_primary = contextvars.ContextVar("stick_to_primary", default=False)


class PrimaryReplicaRouter:
    def db_for_read(self, model, **hints):
        return "default" if stick_to_primary.get() else "replica"

    def db_for_write(self, model, **hints):
        stick_to_primary.set(True)      # read-your-writes for the rest of this request
        return "default"

    def allow_relation(self, obj1, obj2, **hints):
        return True

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return True


class Notice(models.Model):
    title = models.CharField(max_length=60)
    class Meta:
        app_label = "school"


for alias in ("default", "replica"):
    with connections[alias].schema_editor() as editor:
        editor.create_model(Notice)

# Pretend replication already copied one old row
Notice.objects.using("replica").create(title="Holiday on Monday")
Notice.objects.using("default").create(title="Holiday on Monday")

print("read goes to:", Notice.objects.all().db, list(Notice.objects.values_list("title", flat=True)))

Notice.objects.create(title="Exam timetable out")   # write -> primary, replica lags behind
print("after write, read goes to:", Notice.objects.all().db,
      list(Notice.objects.order_by("id").values_list("title", flat=True)))
print("replica still has:", list(Notice.objects.using("replica").values_list("title", flat=True)))

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Two SQLite files stand in for a primary and a replica; the stale replica shows why read-your-writes routing matters. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): read goes to: replica ['Holiday on Monday'] after write, read goes to: default ['Holiday on Monday', 'Exam timetable out'] replica still has: ['Holiday on Monday']

Key points

  • Aliases in DATABASES; .using() and save(using=) for manual control
  • Routers implement db_for_read, db_for_write, allow_relation, allow_migrate
  • Returning None passes the decision to the next router
  • Replication lag: read-your-writes needs routing to primary
  • No cross-database joins or foreign keys

Common mistakes

  • Reading from a replica right after a write and showing stale data
  • Trying to join or add foreign keys across databases
  • Forgetting allow_migrate so tables are created on the wrong database
  • Running a transaction on one alias while queries go to another

Follow-ups

  • How would you implement read-your-writes across requests?
  • How do you test code that uses two databases?
  • When is sharding a better answer than replicas?

Tips

  • Show the router's four methods and what None means
  • Raise replication lag before the interviewer does
  • Mention test configuration with MIRROR