Why don't Django apps enforce boundaries on their own?
A Django app is a Python package with a label in INSTALLED_APPS. Being an app gives you model registration, migrations, and template and static discovery. It does not give you encapsulation. Python has no notion of package-private modules, so billing.services can import accounts.models, notifications.tasks, or a helper buried three levels deep in another app. Neither the interpreter, Django, nor manage.py check will object.
That makes coupling cheap to add and hard to see. Each cross-app import looks reasonable in its own pull request. Reviewers judge the diff, not the dependency graph, so nobody notices when orders starts depending on reporting while reporting already depends on orders. The architecture diagram and the actual import graph drift apart, and only one of them is enforced.
The cost shows up later, in a few recognizable ways:
- Circular import errors at startup. These often appear only when module load order changes, and teams patch them by moving imports inside functions instead of fixing the dependency.
- Migration tangles. A
ForeignKeyto another app's model adds a cross-app migration dependency, and enough of them make squashing or reordering migrations painful. - Apps that can't stand alone. You cannot test, reuse, or extract an app into its own service without dragging half the project along.
These problems hit backend and platform engineers hardest when they maintain a growing modular monolith. That is the codebase where several teams share one repository and the boundaries between apps are the main thing keeping it manageable.
What is import-linter and how does it work?
import-linter treats architecture as something you can test. You describe the dependency rules your project should follow, and the tool fails the build when the code breaks them. It works like a unit test whose subject is the shape of the codebase.
Under the hood it uses grimp, a library that parses every module in your top-level package and builds a directed graph of import statements. It does this statically, without importing or executing your code, so Django settings, database connections and app registry setup never come into play. import-linter then checks that graph against the contracts you declare in configuration. The three you will use most are layers, independence and forbidden.
The graph matters because the rules apply to chains of imports, not only to direct ones. If billing is supposed to be independent of shipping, a path from billing through core.utils into shipping still counts as a violation, and the report shows the full chain. Layers and independence contracts check these indirect paths, which closes the loophole of routing a dependency through a shared helper module.
The command, lint-imports, prints each contract as kept or broken and exits non-zero when any contract is broken. That exit code is all CI or a pre-commit hook needs to block a change.
The limitation is that static analysis only sees import statements. It cannot see Django's string-based references such as ForeignKey("shipping.Parcel"), apps.get_model(), importlib calls or signal receivers wired up by path. Those dependencies exist at runtime but do not appear in the graph.
How do you choose a target architecture before writing contracts?
Before writing a single contract, decide which way dependencies are supposed to flow. import-linter checks that the code matches a rule; it cannot tell you whether the rule is a good one. If you encode boundaries before agreeing on them, the first failing build becomes an argument about architecture held inside a pull request, which is a poor place for it.
A common starting point for a Django monolith has two dimensions. Within each feature app, layers point downward: api (views, serializers, URL routing) depends on services (use cases, transactions, orchestration), which depends on domain (models and business rules), which may depend on a shared package of utilities. Nothing points back up. A model should never import a serializer, and a service should never reach into a view. Across the codebase, sibling feature apps such as billing, shipping and catalog should not import each other directly. When one app needs another's data, it goes through an explicit, narrow interface. That interface can be a published service function or an event.
Sketch this on a whiteboard or in a short design document, then check it against the real import graph. You will usually find a few edges that contradict the drawing. Each one points to one of two things: a boundary drawn in the wrong place, or a dependency the team actually wants to remove. Decide which before going further.
Once the team has signed off, the contracts become executable documentation of that decision. That framing matters. Developers who hit a failing check are being reminded of an agreement they took part in. They are not being blocked by a rule nobody explained.
billing shipping catalog
+-----------+ +-----------+ +-----------+
| api | X | api | X | api |
+-----+-----+ +-----+-----+ +-----+-----+
| | |
v v v
+-----------+ +-----------+ +-----------+
| services |<-----| services | X | services |
+-----+-----+ +-----+-----+ +-----+-----+
| | |
v v v
+-----------+ +-----------+ +-----------+
| domain | X | domain | X | domain |
+-----+-----+ +-----+-----+ +-----+-----+
| | |
+------------------+------------------+
|
v
+------------------------+
| shared (utilities) |
+------------------------+
v allowed import direction (downward only, never back up)
<---- cross-app call via a published service function or event
X no direct imports between sibling feature apps
Agree on this target before writing any contracts: within each feature app, imports flow only downward from api to services to domain to shared, and sibling apps do not import each other except through a narrow, explicit interface.
How do you configure layers, independence and forbidden contracts?
Configuration can live in a dedicated .importlinter file, in setup.cfg under an [importlinter] section, or in pyproject.toml under [tool.importlinter]. Use whichever file your team already reviews; a separate file is easy to miss. Set root_packages to the top-level packages you want analysed. import-linter builds its import graph by locating those packages on the Python path, so it cannot analyse what Python cannot import.
That requirement causes most first-run failures in Django projects. Many projects use a flat layout where apps sit beside manage.py with no shared parent. Move the apps under one project package with an __init__.py at every level, or list each app as its own root package. Then run lint-imports from the directory that puts those packages on the path.
Writing the three contracts
Use a layers contract with containers set to each app, such as billing, notifications and catalog, and layers views, services, models. A single contract then enforces the same direction inside every app: views may import services, and services may import models, but nothing imports upward.
Use an independence contract that lists billing, notifications and catalog. This stops the apps from importing each other in any direction.
Use a forbidden contract to keep django.http and rest_framework out of the services and models modules. Because these are third-party packages, set include_external_packages = true. Without it, external imports are left out of the graph and the contract cannot check them.
| Contract | Enforces | Use when |
|---|---|---|
| Layers | One-way dependency between ordered layers | Code within an app has a clear direction |
| Independence | No imports between listed modules | Apps should stay separable |
| Forbidden | Specific modules never imported | Framework or transport code must stay out of the domain |
# .importlinter at the repo root; run `lint-imports` from this directory
[importlinter]
root_packages =
myproject
# Add third-party packages to the graph so the forbidden contract can see them
include_external_packages = True
[importlinter:contract:app-layers]
name = Each app flows views -> services -> models
type = layers
# Higher layers may import lower ones, never the reverse
layers =
views
services
models
containers =
myproject.billing
myproject.notifications
myproject.catalog
[importlinter:contract:app-independence]
name = Apps do not import each other
type = independence
modules =
myproject.billing
myproject.notifications
myproject.catalog
[importlinter:contract:domain-no-web]
name = Domain code stays free of the REST framework
type = forbidden
source_modules =
myproject.billing.services
myproject.billing.models
myproject.catalog.services
myproject.catalog.models
# External packages appear in the graph under their top-level name only
forbidden_modules =
rest_framework
A .importlinter file with one layers, one independence and one forbidden contract. External packages are tracked only by top-level name, so this file can forbid rest_framework but not django.http by itself.
How do you adopt import-linter on an existing codebase incrementally?
Start by running lint-imports against your contracts with nothing ignored. On a mature monolith the first run will usually fail, and that is useful: the output is a complete list of current violations. Copy each offending import into the contract's ignore_imports list and commit it. That list is now tracked debt, reviewed like any other code. Every later run passes on today's code and fails only on new violations, so CI can block regressions on day one.
Reading a reported chain
Each broken contract lists the import chains that cause it, with the line numbers of each link. A direct chain is one module importing another. An indirect chain is longer: orders.views imports shared.utils, which imports billing.models. The fix often belongs in the middle link rather than at the top, so read the whole chain before you change anything.
Common fixes
- Move shared code down a layer. If two apps import the same helper from each other, put the helper in a lower module that both can depend on.
- Invert the dependency. Have the lower layer define an interface or accept a callback, and let the higher layer supply the implementation.
- Replace direct model imports with service functions. The other app calls a function and gets back plain data, so the owning app keeps control of its schema.
- Route cross-app communication through signals or a shared interface module. Neither app then needs to import the other.
Each fix removes one line from ignore_imports, so you pay the debt down a little with every feature that touches the area. A big-bang refactor needs a long-lived branch, a code freeze, and large merges. Incremental adoption needs none of these, and the work is spread across ordinary pull requests.
# .importlinter (at the repository root)
# Run `lint-imports` with an empty ignore list first, then copy each
# reported link here. This list is tracked debt: each fix deletes a line.
[importlinter]
root_package = myproject
[importlinter:contract:apps-independent]
name = orders and billing do not import each other
type = independence
modules =
myproject.orders
myproject.billing
ignore_imports =
# Direct chain: the view reads billing models itself.
# Planned fix: call a billing service function that returns plain data.
myproject.orders.views -> myproject.billing.models
# Middle link of an indirect chain:
# orders.views -> shared.utils -> billing.models
# Planned fix: move the helper down into a module that imports neither app.
myproject.shared.utils -> myproject.billing.models
[importlinter:contract:layers]
name = Views sit above services, services above models
type = layers
containers =
myproject.orders
myproject.billing
layers =
views
services
models
# Empty on purpose: this contract had no existing violations,
# so any new upward import fails CI immediately.
An import-linter config that records existing violations as ignore_imports debt, including the middle link of an indirect chain, so CI passes today and fails only on new violations.
Wiring lint-imports into CI, pre-commit and code review
Run lint-imports as its own CI job, next to the test suite and your other linters, and make it a required check. Its own job means a failure reads as an architecture violation, not a broken test. It only needs the project importable from the checkout and the config file present, so it can run in parallel with tests rather than after them.
A pre-commit hook is optional. Define it as a local hook that calls lint-imports, so developers get feedback before pushing. Some teams leave it out because it slows commits. CI remains the enforcement point either way.
Make contract changes deliberate
Put the import-linter configuration under a code-owners rule so that edits need approval from whoever owns the architecture, usually a platform or staff group. Adding an entry to an ignore_imports list is an architectural decision and deserves the same review as a schema change. Adopt a simple policy: the ignore list only shrinks. Reviewers reject new ignores unless they come with a linked plan to remove them.
Also watch for workarounds that pass the linter without fixing the dependency. A function-local import added to break a cycle is often a sign someone hit a rule. String-based lookups such as apps.get_model("billing", "Invoice") or importlib calls are worse, because static analysis never sees them. Flag both in review.
Measure the cost
Building the import graph takes time that grows with codebase size. Time the step in your own pipeline before deciding whether it belongs in pre-commit.
# .pre-commit-config.yaml
# Optional local hook: gives developers import-contract feedback before pushing.
# CI still runs `lint-imports` as its own required job; this hook is a convenience.
repos:
- repo: local
hooks:
- id: lint-imports
name: import-linter contracts
# Uses the import-linter installed in the developer's virtualenv,
# so it reads the same contract config that CI uses.
entry: lint-imports
language: system
# lint-imports analyses the whole import graph, not individual files,
# so don't pass the staged filenames to it.
pass_filenames: false
# Only trigger when Python files are staged.
types: [python]
A local pre-commit hook that runs lint-imports against the whole project when Python files change. CI remains the place where contracts are enforced.
When should you avoid import-linter, and what are the alternatives?
import-linter only sees import statements, and Django wires much of a monolith together through strings. ForeignKey("billing.Invoice"), apps.get_model(), INSTALLED_APPS, include("orders.urls"), signal receivers and dotted paths in settings never show up in the import graph. A passing run can therefore hide tight coupling. Cross-app ForeignKeys cause the most trouble. Even when written as strings, they tie two apps' schemas together and create migration ordering dependencies that no contract will report.
Check how your installed version handles imports under TYPE_CHECKING and imports inside functions. Don't assume either way, because the answer decides whether a contract covers those cases. Give every ignore entry an owner and a reason. If the ignore list only ever grows, the contract describes where you want to be, and it has stopped describing the code. The tool also has no opinion on whether a boundary is correct. It enforces whatever rules you give it.
It is premature to adopt it for a codebase with a handful of apps, or before the team agrees on a target architecture. Contracts written before that agreement tend to get silenced or worked around, and that makes enforcement look like obstruction.
| Approach | What it catches | Main cost |
|---|---|---|
| Code review conventions | Intent, string-based dependencies, model design | Inconsistent; depends on reviewer attention |
| Custom architecture tests over the import graph | Any rule you can express, including checks on model relations | You write and maintain the tooling |
| Separately installed packages | Undeclared dependencies fail at install or import time | Packaging, versioning and release overhead |
| Separate services | Hard runtime and data boundaries | Network calls, operations, distributed consistency |
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 boundaries, 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.