What is an app boundary in a Django modular monolith?
In a Django project, an app boundary is a rule about which apps may import from which. Django won't enforce one. Any module can import any model, so orders ends up reaching into billing.models and billing calls back into orders.utils. After a few years, no app can change without touching three others.
Classify your apps into three kinds:
- Domain modules own a business capability and its data. Examples are
accounts,ordersandbilling. They should not import each other directly. - Core holds shared primitives such as base models, money types and time helpers. Everything may depend on it, and it depends on nothing in your project.
- Entry points include API views, admin registrations and management commands. They sit on top and may import anything below them.
entry points (api, admin, management commands)
|
v
services (cross-domain workflows)
|
v
+----------+ +--------+ +---------+
| accounts | | orders | | billing | independent
+----------+ +--------+ +---------+
| | |
v v v
core (shared primitives)
import-linter is a Python tool that checks these rules statically. It works on dotted module paths under one root package, such as myproject.orders. It does not use Django app labels or INSTALLED_APPS. Your directory layout therefore has to express the boundaries. If billing is scattered across top-level packages, no contract can describe it.
This setup pays off for teams with several apps and shared ownership, where nobody holds the whole dependency graph in their head. Until the rules are written down and checked in CI, apps are just folders. Once a violating import fails the build, they behave like modules.
myproject/ (one root package; import-linter checks dotted module paths)
+-----------------------------------------------------------------------+
| ENTRY POINTS myproject.api myproject.admin management commands |
+-----------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------+
| SERVICES myproject.services (cross-domain workflows) |
+-----------------------------------------------------------------------+
| | |
v v v
+-------------------+ +-------------------+ +-------------------+
| myproject.accounts| X | myproject.orders | X | myproject.billing |
| (domain module) | | (domain module) | | (domain module) |
+-------------------+ +-------------------+ +-------------------+
| | |
v v v
+-----------------------------------------------------------------------+
| CORE myproject.core (base models, money, time helpers) |
| depends on nothing else inside myproject |
+-----------------------------------------------------------------------+
| v : allowed import direction (higher layers import lower ones)
X : forbidden direct import between independent domain modules
Target layering under a single root package: entry points import services, services coordinate the independent domain apps accounts, orders and billing, and every layer may depend on core, which imports nothing else in the project.
How does import-linter work, and what do its contract types enforce?
That is the job import-linter does. It never executes your code. It hands your root package to grimp, a library that parses every module's source and records each import statement as an edge in a directed graph. Contracts are then checked against that graph, so a run is deterministic and needs no database, settings module or django.setup().
Because grimp reads source, not runtime behaviour, imports inside functions and under if TYPE_CHECKING: still appear as edges. A lazy import tucked into a method to dodge a circular-import error counts as a dependency, and so does a type-only import of another app's model. That is usually what you want: both couple the modules, even if Python only resolves one of them at runtime.
Contracts check chains as well as direct imports. If billing imports core.utils and core.utils imports accounts.views, the chain is reported. This is why most real failures are indirect.
| Contract type | What it checks | Typical use | Common failure mode |
|---|---|---|---|
forbidden |
Source modules never import the listed forbidden modules, directly or through a chain | billing must not import accounts.views |
An indirect path through a shared helper module |
independence |
None of the listed modules import each other | Peer domain apps such as accounts, orders and billing |
A signal handler or serializer in one app that reaches into another app's models |
layers |
Lower layers never import higher ones, but higher layers may import lower ones | core below the domain apps, with entry points above them |
Code in core that imports a domain model "just for one helper" |
How do you set up import-linter and map your current dependencies?
Install import-linter into the same environment your tests run in, since it builds the graph by locating your modules on the import path. Add a [tool.importlinter] table to pyproject.toml (or an .importlinter file if you keep tooling config separate) and set root_package to the package that contains your apps. Many Django projects keep apps as top-level packages beside manage.py. In that layout, either list them under root_packages or move them under a single project package first.
Run lint-imports before you write any meaningful contracts. The first run shows whether the tool can parse the whole codebase. A syntax error in a forgotten script, or a module that only resolves under certain settings, is easier to fix now than when it is mixed in with contract failures.
Next, map the dependencies that already exist. You can query the graph directly with grimp, the library import-linter builds on, and ask which modules each app imports. The quicker route is to add a deliberately strict independence contract across all domain apps and read the violations it reports. Either way, record each cross-app import by kind:
- Models. These usually mean a foreign key or a shared query.
- Services. These are often legitimate dependencies.
- Internals such as private helpers or
utils. These are the ones to remove first.
This inventory becomes your ratchet baseline.
If the mapping shows you need to restructure packages, move one app per pull request. Moves rewrite imports across the repository, which produces large diffs that conflict with every in-flight branch.
# .importlinter (INI format; the same keys can live under [tool.importlinter] in pyproject.toml)
[importlinter]
# The single package that contains every Django app.
# If your apps sit beside manage.py as top-level packages,
# use root_packages instead and list each one on its own line.
root_package = shopsite
# Deliberately strict mapping contract. It is not meant to pass.
# Each reported violation is one existing cross-app import to record
# in the baseline as a model, service or internal dependency.
[importlinter:contract:map-domain-apps]
name = Mapping: domain apps should not import each other
type = independence
modules =
shopsite.accounts
shopsite.catalog
shopsite.orders
shopsite.billing
shopsite.shipping
# Run from the environment your tests use, so every module resolves:
# lint-imports
# Before you add this contract, a run with only the [importlinter]
# section confirms the whole graph parses on its own.
A minimal import-linter config that sets the root package and adds a deliberately strict independence contract across all domain apps, so its violations serve as an inventory of existing cross-app imports.
Worked example: ratcheting contracts on accounts, orders, billing and core
Model it as four packages: core at the bottom, then accounts, orders and billing above it. One existing violation is already in place: billing/invoicing.py imports orders.models directly.
Write three contracts, and name each one so a failure tells the developer which rule they broke and where the allowed entry point is:
- Layers contract: "Apps depend downward: billing → orders → accounts → core". This means
orderscan never importbilling. - Forbidden contract: "billing must call orders.services, not orders.models/selectors/tasks". List those three modules explicitly. Keep wildcards to
ignore_imports, where*matches one module segment, as inmyproject.*.models. - Independence contract: applied to the per-app
modelsmodules, so no app's models import another app's models.
Each app's services.py becomes its public surface. Everything else in the app is internal.
The existing billing.invoicing -> orders.models import goes into the forbidden contract's ignore_imports. Put a comment above it naming the owner and the ticket. This creates the ratchet: the list only shrinks, and each removal is one small refactor ticket.
When someone adds billing.refunds -> orders.models, CI fails. The failure prints the contract name, which already points to orders.services.
To fix the original violation, add a function to orders/services.py that returns what invoicing needs, and switch billing.invoicing to call it. Then delete the ignore entry. If the linter passes without the entry, the ratchet has moved.
Moving the import into a function body or an if TYPE_CHECKING: block is not a fix. Import-linter still sees function-level imports. TYPE_CHECKING imports are usually typing-only, but they still couple billing to orders' internal model shapes. If you exclude them from analysis, you only hide that coupling. The dependency on orders internals is still there.
# .importlinter (run in CI with: lint-imports)
[importlinter]
root_package = myproject
[importlinter:contract:app-layers]
# Higher apps may import lower ones, never the reverse.
name = Apps depend downward: billing -> orders -> accounts -> core
type = layers
layers =
myproject.billing
myproject.orders
myproject.accounts
myproject.core
[importlinter:contract:billing-uses-orders-services]
# orders.services is the public surface; everything else is internal.
name = billing must call orders.services, not orders.models/selectors/tasks
type = forbidden
source_modules =
myproject.billing
forbidden_modules =
myproject.orders.models
myproject.orders.selectors
myproject.orders.tasks
# RATCHET: this list only shrinks. Never add entries.
# owner: billing-team, ticket: PLAT-123 (move to orders.services)
ignore_imports =
myproject.billing.invoicing -> myproject.orders.models
[importlinter:contract:models-independent]
# No app's models may import another app's models.
name = App models are independent; share data via each app's services.py
type = independence
modules =
myproject.accounts.models
myproject.orders.models
myproject.billing.models
An .importlinter config with a layers contract, a forbidden contract that holds the one existing billing.invoicing -> orders.models violation in an owned ignore_imports entry, and an independence contract across the per-app models modules.
What Django coupling can import-linter not see?
Import-linter only sees import statements. Django lets apps depend on each other in many other ways that never produce one:
- String model references.
ForeignKey('orders.Order')creates a hard dependency at the database and ORM level without any import. apps.get_model('orders', 'Order')resolves a model at runtime from two strings.- Signal receivers connected in another app's
ready(), or loaded by naming convention, react toordersevents without importing anything fromorders. INSTALLED_APPSordering affects template and static file lookup, and can affect signal registration order.- URL
include()strings, Celery task names sent by string, and template paths such asorders/detail.htmlused from billing views.
Migrations make this concrete. A cross-app ForeignKey makes makemigrations add a dependency on the other app's migration, which ties the two apps' schema histories together. Keep migrations packages out of contract scope. They are generated, append-only history, and editing old migrations to satisfy a lint rule is riskier than the coupling itself. The boundary decision belongs at the model field, before the migration is written.
To limit this, keep an explicit allowlist of permitted cross-app relations, such as billing → orders, and enforce it in code review. You can back the allowlist with a small check. Here is an illustrative sketch, not a hardened tool. A test or system check iterates over apps.get_models(). For each relational field, it compares the model's app_label with that of related_model, and fails when the pair is not on the allowlist.
A green import-linter run means your imports respect the contracts. It does not mean the apps are decoupled.
# tests/test_app_boundaries.py
# Illustrative sketch, not a hardened tool: fails when a model relation
# crosses app boundaries without being on the reviewed allowlist.
from django.apps import apps
from django.test import SimpleTestCase
# Only check our own apps; relations to django.contrib (e.g. auth) are out of scope.
PROJECT_APPS = {"orders", "billing", "inventory", "accounts"}
# (from_app, to_app) pairs approved in code review. Change via PR only.
ALLOWED_CROSS_APP_RELATIONS = {
("billing", "orders"),
("orders", "inventory"),
}
class AppBoundaryTests(SimpleTestCase):
def test_cross_app_relations_are_allowlisted(self):
violations = []
for model in apps.get_models():
source = model._meta.app_label
if source not in PROJECT_APPS:
continue
for field in model._meta.get_fields():
# Skip non-relations and reverse accessors (auto_created);
# each forward ForeignKey/OneToOne/M2M is checked once, on its owner.
if not field.is_relation or field.auto_created:
continue
if field.related_model is None: # e.g. GenericForeignKey
continue
target = field.related_model._meta.app_label
if target == source or target not in PROJECT_APPS:
continue
if (source, target) not in ALLOWED_CROSS_APP_RELATIONS:
violations.append(
f"{model._meta.label}.{field.name} -> {field.related_model._meta.label}"
)
self.assertEqual(violations, [], "Unapproved cross-app relations found")
An illustrative Django test that walks the app registry and fails when a ForeignKey, OneToOne or ManyToMany field links two project apps whose pair is not on a reviewed allowlist, catching string references such as ForeignKey('orders.Order') that import-linter cannot see.
How do you run import-linter in CI and pre-commit without slowing the team down?
Run lint-imports as its own CI job, separate from the test suite rather than tacked onto the end of it. A boundary failure then shows up as a distinctly named red check, and the job needs no database, migrations or Django settings, because import-linter builds its graph by parsing source rather than executing it. It does have two requirements. The root packages named in your contracts must be locatable on the Python path, so install the project or set the path the way local runs do. Every module must also parse under the CI interpreter, so a file with syntax only a newer Python accepts will break the job.
For local feedback, add a pre-commit hook that runs lint-imports once over the whole project rather than per staged file (pass_filenames: false). A dependency is a property of the graph, not of a single file.
Measure the runtime in your own pipeline before claiming it is free. As an illustrative estimate, assume the job takes 20 seconds and replaces three review threads a week that each cost 20 minutes of debate over whether billing may import orders.models. That trades one minute of compute for an hour of engineering time. The bigger saving comes when the violation is caught in the pull request that introduces it, not months later during an extraction.
Treat ignore_imports as debt with an owner:
- Every entry carries a comment naming a team and a tracking issue.
- A code-owners rule requires that team's approval to add lines.
- CI fails if the list grows.
Without these rules, the ignore list becomes the real architecture diagram.
When should you avoid import-linter contracts, and what are the alternatives?
Contracts pay off when several teams share one codebase and the domain lines are stable enough to name. They cost more than they return in three cases:
- One small team. Everyone already holds the dependency map in their head, and review catches the same mistakes.
- Domains still in flux. Every redrawn boundary means editing contracts and ignore lists, which slows the exploration you need.
- Wrong layer definitions. The linter enforces a bad design as strictly as a good one, so mistakes harden into the structure.
Over-strict independence contracts have their own failure mode. If accounts, orders and billing may not import each other, teams either copy helpers, and the copies drift, or they move shared code into core. A growing core becomes the module everything depends on. That is the original coupling with a different name.
Boundaries also do not give you independent deployment, separate databases or separate scaling. Cross-app ForeignKeys, shared tables and transactions that span apps all remain. Passing contracts is not a migration plan to microservices.
| Alternative | Trade-off |
|---|---|
| Code review conventions only | No tooling cost; depends on reviewer memory and erodes as the team grows |
| Django system checks or custom scripts | Can inspect models and settings; you write and maintain the logic yourself |
| Separate installable packages | Dependencies declared explicitly; adds packaging and versioning overhead |
| Separate services | Real deployment and scaling independence; adds network calls, data ownership work and distributed failures |
Revisit contracts in these situations:
- An ignore entry outlives its tracking issue.
- A new app fits no layer.
- Two apps keep changing in the same pull requests. Merge them or redraw the line.
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 django import-linter, 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.