Why does the default Django apps layout break down in a large project?

Django's startapp convention nudges teams toward one app per noun: orders, customers, billing, inventory. That works while the project is small. Past a certain size, the app boundaries stop meaning anything, because nothing in Django stops one app from reaching into another.

In practice, billing imports orders.models.Order and filters on its fields directly. orders calls a helper from customers.utils that was never meant to be shared. A custom queryset method in inventory gets reused in four places, each depending on its exact behavior. None of these imports is wrong in isolation. Together they form a dependency graph that exists only in the code. No one reviews it as a whole, and no tool reports it. Renaming a field or changing a queryset then means a search across the repository and a hope that the tests catch the rest. Cycles show up as circular import errors, often patched with a function-level import instead of a design fix.

A modular monolith treats each Django app as a bounded module. Each module exposes a small, explicit public interface. Everything else is private. The allowed dependencies between modules are written down as rules and checked automatically in CI. The guarantee comes from the checks, not from directory names.

This pays off most for teams with several engineers or squads sharing one Django codebase that is getting slower to change. You get clear ownership and safe refactoring without splitting into services.

How should you structure a large Django project into modules?

Use three kinds of package under one top-level package, say acme/:

  • Domain modules: acme/billing/, acme/catalog/, acme/orders/. Each is a full Django app with its own apps.py, models.py, migrations/ and api.py for its public interface.
  • Platform layer: acme/platform/ holds cross-cutting code such as auth helpers, base model mixins, logging and money types. It may be split into several small apps. Platform code never imports from domain modules.
  • Config package: acme/config/ contains settings/, the root urls.py, wsgi.py and asgi.py. It wires modules together and contains no business logic.

INSTALLED_APPS lists the dotted paths, for example "acme.billing" and "acme.platform.audit". In each AppConfig, set name to that full dotted path. Set label explicitly to a short, stable string such as billing. The label determines table names and the keys Django uses for migration dependencies. Pinning it means you can rename or relocate the Python package later without renaming database tables.

Draw boundaries around business capabilities, not technical layers. A models app, a serializers app and a services app guarantee that every feature change touches every module, and every module ends up importing every other. A billing module can own its invoices, payment rules and endpoints end to end, so one team can change it without coordinating with others.

Spend real time on these boundaries up front, because a model's app is hard to change later. Moving a model between apps changes its owning label. That means hand-written migrations using SeparateDatabaseAndState, updating every foreign key and content type that references it, and coordinating the change across every environment's migration history.

# Layout (abridged):
# acme/
#   config/      settings/, urls.py, wsgi.py, asgi.py  (wiring only)
#   platform/
#     audit/     apps.py, models.py, migrations/
#   billing/     apps.py, models.py, migrations/, api.py
#   catalog/     apps.py, models.py, migrations/, api.py
#   orders/      apps.py, models.py, migrations/, api.py

# acme/billing/apps.py
from django.apps import AppConfig


class BillingConfig(AppConfig):
    # Full dotted path: must match the INSTALLED_APPS entry.
    name = "acme.billing"
    # Pinned label: drives table names (billing_invoice) and migration
    # dependency keys, so moving the package later leaves the DB untouched.
    label = "billing"
    default_auto_field = "django.db.models.BigAutoField"


# acme/platform/audit/apps.py
class AuditConfig(AppConfig):
    name = "acme.platform.audit"
    label = "audit"  # short and stable, not "platform_audit"


# acme/config/settings/base.py
INSTALLED_APPS = [
    "django.contrib.auth",
    "django.contrib.contenttypes",
    # Platform layer first: domain modules may depend on it, never the reverse.
    "acme.platform.audit",
    # Domain modules, one per business capability.
    "acme.billing",
    "acme.catalog",
    "acme.orders",
]
ROOT_URLCONF = "acme.config.urls"

A domain-first package tree mapped onto INSTALLED_APPS, with each AppConfig setting name to the full dotted path and pinning a short, stable label.

How do you define a public interface for each Django app?

Each app exposes one importable surface, typically services.py or api.py. Everything else (models, selectors, querysets, helpers) is private by convention and, later, by contract. Public functions accept and return primitives and frozen dataclasses, never model instances or QuerySets. A returned model lets callers traverse relations and trigger lazy queries against tables they don't own, so the boundary leaks the moment you hand one out.

When orders needs customer data, it calls customers.services.get_customer_summary(customer_id) instead of importing Customer. Orders stores customer_id and treats it as an opaque reference.

Whether that reference should be a real foreign key is a separate decision:

Concern Cross-module ForeignKey Plain identifier field
Referential integrity Enforced by the database Enforced by application code, or not at all
Cascading deletes Available via on_delete Must be handled explicitly, usually through events
SQL joins Possible Not available; data is fetched through services
Migration coupling Migration depends on the other app's migrations None
Extracting the module later Requires schema surgery Mostly a code change

A string reference like "customers.Customer" needs no Python import, so import-linter never sees it. The schema and migration graph stay coupled even when every import contract passes. Use FKs only where integrity matters more than the option to separate the modules later.

