What is a domain-structured Django monolith, and who should use it?
A domain-structured Django monolith organizes the codebase so that each Django app corresponds to a business domain, such as billing, accounts or catalog. It does not organize apps by technical layer (a models app, a serializers app) or wrap a single model in its own app. Each domain app owns its models, business rules and migrations. It exposes a small, deliberate public interface that other apps are expected to use. Everything else inside the app is treated as private, even though Python will not stop anyone from importing it.
Teams adopt this structure for two reasons: ownership and safer changes. When billing is a bounded unit with a known surface, one team can own it, review changes to it and refactor its internals. The team only needs to keep the interface stable, not audit every file that might import a model directly. The structure also makes the blast radius of a change visible. A pull request that touches only one domain's internals is low-risk. One that alters a public interface signals that callers in other domains need attention.
The approach fits codebases where several teams or many contributors work in one repository and cross-app coupling has started to slow change. A small project with one team usually gains little and pays for the extra indirection.
The result is still one database, one deploy and one runtime. All domains scale together, fail together and ship together. Clean boundaries make a later extraction into separate services easier, but they do not guarantee that path.
How do you find domain boundaries in an existing Django codebase?
Start from business capabilities, not from the current apps/ folder. Ask which part of the business owns each model and which team gets paged when it breaks. Billing, catalog, fulfilment and identity are typical answers. Then check that grouping against what the code actually does.
Three sources of evidence show real coupling:
- The import graph. List which modules import from which. Clusters that import each other heavily are one domain in practice, whatever their app labels say.
- Cross-app foreign keys. Each
ForeignKeythat crosses an app boundary is a join, a cascade rule and a migration dependency. Dense FK webs between two apps usually mean they belong together. - Co-change history. Running
git log --name-onlyover the last year shows which files change in the same commits. Models that always change together have one owner, even if they live in different apps.
Treat this evidence as a description of today's coupling, not as the target design. Some of that coupling is accidental. A utils module imported everywhere tells you about past shortcuts, not about your domains.
Resist over-splitting. Twenty small apps means twenty public interfaces to define, version and keep stable, and every feature touches four of them. That adds ceremony without isolation, because the apps still share one database and one deploy. Four to eight coarse domains usually hold up better.
Take time to get this step right. Boundaries harden once other code depends on the interfaces, and moving a model between apps later means data migrations, rewritten imports and renegotiated ownership.
How should you lay out domain apps in a large Django project structure?
…a long tail of broken references. Once you know the boundaries, give each domain its own Django app under a single top-level domains/ package:
domains/
accounts/ billing/ catalog/
│ │ │ │
│ │ └──► catalog.services
│ └─────► accounts.services
▼ ▼ ▼
shared/ (kernel: money types, base models, utilities)
Each app owns its models.py, migrations/, admin.py and tests/. It also has one public module, services.py or api.py, and that is the only module other domains may import. Arrows point one way: billing may call accounts.services and catalog.services, but neither of them imports from billing. Everything may depend on shared/, and shared/ depends on no domain. Keep the kernel small. If it fills up with business logic, it turns into a second, unbounded domain.
In each app's AppConfig, set name to the dotted path ("domains.billing") and label to the short form ("billing"). Django would derive that label from the last path segment anyway. Setting it explicitly pins a value that is hard to change later.
The label is the app identifier in migration files and the django_migrations table. It is also the prefix in string references like "billing.Invoice" and the default table name (billing_invoice). Content types and permissions are keyed on it too. If you rename the label after deployment, Django treats the app as new. Migration history stops matching, tables need renaming, and permissions and generic relations are left orphaned.
# domains/billing/apps.py
from django.apps import AppConfig
class BillingConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "domains.billing" # dotted import path of the package
label = "billing" # pinned explicitly; never change after deploy
verbose_name = "Billing"
# domains/billing/models.py
from django.db import models
class Invoice(models.Model):
# Lazy string reference uses the *label*, not the dotted path.
# billing -> accounts is an allowed dependency direction.
customer = models.ForeignKey(
"accounts.Customer", on_delete=models.PROTECT, related_name="invoices"
)
number = models.CharField(max_length=32, unique=True)
# No Meta.db_table, so the table is "<label>_<model>": billing_invoice
# domains/billing/migrations/0002_invoice_customer.py (generated excerpt)
# Migration dependencies are keyed on labels as well:
# dependencies = [
# ("billing", "0001_initial"),
# ("accounts", "0001_initial"),
# ]
# config/settings.py
INSTALLED_APPS = [
"django.contrib.contenttypes",
"django.contrib.auth",
"domains.accounts.apps.AccountsConfig",
"domains.catalog.apps.CatalogConfig",
"domains.billing.apps.BillingConfig",
]
An AppConfig for the billing domain with a dotted name and a short pinned label, showing where that label appears: in model string references, default table names and migration dependencies.
How do you define a domain's public interface?
Each domain app should expose a small module, typically services.py or api.py, that other domains are allowed to import. Everything else in the app (models, managers, querysets, internal helpers) is private. Functions in this module accept plain values such as IDs, strings and dates, and return plain values or simple frozen dataclasses. They never return a model instance or a QuerySet.
The reason is control over change. When billing receives a QuerySet[Customer], it can chain .filter(region__code="EU"), follow relations, and read any field. Billing now depends on customer's column names, its relation graph, and the shape of its queries. Splitting a table, denormalizing a field, or moving Customer to a different database each becomes a change across several domains. A returned model instance has the same problem, and it also allows lazy queries and writes from outside the owning domain. A dataclass such as CustomerSummary(id, name, billing_email) fixes the contract. The customer domain can change everything behind it, as long as it still fills those fields.
You lose ORM convenience in return, and this is the main cost of the pattern. Without cross-domain select_related, prefetch_related or joins, a loop that calls get_customer(id) for each invoice produces one query per row, which is the N+1 problem. Every public interface therefore needs batch lookups, such as get_customers_by_ids(ids) returning a dict keyed by ID. Callers collect IDs first, fetch them in one call, then combine the results in Python. This is more code than one joined query, and you should plan for it from the start.
# customers/services.py -- the only module other domains may import
from dataclasses import dataclass
from customers.models import Customer # private to this app
@dataclass(frozen=True)
class CustomerSummary:
# The public contract: callers see these fields, not the schema behind them.
id: int
name: str
billing_email: str
def _to_summary(c: Customer) -> CustomerSummary:
return CustomerSummary(id=c.id, name=c.name, billing_email=c.billing_email)
def get_customer(customer_id: int) -> CustomerSummary | None:
c = Customer.objects.filter(pk=customer_id).only("id", "name", "billing_email").first()
return _to_summary(c) if c else None
def get_customers_by_ids(ids: list[int]) -> dict[int, CustomerSummary]:
# Batch lookup: one query for any number of IDs, so callers avoid N+1.
rows = Customer.objects.filter(pk__in=set(ids)).only("id", "name", "billing_email")
return {c.id: _to_summary(c) for c in rows}
# billing/reports.py -- a caller in another domain
from billing.models import Invoice
from customers import services as customers
def invoice_rows(invoices: list[Invoice]) -> list[tuple[str, str, int]]:
# Collect IDs first, fetch once, then combine in Python instead of a cross-domain join.
by_id = customers.get_customers_by_ids([inv.customer_id for inv in invoices])
return [
(inv.number, by_id[inv.customer_id].name, inv.total_cents)
for inv in invoices
if inv.customer_id in by_id
]
A customer domain's public services module returns frozen dataclasses instead of models or querysets, and provides a batch lookup that billing uses to fetch all needed customers in one query rather than one query per invoice.
Should cross-domain relationships use a ForeignKey or a stored ID?
A ForeignKey is the default Django reach for, and inside a domain it is the right choice. Across domains it has costs that are easy to miss. Writing ForeignKey('accounts.Customer', ...) as a string avoids a Python import, but it does not remove the coupling. When you run makemigrations, Django resolves the string reference and adds a dependency on the accounts app's migrations. From then on, billing cannot be migrated, squashed or extracted without accounts. The relation also lets any caller write Invoice.objects.filter(customer__email=...), which joins straight into another domain's tables without going through its interface.
A stored ID, such as an indexed customer_id integer or UUID field, removes both problems. The cost is that the database no longer guarantees the row exists, and on_delete no longer applies. You must handle deletions in application code, for example by reacting to a domain event, and you lose joins.
| Concern | ForeignKey | Stored ID |
|---|---|---|
| Coupling | Schema and ORM coupled | Coupled only through the public interface |
| Integrity | Enforced by the database constraint | Application-level, needs reconciliation |
| Query cost | One joined query | Batched lookups combined in Python |
| Migration impact | Cross-app migration dependency | Independent migration graphs |
Reporting queries and Django admin sometimes need cross-domain reads. A join may be the only practical way to build them, and that is a legitimate reason to keep one. Allow these as documented exceptions and keep them read-only. Isolate them in a dedicated reporting app, and list them explicitly in your boundary configuration so reviewers can see where the exceptions are.
# billing/models.py
from django.db import models
class Invoice(models.Model):
# Avoided: makemigrations would add a dependency on accounts' migrations,
# and callers could join with filter(customer__email=...).
# customer = models.ForeignKey("accounts.Customer", on_delete=models.PROTECT)
# Stored ID: indexed, but no DB constraint, no on_delete, no join.
customer_id = models.UUIDField(db_index=True)
total_cents = models.PositiveIntegerField()
# accounts/services.py (public interface of the accounts domain)
from accounts.models import Customer # assumes a UUID primary key
def get_customers_by_ids(ids):
# Return plain dicts so other domains never hold accounts model instances.
return {
c.id: {"id": c.id, "email": c.email}
for c in Customer.objects.filter(id__in=set(ids))
}
# billing/services.py
from accounts.services import get_customers_by_ids
from billing.models import Invoice
def recent_invoices_with_customers(limit=50):
invoices = list(Invoice.objects.order_by("-id")[:limit])
# One batched lookup through the interface replaces the join.
customers = get_customers_by_ids(inv.customer_id for inv in invoices)
# None means the customer was deleted: integrity is now the app's job.
return [(inv, customers.get(inv.customer_id)) for inv in invoices]
Shows a billing model storing a customer UUID instead of a ForeignKey to 'accounts.Customer'. Billing resolves customers with one batched call to the accounts domain's service function and treats a missing customer as a case it must handle itself.
How do you enforce import boundaries in CI?
A boundary that lives only in a design document erodes the first time someone is in a hurry. The fix is to make it executable: declare which packages may depend on which, and fail the build when code reaches into another domain's internals.
The usual model is a set of contracts. A layer contract says higher packages may import lower ones but not the reverse, such as domains over platform over core. An independence contract says sibling packages may not import each other except through their public module. Static import-contract linters for Python already express both kinds and can be configured per package. They read the import graph without running Django, so they are fast enough to run on every pull request.
If you want something smaller, a custom checker takes about forty lines. It uses the standard library ast module to parse every file under domains/, collects Import and ImportFrom nodes, and resolves relative imports against the file's package. It flags any import of domains.<other> that is not domains.<other>.api. Entries in a checked-in allowlist file, keyed by importing module and target, are skipped. The checker exits non-zero on any violation that is not on the list.
The check also needs an owner. If no one reviews allowlist additions, blanket exceptions pile up until developers learn to append a line rather than fix the import, and the check becomes noise. Don't expect the list to reach zero. Admin registrations, contenttypes, generic foreign keys and third-party apps all legitimately cross boundaries. The goal is an allowlist that is short, commented and shrinking.
# check_boundaries.py: run from repo root. Fails if a domain imports another domain's internals.
import ast, sys
from pathlib import Path
ROOT, ALLOWLIST = Path("domains"), Path("import_allowlist.txt")
def load_allowlist():
# One "importer target" pair per line; '#' starts a comment explaining the exception.
pairs = set()
for line in ALLOWLIST.read_text().splitlines():
line = line.split("#", 1)[0].strip()
if line:
importer, target = line.split()
pairs.add((importer, target))
return pairs
def module_info(path):
parts = list(path.with_suffix("").parts)
if parts[-1] == "__init__":
parts.pop()
return ".".join(parts), parts # a package's __init__ is its own package
return ".".join(parts), parts[:-1]
def imported_names(tree, pkg):
for node in ast.walk(tree):
if isinstance(node, ast.Import):
yield from ((node.lineno, a.name) for a in node.names)
elif isinstance(node, ast.ImportFrom):
# Resolve relative imports: level 1 is the current package, level 2 its parent.
base = pkg[: len(pkg) - node.level + 1] if node.level else []
mod = ".".join(base + ([node.module] if node.module else []))
yield from ((node.lineno, f"{mod}.{a.name}") for a in node.names)
allow, violations = load_allowlist(), []
for path in sorted(ROOT.rglob("*.py")):
module, pkg = module_info(path)
own = module.split(".")[1] if "." in module else None
for lineno, name in imported_names(ast.parse(path.read_text(), str(path)), pkg):
p = name.split(".")
if p[0] != "domains" or len(p) < 2 or p[1] == own or p[2:3] == ["api"]:
continue # not a domain import, same domain, or the other domain's public api
if (module, ".".join(p[:3])) not in allow:
violations.append(f"{path}:{lineno}: {module} imports {name}")
print("\n".join(violations))
sys.exit(1 if violations else 0)
A standard-library ast checker that resolves absolute and relative imports under domains/, flags any cross-domain import that does not go through domains..api, skips pairs listed in a commented allowlist file, and exits non-zero so CI fails on new violations.
How should domains communicate without circular imports?
When the caller needs an answer, such as a price, a permission check or a created object, call the owning domain's public interface directly. orders importing billing.services.calculate_total is an explicit, one-way dependency that the import linter can see and approve. Use events only when the owning domain should not know who reacts: accounts emits "user deactivated", and notifications and billing each decide what that means.
Django signals do this, but they hide control flow. The sender has no list of receivers. Handlers are connected in AppConfig.ready(), so what runs depends on which apps are installed. A plain send() also propagates any receiver's exception back to the sender, so an unrelated failure in notifications can break deactivation in accounts. An explicit dispatcher, such as a small module that maps event names to handler lists, keeps the decoupling and lets you grep for every subscriber.
Transactions cause the worst bugs. A handler that runs synchronously inside the sender's atomic() block shares its fate. If the outer transaction rolls back, any email or queued task the handler started has already gone out, and a worker may look up a row that never committed. Deferring with transaction.on_commit fixes this, but the deferred work can no longer roll back the original write. It also never fires inside a plain TestCase unless you use captureOnCommitCallbacks.
| Pattern | Discoverability | Transaction behavior | Coupling |
|---|---|---|---|
| Direct call | High: visible import | Runs in caller's transaction | Caller depends on callee |
| Django signal | Low: receivers registered elsewhere | In-transaction unless handler defers | Hidden, runtime-only |
| Explicit dispatcher | Medium: one registry to read | Can defer to on_commit by default |
Owner knows only the event name |
What are the alternatives, and what does the migration cost?
Alternatives
| Option | Strength | Cost |
|---|---|---|
Layer-based apps (models, api, services) |
Familiar, easy to start | Every feature touches every app, so nobody owns anything |
| One app per model | Small files | Boundaries follow tables, not behaviour; imports become a mesh |
| Separate services | Hard isolation, independent deploys | Network failures, distributed transactions, duplicated ops work |
| Leave it as is | Zero migration cost | Coupling keeps growing, and reviews keep getting slower |
Migrating incrementally
Start by dismantling core or common. Keep a true shared kernel there: base model mixins and money and time utilities that import nothing from any domain. Move drifted domain logic, such as a send_invoice_email helper, back to the domain that owns it. If the kernel depends on a domain, every domain depends on every other domain.
Next, add each domain's public interface module and redirect callers to it. Run boundary checks in warn-only mode with an allowlist of the violations that already exist. New violations fail the build, and the allowlist only shrinks. This lets you merge the change without fixing every existing violation first.
For models, you can use SeparateDatabaseAndState to move a model's state without touching its table, keep the old db_table, or leave the model where it is. Leaving tables and app labels alone is often safer. Migration surgery needs a rehearsal on a production-like database, and it conflicts with long-lived branches that still reference the old migration graph.
Testing per domain
Give each domain an isolated test suite and contract tests on its public interface. Put cross-domain integration tests in a separate location, so a failure points to the contract between domains rather than to one owner's code.
When to skip it
Skip this work for small teams or codebases that one person can hold in their head. The payoff comes from faster reviews, clear ownership and a smaller blast radius. You pay for it with upfront refactoring and the ongoing cost of maintaining the boundary rules.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to large django project structure, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.