Enforcing boundaries with architecture tests
Lab: build a small Python modular monolith, write import-linter contracts for public-API-only access, dependency direction and no cycles, break each rule on purpose, read the failing output and exit code a CI job would see, and find what a static check cannot see.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create the Spokes monolith
- Step 2: Write the contracts and run them
- Step 3: Break privacy
- Step 4: Create a cycle
- Step 5: Make it fail the build
- Step 6: What a static check cannot see
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of Modular Monolith
- Why modular first: cost of distribution versus cost of coupling Concept · 15 min
- Module anatomy, owned tables and component principles Concept · 25 min
- Enforcing boundaries with architecture tests Lab · 25 min
- Cross-module calls, in-process events and transactions Concept · 20 min
- Carving a big ball of mud into modules Worked example · 30 min
- Modularity check Knowledge check · 6 questions
What you will learn
- Enforce module boundaries, including acyclic and stable dependency directions, with automated dependency checks that fail the build.
01. Goal and setup
A boundary rule that lives in a wiki erodes as soon as a deadline comes close. This lab turns the three rules of lesson 2 into an architecture test: a check that runs in the build and fails it. You will check that modules use each other only through their public API, that dependencies point towards stable modules, and that no cycle exists between modules. Then you break each rule, predict the result before running, and read what the tool reports.
You need: Python 3.11 or newer and a terminal with bash or zsh (on Windows, use WSL or Git Bash). The lab uses import-linter 2.17, released on 18 November 2026; its private_modules contract is new in that release. The outputs below were produced with Python 3.12.13.
spokes-lab/
├── .venv/ setup: a virtual environment with import-linter
├── scaffold.py step 1: writes the spokes package (run it again to reset)
├── .importlinter step 2: the three contracts
└── spokes/ written by scaffold.py
├── app.py composition root
├── platform/ a tiny in-process event bus
└── accounts/ fleet/ rentals/ billing/mkdir spokes-lab && cd spokes-lab
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --quiet import-linter==2.17
lint-imports --version
python --versionimport-linter 2.17
Python 3.12.1302. Step 1: Create the Spokes monolith
Save this file as scaffold.py in spokes-lab. It writes five modules of the bike-rental platform from lessons 1 and 2. Each business module has a public api.py and a private _store.py, whose leading underscore marks it as internal. platform holds the event bus, and app.py is the composition root: the one place that knows every module and wires billing's handler to rentals' RideEnded event.
"""scaffold.py: writes the Spokes modular monolith used in this lab.
Run it again at any time to reset every file to its clean state.
"""
from pathlib import Path
FILES = {
"spokes/__init__.py": "",
"spokes/platform/__init__.py": "",
"spokes/platform/events.py": '''\
"""A tiny in-process event bus: modules publish facts, others subscribe."""
from collections import defaultdict
_handlers = defaultdict(list)
def subscribe(event_type, handler):
_handlers[event_type].append(handler)
def publish(event):
for handler in _handlers[type(event)]:
handler(event)
''',
"spokes/accounts/__init__.py": "",
"spokes/accounts/_store.py": 'RIDERS = {"r1": {"name": "Ana", "card_ok": True}}\n',
"spokes/accounts/api.py": '''\
from spokes.accounts._store import RIDERS
def can_ride(rider_id: str) -> bool:
return RIDERS.get(rider_id, {}).get("card_ok", False)
''',
"spokes/fleet/__init__.py": "",
"spokes/fleet/_store.py": 'BIKES = {"b7": "docked"}\n',
"spokes/fleet/api.py": '''\
from spokes.fleet._store import BIKES
def take_bike(bike_id: str) -> bool:
if BIKES.get(bike_id) != "docked":
return False
BIKES[bike_id] = "in use"
return True
''',
"spokes/rentals/__init__.py": "",
"spokes/rentals/_store.py": "RIDES: dict[int, dict] = {}\n",
"spokes/rentals/api.py": '''\
from dataclasses import dataclass
from spokes.accounts.api import can_ride
from spokes.fleet.api import take_bike
from spokes.platform.events import publish
from spokes.rentals._store import RIDES
@dataclass(frozen=True)
class RideEnded: # part of the public API: other modules may subscribe
ride_id: int
rider_id: str
minutes: int
def start_ride(rider_id: str, bike_id: str) -> int:
if not (can_ride(rider_id) and take_bike(bike_id)):
raise ValueError("cannot start ride")
ride_id = len(RIDES) + 1
RIDES[ride_id] = {"rider": rider_id, "bike": bike_id}
return ride_id
def end_ride(ride_id: int, minutes: int) -> None:
publish(RideEnded(ride_id, RIDES[ride_id]["rider"], minutes))
''',
"spokes/billing/__init__.py": "",
"spokes/billing/_store.py": "CHARGES: dict[int, int] = {}\n",
"spokes/billing/api.py": '''\
from spokes.billing._store import CHARGES
from spokes.platform.events import subscribe
from spokes.rentals.api import RideEnded
UNLOCK_CENTS, PER_MINUTE_CENTS = 100, 25
def _on_ride_ended(event: RideEnded) -> None:
CHARGES[event.ride_id] = UNLOCK_CENTS + PER_MINUTE_CENTS * event.minutes
def register() -> None:
subscribe(RideEnded, _on_ride_ended)
def charge_for(ride_id: int) -> int:
return CHARGES[ride_id]
''',
"spokes/app.py": '''\
"""Composition root: the only place that knows every module."""
from spokes.billing import api as billing
from spokes.rentals import api as rentals
billing.register()
ride = rentals.start_ride("r1", "b7")
rentals.end_ride(ride, minutes=12)
print(f"ride {ride} charged {billing.charge_for(ride)} cents")
''',
}
for name, text in FILES.items():
path = Path(name)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
print(f"wrote {len(FILES)} files under spokes/")python scaffold.py
python -m spokes.appwrote 16 files under spokes/
ride 1 charged 400 centsThe charge is 100 cents to unlock plus 25 cents for each of the 12 minutes. Rentals never calls billing: it publishes RideEnded, and billing reacts. That is the event fix from lesson 2, so the dependency points one way only, from billing to rentals.
03. Step 2: Write the contracts and run them
Save the configuration below as .importlinter next to scaffold.py. import-linter looks for .importlinter, setup.cfg or pyproject.toml in the current folder; the same contracts can live in pyproject.toml under [tool.importlinter].
[importlinter]
root_package = spokes
[importlinter:contract:public-api-only]
name = Modules use each other only through their public API
type = private_modules
[importlinter:contract:module-direction]
name = Module dependencies point towards stable modules
type = layers
layers =
spokes.billing
spokes.rentals
spokes.accounts | spokes.fleet
spokes.platform
[importlinter:contract:no-module-cycles]
name = No cycles between the children of spokes
type = acyclic_siblings
ancestors = spokes
depth = 0private_moduleslets a module whose name starts with an underscore be imported only from inside its parent package:spokes.rentals._storeonly fromspokes.rentals. It checks direct imports only, so billing may importrentals.apieven thoughrentals.apiimportsrentals._store; that is the public API doing its job.layerslists modules from top to bottom. A higher layer may import a lower one, never the reverse, and this includes chains through modules not listed. The|makesaccountsandfleetindependent: neither may import the other. Putting the most depended-upon modules at the bottom is the stable dependencies principle written down.acyclic_siblingsforbids cycles between the children ofspokes, whether a layer lists them or not;depth = 0checks only that first level.
Run the check. --no-logo hides the ASCII logo that import-linter prints at the start.
lint-imports --no-logo---------
Contracts
---------
Analyzed 16 files, 11 dependencies.
-----------------------------------
Modules use each other only through their public API KEPT
Module dependencies point towards stable modules KEPT
No cycles between the children of spokes KEPT
Contracts: 3 kept, 0 broken.04. Step 3: Break privacy
A billing developer wants to look at ride data and takes a shortcut into rentals' private store. Predict first: which of the three contracts breaks? Then add the import and run the check again.
echo 'from spokes.rentals._store import RIDES # quick look' >> spokes/billing/api.py
lint-imports --no-logo---------
Contracts
---------
Analyzed 16 files, 12 dependencies.
-----------------------------------
Modules use each other only through their public API BROKEN
Module dependencies point towards stable modules KEPT
No cycles between the children of spokes KEPT
Contracts: 2 kept, 1 broken.
----------------
Broken contracts
----------------
Modules use each other only through their public API
----------------------------------------------------
Private modules may only be imported from within their parent package:
- spokes.billing.api -> spokes.rentals._store (l.18)Only the privacy contract breaks. The report names the importing module, the private module and the line (l.18, the line you appended). The other two contracts hold, because billing depending on rentals is an allowed direction. Run python scaffold.py to reset every file before the next step.
05. Step 4: Create a cycle
Now a rentals developer wants to charge the rider the moment a ride ends, and imports billing directly. Predict first: which contracts break, and does the application still start?
python scaffold.py
echo 'from spokes.billing.api import charge_for # bill now' >> spokes/rentals/api.py
python -m spokes.app
lint-imports --no-logoTraceback (most recent call last):
...
ImportError: cannot import name 'charge_for' from partially initialized module
'spokes.billing.api' (most likely due to a circular import) (.../spokes/billing/api.py)---------
Contracts
---------
Analyzed 16 files, 12 dependencies.
-----------------------------------
Modules use each other only through their public API KEPT
Module dependencies point towards stable modules BROKEN
No cycles between the children of spokes BROKEN
Contracts: 1 kept, 2 broken.
----------------
Broken contracts
----------------
Module dependencies point towards stable modules
------------------------------------------------
spokes.rentals is not allowed to import spokes.billing:
- spokes.rentals.api -> spokes.billing.api (l.26)
No cycles between the children of spokes
----------------------------------------
No cycles are allowed in spokes.
It could be made acyclic by removing 1 dependency:
- .rentals -> .billing (1 import)Two contracts break for one line. The layers contract reports an upward import, from rentals into billing, which sits above it. The acyclic contract reports the cycle between the two siblings and names the single dependency whose removal would end it.
Python also refused to start, but only because both files import names at load time, so whichever loads second finds the other half-built. Move the same import inside a function and the application starts, yet the cycle is still there. That is why you need the check rather than relying on Python to complain. The fix is the one the scaffold already uses: rentals publishes RideEnded and billing subscribes. Run python scaffold.py to reset.
06. Step 5: Make it fail the build
lint-imports exits with status 0 when every contract is kept and 1 when any contract is broken, so any CI system can run it as a step. Each broken run above ended with status 1. Check the clean state explicitly:
python scaffold.py
lint-imports --no-logo > /dev/null; echo "lint-imports exit code: $?"lint-imports exit code: 0- name: Check module boundaries
run: |
python -m pip install import-linter==2.17
lint-importsBecause the step fails on a non-zero exit code, a pull request that adds a forbidden import cannot merge while the check is required. import-linter can also run as a pre-commit hook; its documentation says the hook must use language: system so that it sees your virtual environment.
07. Step 6: What a static check cannot see
import-linter reads import statements without running your code. Predict first: if billing loads the private store by name at run time, does the check notice?
cat >> spokes/billing/api.py <<'EOF'
import importlib
RIDES = importlib.import_module("spokes.rentals._store").RIDES
EOF
lint-imports --no-logo
python scaffold.py---------
Contracts
---------
Analyzed 16 files, 11 dependencies.
-----------------------------------
Modules use each other only through their public API KEPT
Module dependencies point towards stable modules KEPT
No cycles between the children of spokes KEPT
Contracts: 3 kept, 0 broken.Every contract is kept, although billing now reads rentals' private data. A module name built at run time, a plug-in loader or reflection is invisible to any static import check. Shopify's 2024 retrospective on Packwerk, its Ruby boundary checker, describes the same gap: a package with no reported violations still failed to boot when it was loaded on its own. Combine the check with code review that looks for importlib and __import__, and, for a module you may extract, with tests that run it with only its declared dependencies loaded.
08. Troubleshooting
[importlinter]
root_package = spokes
[importlinter:contract:public-api-only]
name = Modules use each other only through their public API
type = forbidden
source_modules =
spokes.*
forbidden_modules =
spokes.*._store
allow_indirect_imports = True09. Check your understanding
10. Apply it
- Add the three contracts to the sample monolith of this skill's practice task, with one layer per module and the most depended-upon modules at the bottom. Make one deliberate violation, show the failing run and its exit code in CI, then fix it with a call through the API or an event.
- If your sample is TypeScript, dependency-cruiser does the same job. The configuration below expresses the privacy rule and the no-cycles rule for a
src/billing/...layout where private files start with an underscore. InpathNot,$1stands for the module folder captured byfrom.path, so a module may still import its own private files.
/** Module boundaries for src/<module>/: files starting with _ are private. */
module.exports = {
forbidden: [
{
name: 'public-api-only',
severity: 'error',
from: { path: '^src/([^/]+)/' },
to: { path: '^src/[^/]+/_', pathNot: '^src/$1/' },
},
{
name: 'no-cycles',
severity: 'error',
from: {},
to: { circular: true },
},
],
options: { tsPreCompilationDeps: true },
};npx -y -p [email protected] -p [email protected] \
depcruise src --config .dependency-cruiser.cjs error public-api-only: src/billing/api.ts → src/rentals/_store.ts
x 1 dependency violations (1 errors, 0 warnings). 5 modules, 5 dependencies cruised.11. Review prompt
Without looking back, explain what each of the three contracts checks and which principle from lesson 2 it enforces. Say why a single import from rentals into billing broke two contracts, why Python refused to start in that case, and why you cannot rely on Python to catch cycles. Explain how the check fails a CI build, and name two kinds of dependency that no static import check can see and what you would add to catch them.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.