Isolation also costs you ORM conveniences. select_related can't cross a boundary you refuse to touch. Admin classes want the other module's model for list displays and filters. Generic relations through contenttypes bypass boundaries entirely. A per-row service call turns one join into N queries. Design services to take batches of IDs and return mappings, and accept that strict isolation will still cost some extra queries.

# customers/services.py: the only module other apps may import
from dataclasses import dataclass
from customers.models import Customer  # private to this app

@dataclass(frozen=True)
class CustomerSummary:
    id: int
    name: str
    email: str

def get_customer_summaries(customer_ids: list[int]) -> dict[int, CustomerSummary]:
    # Batch lookup: one query for many IDs, so callers avoid per-row service calls
    rows = Customer.objects.filter(id__in=customer_ids).values("id", "name", "email")
    return {r["id"]: CustomerSummary(**r) for r in rows}


# orders/models.py: a plain identifier, not ForeignKey("customers.Customer")
from django.db import models

class Order(models.Model):
    customer_id = models.BigIntegerField(db_index=True)  # opaque reference, no migration dependency
    total_cents = models.PositiveIntegerField()


# orders/services.py: crosses the boundary only through customers.services
from dataclasses import dataclass
from customers.services import CustomerSummary, get_customer_summaries
from orders.models import Order

@dataclass(frozen=True)
class OrderView:
    id: int
    total_cents: int
    customer: CustomerSummary | None  # None if the customer was deleted

def list_recent_orders(limit: int = 50) -> list[OrderView]:
    orders = list(Order.objects.order_by("-id")[:limit])
    # Two queries total instead of a SQL join: the price of not using select_related
    customers = get_customer_summaries(list({o.customer_id for o in orders}))
    return [OrderView(o.id, o.total_cents, customers.get(o.customer_id)) for o in orders]

A customers app exposes a batch service that returns frozen dataclasses, and the orders app stores a plain customer_id and calls that service instead of importing Customer. This replaces a select_related join with one extra query per page rather than one per row.

How does import-linter enforce module boundaries?

import-linter reads its configuration from .importlinter, setup.cfg or pyproject.toml. Start by declaring your root packages, for example config, orders, billing, catalog and shared. These root packages define the import graph that the tool builds and checks. Then add contracts. Each contract encodes one architectural rule.

Contract type Rule it encodes Example
Layers Higher layers may import lower ones, never the reverse config → domains → shared
Independence Listed modules may not import each other orders, billing, catalog
Forbidden Source modules may not import specific targets domains must not import config.settings or an HTTP/SDK client package

The layers contract keeps shared from depending on business code. The independence contract makes each domain reach its peers only through the public interfaces defined earlier. The forbidden contract stops domains from reading settings or calling vendors directly, so you can swap or fake those dependencies at one seam. Forbidding third-party packages requires include_external_packages = True.

Run lint-imports locally from the project root. Add the same command as a CI step. It exits non-zero when any contract is broken, so the pipeline fails without extra scripting.

What it cannot see

import-linter analyses only static import statements. It does not see INSTALLED_APPS strings, lazy model references such as ForeignKey("billing.Invoice"), apps.get_model(), importlib.import_module(), or signal receivers wired by dotted path. A green run therefore proves only that there are no forbidden static imports. It does not prove that the modules are actually decoupled. Audit string references separately, for example with a grep-based check in CI.

# .importlinter at the project root. Run locally or as a CI step with: lint-imports
# It exits non-zero if any contract is broken, which fails the pipeline.

[importlinter]
root_packages =
    config
    orders
    billing
    catalog
    shared
# Required so third-party packages such as requests can appear in contracts.
include_external_packages = True

[importlinter:contract:layers]
name = config above domains above shared
type = layers
# Higher layers may import lower ones, never the reverse.
# '|' marks sibling layers that must also stay independent of each other.
layers =
    config
    orders | billing | catalog
    shared

[importlinter:contract:domains-independent]
name = Domains do not import each other directly
type = independence
modules =
    orders
    billing
    catalog

[importlinter:contract:no-settings-or-vendors]
name = Domains do not read settings or call vendor clients directly
type = forbidden
source_modules =
    orders
    billing
    catalog
# Placeholder vendor packages; list the clients your project actually uses.
forbidden_modules =
    config.settings
    requests
    boto3

An import-linter configuration that declares the root packages and defines a layers, an independence and a forbidden contract, which lint-imports checks locally and in CI.

How do you introduce import-linter contracts into an existing codebase?

Start by measuring what you already have. Before writing any contract, generate the current import graph between top-level apps (import-linter's underlying graph library, grimp, can do this from a short script) and list every cross-app edge. The graph is often worse than people expect, and you need it to decide which layers are realistic.

Then write the contracts you actually want and run lint-imports. Each violation it reports goes into that contract's ignore_imports list. CI stays green, and from that point any new forbidden import fails the build. You stop the problem from growing without blocking every merge on day one.

Treat the ignore list as a debt register. Next to each entry, add a comment with an owning team and a linked ticket. Review the list on a fixed cadence, such as once a quarter. If nobody reviews it, the ignore list becomes the real architecture, and the contract only describes what you hoped for. A useful rule is that entries may be removed freely, but adding one needs approval from the module's owner.

The payoff comes from fewer surprises. A change in billing can no longer quietly break notifications. Reviewers can trust the boundaries instead of tracing imports by hand, and you can refactor inside a module knowing who its callers are.

Illustrative estimate (assumed inputs): setup costs 3 engineer-days, and paying down the debt costs 1 day per month. If the contracts prevent two cross-module breakages a month at 4 hours of debugging each, and save 10 minutes on each of 60 reviews, that is about 18 hours saved per month against roughly 8 hours of ongoing cost.

# .importlinter at the repository root (setup.cfg [importlinter] sections also work)
[importlinter]
root_package = shop

# Target architecture: these apps must not import each other.
[importlinter:contract:apps-independent]
name = Feature apps are independent
type = independence
modules =
    shop.billing
    shop.notifications
    shop.catalog
# DEBT REGISTER: every entry below is a known violation that existed on day one.
# Removing an entry needs no approval. Adding one needs sign-off from the
# owning team of the imported module. Reviewed every quarter.
ignore_imports =
    # owner: payments-team, ticket: ARCH-101
    shop.billing.tasks -> shop.notifications.email
    # owner: growth-team, ticket: ARCH-102
    shop.notifications.templates -> shop.catalog.models

# Apps may depend on shared code, but shared code must never import an app.
[importlinter:contract:core-is-leaf]
name = Core does not depend on feature apps
type = forbidden
source_modules =
    shop.core
forbidden_modules =
    shop.billing
    shop.notifications
    shop.catalog
# No ignores here: this contract had no violations, so it is fully enforced.

# Run in CI with: lint-imports
# Known violations pass, and any new cross-app import fails the build.

An import-linter configuration that enforces app boundaries while recording existing violations in ignore_imports as an owned, ticketed debt register, so only new forbidden imports fail CI.

How should modules handle side effects, migrations and tests?

Side effects

Django signals suit genuinely decoupled reactions, such as cache invalidation, where the sender should not know who is listening. Across module boundaries they hide control flow. A post_save receiver in notifications runs synchronously inside the caller's transaction. Reading orders gives no hint that it exists, and an exception in the receiver can roll back the order. Prefer an explicit call to notifications.services.notify_order_placed(). If the caller must not depend on the consumer, use a small in-process dispatcher. The publishing module should own the event names and payloads, and subscribers should register in AppConfig.ready().

For anything that leaves the process, such as emails, task queues or webhooks, wrap the dispatch in transaction.on_commit. The callback runs only after the outermost atomic block commits and is discarded on rollback. Outside a transaction it runs immediately.

Migrations

A migration's dependencies should follow the same direction as your import contracts. If billing may import accounts, then billing migrations may depend on accounts migrations, and never the reverse. In data migrations, load models with apps.get_model("accounts", "User") rather than importing them. The historical model matches the schema at that point in the migration graph, and the import graph stays clean.

Tests

Keep tests inside each app and drive them through its public interface, so internal refactors don't break them. The boundary contracts should cover test modules too. That stops fixtures from quietly creating rows in unrelated modules. Use captureOnCommitCallbacks to assert on deferred side effects in TestCase.

When should you avoid a modular Django monolith, and what are the alternatives?

The discipline has a price. Every cross-module call goes through a service function, and data crosses the boundary as a DTO rather than a model instance. That means more files, more mapping code and more indirection. For a module that is mostly admin-backed CRUD, the wrapper usually just forwards to the ORM and adds nothing. Small teams and short-lived projects often won't recoup the cost. If three people share one mental model of the code, the linter mostly catches mistakes that code review would already catch.

Be clear about what you are not getting. A modular monolith still has one deploy, one database and one runtime. A slow reporting module still competes for the same workers and connection pool. A risky change in billing still ships with everything else. If independent scaling or independent release cadence is the actual requirement, boundaries inside one process won't provide it.

Approach Coupling visibility Operational overhead Refactor cost Team fit
App-per-noun layout Low; imports go anywhere Low Rises with size Small teams, early products
Convention plus code review Depends on reviewers noticing Low Moderate; drift accumulates Stable, senior teams
Modular monolith with import-linter High; violations fail CI Low Moderate; boundaries localise change Several teams, one codebase
Multiple repos or packages High, but enforced by versioning Medium; release and dependency management High for cross-package changes Teams with separate ownership
Microservices High; the network is the boundary High; deploys, observability, data consistency Very high to merge or reshape Teams needing independent scaling or release

A modular monolith also works as a staging step. Once a module only talks to the rest of the code through its service layer and DTOs, its interface is already explicit. Extracting it into a package or a service then becomes a change to transport, not a redesign of the module.

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.