Clean Architecture Tested in Python, Rust and TypeScript
In short
- Clean Architecture comes down to one checkable rule: source-code dependencies point inwards, towards the business rules. Ports and adapters (2005), the onion (2008) and the clean circles (2012) all state it in their own words.
- I built the same small service twice, as one flat module and in layers, and measured both. Layering made the fastest test of a business rule more than 5,000 times faster and cut the modules needed to reach that rule from 274 to 44.
- It also cost 3.7 times the code, and the flat version needed fewer lines for both changes I made. The gains are in testing, in where code goes, and in what each part may import; not in line counts.
- Without an automated check, the rule erodes. Python enforces it with import-linter, Rust with its crate graph on every build, TypeScript with dependency-cruiser. Each caught every violation I planted.
- How much structure to use depends on how long the code will live and how much its rules matter. A thin CRUD service needs little; a service with real rules and several entry points needs the full shape.
Every codebase has a folder layout, and few share one. Some put SQL next to the route that uses it; others hide it behind three layers of classes. A new engineer spends their first weeks learning where things go, and code reviews argue about it again each time. Clean Architecture gives a shared answer to two questions: where does this code go, and what may it import? The answer fits in one sentence, and a machine can check it. That second property is what turns a folder convention into an engineering rule.
Much of what is written about it argues for or against it without numbers, so this post measures it. I built one small service twice, once as a single module and once in layers, and compared them: test speed, import cost, the size of two real changes, and how each language catches a broken rule. The service is written in Python, and its core is repeated in Rust and TypeScript. Every number below comes from that lab, and every quotation was checked against its source.
What structure is for
The oldest argument still applies. In 1972 David Parnas compared two ways to split the same program into modules and concluded: "We propose instead that one begins with a list of difficult design decisions or design decisions which are likely to change. Each module is then designed to hide such a decision from the others." The database, the web framework, the model runtime and the message queue are such decisions. The business rules are the reason the program exists. Structure keeps the first from leaking into the second.
Is there evidence that structure pays off? Some, all of it about coupling in general rather than Clean Architecture in particular:
- The 2017 State of DevOps report, a large practitioner survey, found that "Loosely coupled architectures and teams are the strongest predictor of continuous delivery." One of its markers of loose coupling: "Respondents could do testing without requiring an integrated environment."
- MacCormack, Rusnak and Baldwin defined propagation cost as "the proportion of elements that could be affected, on average, when a change is made to one element in the system". After Mozilla's redesign, "the propagation cost of the design has dropped from 17.35% to 2.78%."
- A mapping study of 73 papers on architecture erosion, the gap "between the intended and implemented architectures", found undesired and cyclic dependencies among "the most frequently mentioned structural symptoms".
- In four systems studied by Oyetoyan and colleagues, "components that transition between dependency cycles have higher probability to be defect-prone". Le and colleagues used architectural decay in 10 open-source systems to predict future issue- and change-proneness. Mo and colleagues measured how well 108 open-source and 21 industrial projects decouple into independently replaceable modules.
Read these with care. They are surveys and correlations, not experiments, and none of them tests Clean Architecture as such. DORA measures coupling between services and teams, not layers inside one codebase. Sas, Avgeriou and Uyumaz, after studying architectural smells in nine industrial C/C++ projects, write: "We cannot claim of course, that the presence of the two smells are directly the cause of the ripple effects of these changes in other components." What the literature supports is narrower and still useful: tangled dependencies go with costly change, and they creep in unless someone stops them.
One rule under several names
Clean Architecture, hexagonal architecture and onion architecture are usually presented as rivals. They are the same rule, stated by different people over forty years:
| Idea | Year | Author | The rule, in the author's words |
|---|---|---|---|
| Information hiding | 1972 | D. L. Parnas | "Each module is then designed to hide such a decision from the others." |
| Dependency inversion | 1996 | Robert C. Martin | "ABSTRACTIONS SHOULD NOT DEPEND UPON DETAILS. DETAILS SHOULD DEPEND UPON ABSTRACTIONS." |
| Ports and adapters (hexagonal) | 2005 | Alistair Cockburn | "The rule to obey is that code pertaining to the inside part should not leak into the outside part." |
| Onion architecture | 2008 | Jeffrey Palermo | "In other words, all coupling is toward the center." |
| Clean Architecture | 2012 | Robert C. Martin | "This rule says that source code dependencies can only point inwards." |
Robert Martin's 2012 post gives the reason for the direction: "The outer circles are mechanisms. The inner circles are policies." Policy is what the business decides: who may approve what, which model goes live. Mechanism is how the program talks to the world: HTTP, SQL, a GPU. Policy changes when the business changes; mechanism changes when technology does. Keeping them apart means each kind of change stays in its own place.
The number of circles is not the point. Martin again: "There's no rule that says you must always have just these four. However, The Dependency Rule always applies." Sam Keen's Clean Architecture with Python keeps Martin's four: domain, application, interface adapters, and frameworks and drivers. Most Python projects merge the outer two and use three names: domain, application and infrastructure, plus one module that wires them together.
The rule is about source-code imports, not about which code calls which at run time. A use case must save a model version, so at run time it calls into SQLite, which lives outside. Martin's Dependency Inversion Principle makes the two directions compatible: "ABSTRACTIONS SHOULD NOT DEPEND UPON DETAILS. DETAILS SHOULD DEPEND UPON ABSTRACTIONS." The use case owns an abstraction, a port, that says what it needs. The SQLite adapter imports that port and implements it. The call goes out; the import points in.
The same few terms come up in every book on the subject. This is what they mean here:
| Term | Meaning | In the lab |
|---|---|---|
| Entity | An object with identity, and the rules that protect it | ModelVersion |
| Value object | An immutable value, compared by its contents | PromotionPolicy |
| Use case | One thing a user can do; it loads, applies rules and saves | PromoteVersion |
| Port | An interface owned by the inner layers, stating what they need from outside | ModelRepository, Evaluator |
| Adapter | Code that implements a port with a real technology, or turns a request into a use-case call | SqliteModels, web.py |
| DTO | Plain data that crosses a boundary | VersionView |
| Composition root | The one place that picks concrete classes and builds the object graph | bootstrap.py, main.py |
Where code goes
The everyday value of the rule is a map. When a new piece of code arrives, you ask what kind of code it is, and the layer follows. This is the map I use, with the lab's names:
| Kind of code | Layer | In the lab | Test for it |
|---|---|---|---|
| Business rules and the errors they raise | Domain | promote_over, NotBetter | A domain expert would recognise the rule and could argue about it. |
| Orchestration: load, apply the rule, save | Application (use case) | PromoteVersion | One class per thing a user can do. No SQL, no HTTP. |
| What a use case needs from outside | Application (port) | ModelRepository, Evaluator, Clock | Named after the need, not the technology. |
| Data that crosses the boundary | Application (DTO) | VersionView | Plain values. No ORM rows, no request models. |
| SQL, ORM models, migrations | Infrastructure | sqlite.py | The schema can change without touching a rule. |
| Routes, request schemas, status codes | Infrastructure (delivery) | web.py | Translate in, call one use case, translate out. |
| Model runtime: tensors, batching, GPU memory, ONNX or PyTorch | Infrastructure | behind Evaluator | The threshold is policy; computing the metric is mechanism. |
| Choosing concrete classes, reading configuration | Composition root | bootstrap.py, main.py | The only code that names every adapter. |
There is no standard folder tree. Martin's post names circles, not folders, and two Python books with published code, Percival and Gregory's Architecture Patterns with Python and Keen's Clean Architecture with Python, choose different names for the same roles. The lab's own names are in the tree below.
| Role | Percival and Gregory | Keen | Martin (2012) |
|---|---|---|---|
| Business rules | domain/ | domain/ | Entities |
| Use cases and ports | service_layer/ | application/ | Use cases |
| HTTP, CLI, controllers | entrypoints/ | interfaces/ | Interface adapters |
| Database, frameworks | adapters/ | infrastructure/ | Frameworks and drivers |
| Wiring | bootstrap.py | web_main.py, cli_main.py | Not named in the 2012 post |
The lab uses three folders and keeps the wiring outside them:
registry/
βββ domain/model.py # entities, rules and their errors
βββ application/
β βββ ports.py # Protocols the use cases need
β βββ use_cases.py # one class per user action, plus VersionView
βββ infrastructure/
β βββ sqlite.py, memory.py # repository adapters
β βββ web.py # FastAPI routes and error mapping
βββ bootstrap.py # composition root: builds the use cases
main.py # web entry point: picks adapters
tests/ # domain, use cases, one contract suite for both repositories
Whatever the names, four decisions are worth making on purpose. First, where ports live: many examples put repository interfaces in the domain; the lab puts them in the application layer, next to the use cases that need them. Either works if the whole codebase picks one. Second, ORM classes are not entities: they live with the adapter, which maps between the two. Third, only the entry points and the composition root may import everything. When they start to hold logic, the layers have started to leak. Fourth, transactions: the lab's save takes several versions and writes them in one transaction, so a promotion and the champion's retirement commit together. Larger systems use a unit of work for this, but Percival and Gregory add a caution: "Your ORM probably already has some perfectly good abstractions around atomicity."
In a codebase with several business areas, layers should not be the top-level folders. Martin's "Screaming Architecture" post: "If your architecture is based on frameworks, then it cannot be based on your use cases." Fowler, on the same split: "it should only be applied at a relatively small granularity." So the top level names the business areas, such as registry/ and billing/, and each one has its own domain, application and infrastructure inside.
Machine learning code needs one extra line on the map. A promotion threshold such as "beat the champion by 0.005 AUC" is policy and belongs in the domain. Tensor shapes, batching, GPU memory, ONNX sessions and model compilation are mechanism and belong behind a port such as Evaluator. In the lab the evaluator is a stub; in production it might call a serving endpoint or run a PyTorch model. The use case cannot tell the difference, and its tests do not need a GPU.
The lab: one service, built twice
The service is a small model registry with four rules. A version is registered as a candidate. It cannot be promoted until it has been evaluated on the deciding metric. Whoever trained it cannot approve it. And it must beat the current champion by a set margin, at which point the old champion retires. Three HTTP endpoints expose it: register, evaluate and promote. The data lives in SQLite.
The flat version is one FastAPI module of 65 lines: routes, SQL and rules together, written the way a tidy small service usually looks. The layered version has a domain, an application layer with ports and use cases, adapters for SQLite, memory and HTTP, and a composition root. A behaviour test sends the same 12 HTTP requests to both, covering a self-review, a gain that is too small, a retired champion and an unknown version, and checks that every status code and response body match. They do.
The full lab, with every script and output behind the numbers in this post, is a 60 KB download: registry-lab.zip. It includes the two changed versions of each app and the planted violations as outputs.
| Measurement | Flat (one module) | Layered |
|---|---|---|
| Production code | 65 lines in 1 file | 238 lines in 8 files |
| Functions that mix HTTP, SQL and rules | 4 of 4 | 0 of 13 |
| Fastest test that exercises a promotion rule | 10.5 ms (through HTTP) | 1.9 Β΅s (domain objects) |
| Modules loaded to import the rule | 274 | 44 |
| Change 1: add a command-line tool | 17 lines added; the tool loads FastAPI | 32 lines added in 2 new files; no existing file changed |
| Change 2: a new promotion rule | 8 added, 5 removed, in 1 file | 16 added, 8 removed, in 3 files |
The domain holds the rules and nothing else. It imports only the standard library:
"""Model versions and the rules for promoting one to champion. No I/O, no framework."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
class Stage(Enum):
CANDIDATE = "candidate"
CHAMPION = "champion"
RETIRED = "retired"
class PromotionError(Exception):
"""A promotion rule was broken. Outer layers translate it; the domain knows nothing of HTTP."""
class NotEvaluated(PromotionError):
pass
class NotBetter(PromotionError):
pass
class SelfReview(PromotionError):
pass
class WrongStage(PromotionError):
pass
@dataclass(frozen=True)
class PromotionPolicy:
"""Which metric decides, and by how much a candidate must beat the champion."""
metric: str
min_gain: float
higher_is_better: bool = True
def gain(self, candidate: float, champion: float) -> float:
return candidate - champion if self.higher_is_better else champion - candidate
@dataclass
class ModelVersion:
name: str
version: int
trained_by: str
created_at: datetime
metrics: dict[str, float] = field(default_factory=dict)
stage: Stage = Stage.CANDIDATE
promoted_by: str | None = None
def record(self, metrics: dict[str, float]) -> None:
if self.stage is not Stage.CANDIDATE:
raise WrongStage(f"{self.name} v{self.version} is {self.stage.value}")
self.metrics.update(metrics)
def promote_over(self, champion: ModelVersion | None, policy: PromotionPolicy, reviewer: str) -> None:
"""Make this version the champion, retiring the current one, if the rules allow it."""
if self.stage is not Stage.CANDIDATE:
raise WrongStage(f"{self.name} v{self.version} is {self.stage.value}")
if reviewer == self.trained_by:
raise SelfReview("the person who trained a model cannot approve it")
if policy.metric not in self.metrics:
raise NotEvaluated(f"no {policy.metric} recorded for v{self.version}")
if champion is not None:
gain = policy.gain(self.metrics[policy.metric], champion.metrics[policy.metric])
if gain < policy.min_gain:
raise NotBetter(f"gain {gain:.4f} is below the required {policy.min_gain}")
champion.stage = Stage.RETIRED
self.stage, self.promoted_by = Stage.CHAMPION, reviewer
The ports say what the use cases need, in their own terms. They are Protocol classes, so an adapter qualifies by having the right methods, without inheriting from anything:
"""What the use cases need from the outside world, stated as Protocols (structural interfaces)."""
from __future__ import annotations
from datetime import datetime
from typing import Protocol
from registry.domain.model import ModelVersion
class ModelRepository(Protocol):
def get(self, name: str, version: int) -> ModelVersion | None: ...
def champion(self, name: str) -> ModelVersion | None: ...
def latest_version(self, name: str) -> int: ...
def save(self, *versions: ModelVersion) -> None: ... # all or nothing
class Evaluator(Protocol):
"""Scores a model version on a named dataset. Runtimes (PyTorch, ONNX, a remote endpoint) live behind it."""
def evaluate(self, model: ModelVersion, dataset: str) -> dict[str, float]: ...
class Clock(Protocol):
def now(self) -> datetime: ...
The use cases orchestrate: load, apply the rule, save, return plain data. They contain no SQL, no HTTP and no status codes.
"""Use cases: one class per thing a user can do. They orchestrate; the rules live in the domain."""
from __future__ import annotations
from dataclasses import dataclass
from registry.application.ports import Clock, Evaluator, ModelRepository
from registry.domain.model import ModelVersion, PromotionPolicy
class NotFound(Exception):
"""The version asked for does not exist: an application concern, not a business rule."""
@dataclass(frozen=True)
class VersionView:
"""What leaves the application layer: plain data, safe to serialise."""
name: str
version: int
stage: str
metrics: dict[str, float]
promoted_by: str | None
@classmethod
def of(cls, m: ModelVersion) -> VersionView:
return cls(m.name, m.version, m.stage.value, dict(m.metrics), m.promoted_by)
class RegisterVersion:
def __init__(self, models: ModelRepository, clock: Clock) -> None:
self._models, self._clock = models, clock
def __call__(self, name: str, trained_by: str) -> VersionView:
version = ModelVersion(name, self._models.latest_version(name) + 1, trained_by, self._clock.now())
self._models.save(version)
return VersionView.of(version)
class EvaluateVersion:
def __init__(self, models: ModelRepository, evaluator: Evaluator) -> None:
self._models, self._evaluator = models, evaluator
def __call__(self, name: str, version: int, dataset: str) -> VersionView:
model = _load(self._models, name, version)
model.record(self._evaluator.evaluate(model, dataset))
self._models.save(model)
return VersionView.of(model)
class PromoteVersion:
def __init__(self, models: ModelRepository, policy: PromotionPolicy) -> None:
self._models, self._policy = models, policy
def __call__(self, name: str, version: int, reviewer: str) -> VersionView:
candidate = _load(self._models, name, version)
champion = self._models.champion(name)
candidate.promote_over(champion, self._policy, reviewer)
self._models.save(*(m for m in (candidate, champion) if m is not None))
return VersionView.of(candidate)
def _load(models: ModelRepository, name: str, version: int) -> ModelVersion:
model = models.get(name, version)
if model is None:
raise NotFound(f"{name} v{version}")
return model
The HTTP adapter translates in both directions and maps errors in one place. A refused promotion becomes a 409 here and only here:
"""HTTP adapter: turns requests into use-case calls and errors into status codes. Nothing else."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import asdict
from typing import Any
from fastapi import APIRouter, FastAPI, HTTPException
from pydantic import BaseModel
from registry.application.use_cases import (EvaluateVersion, NotFound, PromoteVersion, RegisterVersion,
VersionView)
from registry.bootstrap import UseCases
from registry.domain.model import PromotionError
class RegisterIn(BaseModel):
trained_by: str
class EvaluateIn(BaseModel):
dataset: str
class PromoteIn(BaseModel):
reviewer: str
def create_app(uc: UseCases) -> FastAPI:
app = FastAPI()
app.include_router(router(uc.register, uc.evaluate, uc.promote))
return app
def router(register: RegisterVersion, evaluate: EvaluateVersion, promote: PromoteVersion) -> APIRouter:
r = APIRouter()
@r.post("/models/{name}/versions")
def post_version(name: str, body: RegisterIn) -> dict[str, Any]:
return asdict(register(name, body.trained_by))
@r.post("/models/{name}/versions/{version}/evaluate")
def post_evaluate(name: str, version: int, body: EvaluateIn) -> dict[str, Any]:
return _call(lambda: evaluate(name, version, body.dataset))
@r.post("/models/{name}/versions/{version}/promote")
def post_promote(name: str, version: int, body: PromoteIn) -> dict[str, Any]:
return _call(lambda: promote(name, version, body.reviewer))
return r
def _call(use_case: Callable[[], VersionView]) -> dict[str, Any]: # one place maps application and domain errors to HTTP
try:
view = use_case()
except NotFound as e:
raise HTTPException(404, str(e))
except PromotionError as e:
raise HTTPException(409, f"{type(e).__name__}: {e}")
return asdict(view)
The composition root builds the use cases from whichever adapters an entry point chooses. Each entry point is a few lines:
"""Composition root: builds the use cases from whichever adapters the entry point chose.
It imports no delivery framework, so every entry point (web, CLI, worker) can share it.
"""
from __future__ import annotations
from typing import NamedTuple
from registry.application.ports import Clock, Evaluator, ModelRepository
from registry.application.use_cases import EvaluateVersion, PromoteVersion, RegisterVersion
from registry.domain.model import PromotionPolicy
POLICY = PromotionPolicy(metric="auc", min_gain=0.005)
class UseCases(NamedTuple):
register: RegisterVersion
evaluate: EvaluateVersion
promote: PromoteVersion
def build_use_cases(models: ModelRepository, evaluator: Evaluator, clock: Clock) -> UseCases:
return UseCases(RegisterVersion(models, clock), EvaluateVersion(models, evaluator), PromoteVersion(models, POLICY))
"""Web entry point: choose real adapters, build the use cases, wrap them in HTTP."""
import os
from registry.bootstrap import build_use_cases
from registry.infrastructure.memory import FixedScores, SystemClock
from registry.infrastructure.sqlite import SqliteModels
from registry.infrastructure.web import create_app
app = create_app(build_use_cases(SqliteModels(os.environ.get("REGISTRY_DB", "registry.db")), FixedScores({}), SystemClock()))
For contrast, the whole flat version. It is shorter and easy to read, and it is how most small services start:
"""The same model registry as one FastAPI module: routes, SQL and promotion rules together."""
from __future__ import annotations
import json
import os
import sqlite3
from datetime import datetime, timezone
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
METRIC, MIN_GAIN = "auc", 0.005
SCORES: dict[tuple[str, int], dict[str, float]] = {} # stands in for the model runtime
db = sqlite3.connect(os.environ.get("REGISTRY_DB", "registry.db"), check_same_thread=False)
db.execute("""CREATE TABLE IF NOT EXISTS versions (
name TEXT, version INTEGER, trained_by TEXT, created_at TEXT,
metrics TEXT, stage TEXT, promoted_by TEXT, PRIMARY KEY (name, version))""")
app = FastAPI()
class RegisterIn(BaseModel):
trained_by: str
class EvaluateIn(BaseModel):
dataset: str
class PromoteIn(BaseModel):
reviewer: str
def row_dict(row: tuple) -> dict:
name, version, _, _, metrics, stage, promoted_by = row
return {"name": name, "version": version, "stage": stage, "metrics": json.loads(metrics), "promoted_by": promoted_by}
def load(name: str, version: int) -> tuple:
row = db.execute("SELECT * FROM versions WHERE name=? AND version=?", (name, version)).fetchone()
if row is None:
raise HTTPException(404, f"{name} v{version}")
return row
@app.post("/models/{name}/versions")
def post_version(name: str, body: RegisterIn) -> dict:
version = db.execute("SELECT COALESCE(MAX(version), 0) FROM versions WHERE name=?", (name,)).fetchone()[0] + 1
with db:
db.execute("INSERT INTO versions VALUES (?,?,?,?,?,?,?)",
(name, version, body.trained_by, datetime.now(timezone.utc).isoformat(), "{}", "candidate", None))
return row_dict(load(name, version))
@app.post("/models/{name}/versions/{version}/evaluate")
def post_evaluate(name: str, version: int, body: EvaluateIn) -> dict:
row = load(name, version)
if row[5] != "candidate":
raise HTTPException(409, f"WrongStage: {name} v{version} is {row[5]}")
metrics = {**json.loads(row[4]), **SCORES[(name, version)]}
with db:
db.execute("UPDATE versions SET metrics=? WHERE name=? AND version=?", (json.dumps(metrics), name, version))
return row_dict(load(name, version))
@app.post("/models/{name}/versions/{version}/promote")
def post_promote(name: str, version: int, body: PromoteIn) -> dict:
row = load(name, version)
if row[5] != "candidate":
raise HTTPException(409, f"WrongStage: {name} v{version} is {row[5]}")
if body.reviewer == row[2]:
raise HTTPException(409, "SelfReview: the person who trained a model cannot approve it")
metrics = json.loads(row[4])
if METRIC not in metrics:
raise HTTPException(409, f"NotEvaluated: no {METRIC} recorded for v{version}")
champ = db.execute("SELECT * FROM versions WHERE name=? AND stage='champion'", (name,)).fetchone()
with db:
if champ is not None:
gain = metrics[METRIC] - json.loads(champ[4])[METRIC]
if gain < MIN_GAIN:
raise HTTPException(409, f"NotBetter: gain {gain:.4f} is below the required {MIN_GAIN}")
db.execute("UPDATE versions SET stage='retired' WHERE name=? AND version=?", (name, champ[1]))
db.execute("UPDATE versions SET stage='champion', promoted_by=? WHERE name=? AND version=?",
(body.reviewer, name, version))
return row_dict(load(name, version))
What layering buys
Faster tests
I timed one promotion scenario of ten operations at each level a test can reach: domain objects alone, use cases with in-memory adapters, use cases with a real SQLite file, and the full HTTP stack of each version.
| Test level | Median per scenario | 90th percentile | Runs |
|---|---|---|---|
| Domain objects only | 1.9 Β΅s | 1.9 Β΅s | 5,000 |
| Use cases, in-memory adapters | 148.5 Β΅s | 153.5 Β΅s | 2,000 |
| Use cases, SQLite file | 2.5 ms | 3.0 ms | 300 |
| HTTP, layered app, SQLite file | 13.3 ms | 15.1 ms | 100 |
| HTTP, flat app, SQLite file | 10.5 ms | 11.0 ms | 100 |
In the flat version the rules live inside route handlers, so the cheapest test of a rule goes through HTTP and a database: 10.5 ms. In the layered version the same rules run as plain objects in 1.9 Β΅s, more than 5,000 times faster. A thousand rule tests take about 2 ms one way and about 10 seconds the other, and the fast one needs no database, no server and no fixtures.
Two details matter when reading these numbers. The in-memory fake takes 148.5 Β΅s, much more than the domain, because it deep-copies every object it stores and returns. That is deliberate: a real database returns copies, so a fake that hands out live references would let tests pass that production would fail. And the layered HTTP path is slower than the flat one, 13.3 ms against 10.5 ms, because each test builds a fresh app and client, which costs 2.0 ms on its own. Without that setup the gap is 0.8 ms per scenario of ten requests, under 0.1 ms per request.
A fake is only useful if it behaves like the real thing, so the lab runs one contract test suite against both adapters. If the fake drifts, the contract fails:
"""One contract, every adapter: the fake used in unit tests must behave like the real database."""
import pytest
from registry.domain.model import ModelVersion, Stage
from registry.infrastructure.memory import InMemoryModels, SystemClock
from registry.infrastructure.sqlite import SqliteModels
@pytest.fixture(params=["memory", "sqlite"])
def models(request, tmp_path):
return InMemoryModels() if request.param == "memory" else SqliteModels(str(tmp_path / "r.db"))
def test_round_trip(models) -> None:
m = ModelVersion("churn", 1, "ana", SystemClock().now(), {"auc": 0.8})
models.save(m)
assert models.get("churn", 1) == m
assert models.latest_version("churn") == 1 and models.latest_version("other") == 0
def test_changes_need_save(models) -> None:
models.save(ModelVersion("churn", 1, "ana", SystemClock().now()))
models.get("churn", 1).stage = Stage.CHAMPION # mutate a loaded copy without saving
assert models.champion("churn") is None
def test_champion_lookup(models) -> None:
a, b = (ModelVersion("churn", v, "ana", SystemClock().now()) for v in (1, 2))
b.stage = Stage.CHAMPION
models.save(a, b)
assert models.champion("churn").version == 2
What a rule drags in
Where code sits decides what it drags along. I started a fresh interpreter and imported only the module that holds the promotion rule:
Reaching the rule loads 44 modules in 10.0 ms in the layered version, and 274 modules in 119.0 ms in the flat one, because the rule shares a file with FastAPI, pydantic and the SQLite connection. The difference shows up in test collection time, in the start-up of every CLI and worker, and in what breaks when a web framework releases a new major version.
On a larger Python platform I worked on, the same effect came through package files: a package's __init__.py re-exported everything, so importing one light module pulled in heavy machine-learning libraries. Resolving those exports lazily fixed the start-up cost without moving any code.
Each concern in one place
An AST scan of both versions marked every function that touches HTTP, SQL or a promotion rule:
Martin Fowler calls this the reduced scope of attention, and considers it reason enough to layer: "even without either of these reasons I would still divide into layers like this. The reduced scope of attention reason is sufficient on its own." To change how a version is stored, you read sqlite.py. To change a rule, you read model.py. In the flat version, every change means reading the function that does all three.
Two real changes
Claims about changeability are cheap, so I made two changes to both versions and measured the diffs. The first adds a second way in, a command-line tool that promotes a version. The second adds a rule: a candidate and its champion must have been scored on the same dataset.
| Change | Flat | Layered | What the numbers hide |
|---|---|---|---|
| 1. Add a command-line tool that promotes a version | 17 lines in 1 new file. Loads 313 modules, FastAPI included; refusals arrive as HTTP 409. | 32 lines in 2 new files; no existing file touched. Loads 112 modules, no web framework. | The flat tool calls a route, so changing the route changes the command line. |
| 2. Candidate and champion must be scored on the same dataset | 8 added, 5 removed, all in app.py. | 16 added, 8 removed, in the domain, use case and SQLite adapter. | A rule that adds data crosses every layer, so the flat app wins here. Only the layered rule can be tested without HTTP. |
The flat version needed fewer lines both times, so layering does not make every change smaller. What it changed was the shape of the work. The CLI was added without touching a single existing file, and it does not know HTTP exists. The new rule crossed all three layers, because it adds data, and that is the real cost of the structure: a rule that changes what is stored touches the domain, the use case that feeds it and the adapter that stores it.
A mistake the measurements caught
My first composition root also built the FastAPI app. When I added the CLI, it went through the same root, and the import probe showed it loading FastAPI and pydantic to run a command that never serves a request. The layers were right and the wiring was wrong. I split the root so that it builds use cases only, moved app construction into the web adapter, and added a contract that forbids the root from importing a web framework. Measurement found the problem; the contract keeps it from coming back.
What layering costs
The layered version is 238 lines in 8 files; the flat one is 65 lines in 1 file. That is 3.7 times the code for the same behaviour, and the count includes the in-memory adapter that the tests use. The rest of the difference is ports, mapping between rows and objects, and wiring. The authors of Architecture Patterns with Python say the same: an extra layer "does add complexity locally", "Any extra layer of indirection always increases maintenance costs", and "for simple cases, a decoupled domain model is harder work than a simple ORM/ActiveRecord pattern."
The reason given most often for paying this cost is the weakest one: "you can swap the database". Fowler: "while I often hear about data access substitution being a driver for separating the data source layer, I rarely hear of someone actually doing it." The reasons that hold up are the ones measured above: fast tests of the rules, one place for each concern, and new entry points that reuse the use cases.
Martin's own package metrics show where the remaining cost sits. He defines instability as I = Ce / (Ca + Ce), where Ce counts outgoing and Ca incoming dependencies, and abstractness A as the share of abstract classes. Healthy packages lie near the line A + I = 1, the "main sequence". I counted at module level, which adapts his class-level definition, and treated Protocols as abstract:
The infrastructure, the composition root and the application layer sit on or near the line. The domain sits at the worst possible point: maximally stable, fully concrete, a distance of 0.71. Martin's metric is right to flag it. Everything depends on the domain, so a change to it ripples outwards, which is what happened in the second change above. The same article notes that volatility "depends upon market pressures and the whims of the customers." That is the kind of change the domain should absorb: business rules change for business reasons, and the structure makes sure nothing else changes them. The practical consequence is to keep the domain small and its public surface narrow, so that a change to a rule does not become a change to everything.
Enforcing the rule
Alistair Cockburn described the failure mode in his 2005 paper on ports and adapters: "having no mechanism to detect when a violation of that promise occurs, the organization finds a few years later that the new layer is cluttered with business logic". The erosion study above documents the same pattern across 73 papers. A layout described in a README tends not to survive deadlines; a check that fails the build does.
Each language offers a different mechanism, and I planted the same violations in each to see what they catch.
Python: import-linter
import-linter reads the import graph and checks contracts. "Layers contracts enforce a 'layered architecture', where higher layers may depend on lower layers, but not the other way around." Forbidden contracts keep named packages, such as a web framework or a database driver, out of the core. The lab uses three:
[importlinter]
root_package = registry
include_external_packages = True
[importlinter:contract:layers]
name = Dependencies point inwards
type = layers
layers =
registry.infrastructure
registry.bootstrap
registry.application
registry.domain
[importlinter:contract:frameworks]
name = The core imports no framework or driver
type = forbidden
source_modules =
registry.domain
registry.application
forbidden_modules =
fastapi
pydantic
sqlite3
[importlinter:contract:root]
name = The composition root imports no delivery framework
type = forbidden
source_modules =
registry.bootstrap
forbidden_modules =
fastapi
pydantic
With an adapter import planted in the domain and a sqlite3 import planted in a use case, lint-imports fails and shows each path, including the indirect one through which a port now reaches SQLite:
ββββββββββββββΆββ ββ βββββββ
ββ£β ββββββββ βββββββββββΆββββ β
ββ ββββ¦βββ¦β©βββββ ββ¦ββ©ββββββ¦βββ
ββββββ£ββββββββ£β ββ ββ¬β£ββββ ββββββ
ββ£β β£βββββββββββββββββββββββββββ£β
ββββ©β©β©β£βββ©βββ©βββββββββ©β©βββ©ββ©β©ββ©β
ββββΆββ β²
βββββββββββββββββββββββ
---------
Contracts
---------
Analyzed 21 files, 36 dependencies.
-----------------------------------
Dependencies point inwards BROKEN
The core imports no framework or driver BROKEN
Contracts: 0 kept, 2 broken.
----------------
Broken contracts
----------------
Dependencies point inwards
--------------------------
registry.domain is not allowed to import registry.infrastructure:
- registry.domain.model -> registry.infrastructure.sqlite (l.8)
The core imports no framework or driver
---------------------------------------
registry.application is not allowed to import sqlite3:
- registry.application.ports -> registry.domain.model (l.7)
registry.domain.model -> registry.infrastructure.sqlite (l.8)
registry.infrastructure.sqlite -> sqlite3 (l.5)
- registry.application.use_cases -> sqlite3 (l.4)
registry.domain is not allowed to import sqlite3:
- registry.domain.model -> registry.infrastructure.sqlite (l.8)
registry.infrastructure.sqlite -> sqlite3 (l.5)
exit 1
A test that needs no tool at all is also possible. The companion code of Keen's book walks the syntax tree of every domain module and fails on any import from an outer layer. That is a good start, with one limit: it sees direct imports only, while import-linter also reported the indirect chain above.
Two habits from the platform I mentioned are worth borrowing. The first is a ratchet for existing code: write the contracts, record today's violations in an ignore list, and fail the build both on any new violation and on any listed one that has been fixed. The list can only shrink, so you adopt the rule on the day you write it. The second is a test that imports each module first in a fresh interpreter. A normal test run imports modules in one order and hides cycles that only break when a process starts from a different entry point.
Rust: the crate graph
In Rust, put each layer in its own crate in one Cargo workspace, and the compiler enforces the direction. The domain crate's Cargo.toml lists no dependencies, so the domain cannot name the infrastructure crate at all:
error[E0432]: unresolved import `infrastructure`
--> domain/src/lib.rs:3:5
|
3 | use infrastructure::InMemoryModels; // planted violation
| ^^^^^^^^^^^^^^ use of unresolved module or unlinked crate `infrastructure`
|
= help: if you wanted to use a crate named `infrastructure`, use `cargo add infrastructure` to add it to your `Cargo.toml`
For more information about this error, try `rustc --explain E0432`.
error: could not compile `domain` (lib) due to 1 previous error
exit 101
Adding the dependency does not help, because the infrastructure crate already depends on the domain. Cargo's resolver "does not allow cycles in the graph", and refuses to build:
error: cyclic package dependency: package `application v0.1.0 (<lab>/application)` depends on itself. Cycle:
package `application v0.1.0 (<lab>/application)`
... which satisfies path dependency `application` (locked to 0.1.0) of package `infrastructure v0.1.0 (<lab>/infrastructure)`
... which satisfies path dependency `infrastructure` (locked to 0.1.0) of package `domain v0.1.0 (<lab>/domain)`
... which satisfies path dependency `domain` (locked to 0.1.0) of package `application v0.1.0 (<lab>/application)`
... which satisfies path dependency `application` (locked to 0.1.0) of package `app v0.1.0 (<lab>/app)`
exit 101
No extra tool, no CI step: the check runs on every build. Within a crate, items are private by default and pub(crate) keeps helpers out of the public surface, which is Parnas's information hiding as a language feature. The application crate holds the ports as traits and the use cases as one generic struct, so the adapters are resolved at compile time:
//! Ports (traits the outer crates implement) and use cases.
use std::collections::BTreeMap;
use domain::{ModelVersion, PromotionError, PromotionPolicy};
pub trait ModelRepository {
fn get(&self, name: &str, version: u32) -> Option<ModelVersion>;
fn champion(&self, name: &str) -> Option<ModelVersion>;
fn latest_version(&self, name: &str) -> u32;
fn save(&mut self, versions: &[&ModelVersion]);
}
pub trait Evaluator {
fn evaluate(&self, model: &ModelVersion, dataset: &str) -> BTreeMap<String, f64>;
}
#[derive(Debug, PartialEq)]
pub enum AppError { NotFound(String, u32), Rule(PromotionError) }
impl From<PromotionError> for AppError {
fn from(e: PromotionError) -> Self { AppError::Rule(e) }
}
/// The registry's use cases, generic over its adapters: resolved at compile time, no dynamic dispatch.
pub struct Registry<R: ModelRepository, E: Evaluator> { pub models: R, evaluator: E, policy: PromotionPolicy }
impl<R: ModelRepository, E: Evaluator> Registry<R, E> {
pub fn new(models: R, evaluator: E, policy: PromotionPolicy) -> Self { Self { models, evaluator, policy } }
pub fn register(&mut self, name: &str, trained_by: &str) -> ModelVersion {
let v = ModelVersion::new(name, self.models.latest_version(name) + 1, trained_by);
self.models.save(&[&v]);
v
}
pub fn evaluate(&mut self, name: &str, version: u32, dataset: &str) -> Result<ModelVersion, AppError> {
let mut m = self.load(name, version)?;
m.record(self.evaluator.evaluate(&m, dataset))?;
self.models.save(&[&m]);
Ok(m)
}
pub fn promote(&mut self, name: &str, version: u32, reviewer: &str) -> Result<ModelVersion, AppError> {
let mut candidate = self.load(name, version)?;
let mut champion = self.models.champion(name);
candidate.promote_over(champion.as_mut(), &self.policy, reviewer)?;
match &champion {
Some(c) => self.models.save(&[&candidate, c]),
None => self.models.save(&[&candidate]),
}
Ok(candidate)
}
fn load(&self, name: &str, version: u32) -> Result<ModelVersion, AppError> {
self.models.get(name, version).ok_or_else(|| AppError::NotFound(name.into(), version))
}
}
The domain returns business refusals as values of an enum inside Result. A caller cannot forget to handle one: a match that misses a case does not compile.
//! Model versions and the promotion rules. No I/O, no dependencies.
use std::collections::BTreeMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stage { Candidate, Champion, Retired }
/// Every way a promotion can be refused. A closed set: callers must handle each case.
#[derive(Debug, PartialEq)]
pub enum PromotionError {
WrongStage(Stage),
SelfReview,
NotEvaluated(String),
NotBetter { gain: f64, required: f64 },
}
pub struct PromotionPolicy { pub metric: String, pub min_gain: f64, pub higher_is_better: bool }
impl PromotionPolicy {
fn gain(&self, candidate: f64, champion: f64) -> f64 {
if self.higher_is_better { candidate - champion } else { champion - candidate }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ModelVersion {
pub name: String,
pub version: u32,
pub trained_by: String,
pub metrics: BTreeMap<String, f64>,
pub stage: Stage,
pub promoted_by: Option<String>,
}
impl ModelVersion {
pub fn new(name: &str, version: u32, trained_by: &str) -> Self {
Self { name: name.into(), version, trained_by: trained_by.into(), metrics: BTreeMap::new(),
stage: Stage::Candidate, promoted_by: None }
}
pub fn record(&mut self, metrics: BTreeMap<String, f64>) -> Result<(), PromotionError> {
if self.stage != Stage::Candidate { return Err(PromotionError::WrongStage(self.stage)); }
self.metrics.extend(metrics);
Ok(())
}
/// Become champion over `champion`, retiring it, if every rule allows it.
pub fn promote_over(&mut self, champion: Option<&mut ModelVersion>, policy: &PromotionPolicy,
reviewer: &str) -> Result<(), PromotionError> {
if self.stage != Stage::Candidate { return Err(PromotionError::WrongStage(self.stage)); }
if reviewer == self.trained_by { return Err(PromotionError::SelfReview); }
let score = *self.metrics.get(&policy.metric)
.ok_or_else(|| PromotionError::NotEvaluated(policy.metric.clone()))?;
if let Some(champ) = champion {
let gain = policy.gain(score, champ.metrics[&policy.metric]);
if gain < policy.min_gain {
return Err(PromotionError::NotBetter { gain, required: policy.min_gain });
}
champ.stage = Stage::Retired;
}
self.stage = Stage::Champion;
self.promoted_by = Some(reviewer.into());
Ok(())
}
}
TypeScript: dependency-cruiser
TypeScript has no crate boundary, so the rule needs a tool. dependency-cruiser checks forbidden paths between folders:
/** Dependencies point inwards: domain <- application <- infrastructure <- main. */
module.exports = {
forbidden: [
{ name: "domain-is-pure", severity: "error", comment: "The domain imports nothing outside itself.",
from: { path: "^src/domain" }, to: { path: "^src/(application|infrastructure|main)" } },
{ name: "application-uses-ports", severity: "error", comment: "Use cases never import adapters.",
from: { path: "^src/application" }, to: { path: "^src/(infrastructure|main)" } },
{ name: "no-cycles", severity: "error", from: {}, to: { circular: true } },
],
options: { tsConfig: { fileName: "tsconfig.json" }, tsPreCompilationDeps: true },
};
One option matters more than it looks. Ports and adapters often import only types, and type-only imports disappear when TypeScript compiles. Without tsPreCompilationDeps, dependency-cruiser checked 3 of the lab's 6 dependencies and reported no violations; with it, all 6. With the option on and violations planted, it reports every one, including the cycle the planted import creates:
error no-cycles: src/domain/model.ts β
src/infrastructure/memory.ts β
src/domain/model.ts
error domain-is-pure: src/domain/model.ts β src/infrastructure/memory.ts
error application-uses-ports: src/application/useCases.ts β src/infrastructure/memory.ts
x 3 dependency violations (3 errors, 0 warnings). 5 modules, 8 dependencies cruised.
exit 3
The domain models refusals as a discriminated union and returns them as values, so a caller must check ok before touching the result:
// Model versions and the promotion rules. No I/O, no framework.
export type Stage = "candidate" | "champion" | "retired";
// Every way a promotion can be refused, as a discriminated union the compiler can check for exhaustiveness.
export type PromotionError =
| { kind: "WrongStage"; stage: Stage }
| { kind: "SelfReview" }
| { kind: "NotEvaluated"; metric: string }
| { kind: "NotBetter"; gain: number; required: number };
export type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
const ok = <T>(value: T): Result<T, never> => ({ ok: true, value });
const fail = <E>(error: E): Result<never, E> => ({ ok: false, error });
export interface PromotionPolicy { metric: string; minGain: number; higherIsBetter: boolean }
export interface ModelVersion {
readonly name: string;
readonly version: number;
readonly trainedBy: string;
readonly metrics: Readonly<Record<string, number>>;
readonly stage: Stage;
readonly promotedBy: string | null;
}
export const newVersion = (name: string, version: number, trainedBy: string): ModelVersion =>
({ name, version, trainedBy, metrics: {}, stage: "candidate", promotedBy: null });
export function record(m: ModelVersion, metrics: Record<string, number>): Result<ModelVersion, PromotionError> {
if (m.stage !== "candidate") return fail({ kind: "WrongStage", stage: m.stage });
return ok({ ...m, metrics: { ...m.metrics, ...metrics } });
}
/** Returns the new champion and the retired one; values are immutable, so nothing changes on failure. */
export function promote(candidate: ModelVersion, champion: ModelVersion | null, policy: PromotionPolicy,
reviewer: string): Result<{ promoted: ModelVersion; retired: ModelVersion | null }, PromotionError> {
if (candidate.stage !== "candidate") return fail({ kind: "WrongStage", stage: candidate.stage });
if (reviewer === candidate.trainedBy) return fail({ kind: "SelfReview" });
const score = candidate.metrics[policy.metric];
if (score === undefined) return fail({ kind: "NotEvaluated", metric: policy.metric });
let retired: ModelVersion | null = null;
if (champion) {
const best = champion.metrics[policy.metric]!;
const gain = policy.higherIsBetter ? score - best : best - score;
if (gain < policy.minGain) return fail({ kind: "NotBetter", gain, required: policy.minGain });
retired = { ...champion, stage: "retired" };
}
return ok({ promoted: { ...candidate, stage: "champion", promotedBy: reviewer }, retired });
}
Fakes that drift
Python Protocols and TypeScript interfaces are structural. The TypeScript handbook: "Structural typing is a way of relating types based solely on their members." The in-memory fake never declares that it implements the port:
// In-memory adapter. Note: no `implements ModelRepository`; the shape is enough for the compiler.
import type { ModelVersion } from "../domain/model.ts";
export class InMemoryModels {
private rows = new Map<string, ModelVersion>();
async get(name: string, version: number) { return this.rows.get(`${name}@${version}`) ?? null; }
async champion(name: string) {
return [...this.rows.values()].find((m) => m.name === name && m.stage === "champion") ?? null;
}
async latestVersion(name: string) {
return Math.max(0, ...[...this.rows.values()].filter((m) => m.name === name).map((m) => m.version));
}
async save(...versions: ModelVersion[]) { for (const m of versions) this.rows.set(`${m.name}@${m.version}`, m); }
}
export const fixedScores = (scores: Record<string, Record<string, number>>) => ({
async evaluate(m: ModelVersion) { return scores[`${m.name}@${m.version}`] ?? {}; },
});
That makes fakes cheap, but it moves the error. Delete one method from the fake, and the type checker complains where the fake is passed in, not where it is defined:
src/main.ts(7,16): error TS2345: Argument of type 'InMemoryModels' is not assignable to parameter of type 'ModelRepository'.
Property 'latestVersion' is missing in type 'InMemoryModels' but required in type 'ModelRepository'.
exit 2
check_fake.py:4: error: Argument 1 to "RegisterVersion" has incompatible type "InMemoryModels"; expected "ModelRepository" [arg-type]
check_fake.py:4: note: "InMemoryModels" is missing following "ModelRepository" protocol member:
check_fake.py:4: note: latest_version
Found 1 error in 1 file (checked 1 source file)
exit 1
Rust traits are nominal: the same deletion fails at the impl block with error E0046, "not all trait items implemented". In all three, a type checker in CI catches a drifting fake; in Python only if mypy or a similar checker actually runs.
| Planted violation | Python | Rust | TypeScript |
|---|---|---|---|
| The domain imports an adapter | import-linter: contract BROKEN, exit 1 | rustc E0432, unresolved import, exit 101 | dependency-cruiser: domain-is-pure, exit 3 |
| A dependency cycle | Reported with the full import chain | Cargo: cyclic package dependency, exit 101 | no-cycles rule, exit 3 |
| A use case imports a driver or an adapter | forbidden contract on sqlite3, exit 1 | Impossible without a new dependency in Cargo.toml | application-uses-ports, exit 3 |
| A fake misses one method of its port | mypy: missing protocol member, exit 1 | rustc E0046, exit 101 | tsc TS2345, exit 2 |
Python, Rust and TypeScript side by side
The rule is the same in each language; the idioms are not. Do not copy one language's shape into another. Use each language's own tools for ports, errors and boundaries:
| Concept | Python | Rust | TypeScript |
|---|---|---|---|
| Port | typing.Protocol (by shape) or abc.ABC (by inheritance) | trait | interface (by shape) |
| How an adapter qualifies | Matches the shape, or subclasses the ABC | impl Trait for Type, always explicit | Matches the shape; implements is optional |
| Where a missing method is reported | Where the adapter is passed in (mypy) | At the impl (rustc E0046) | Where the adapter is passed in (tsc TS2345) |
| Business errors | An exception hierarchy | An enum inside Result<T, E> | A discriminated union returned as a value |
| Injection | Constructor arguments, wired in one bootstrap module | Generic parameters (static dispatch) or Box<dyn Trait> | Constructor or factory arguments |
| Boundary check | import-linter in CI | The crate graph: rustc and Cargo, on every build | dependency-cruiser or an ESLint plugin, in CI |
| Hiding details | Convention (_name) and contracts | Private by default, pub(crate) | Unexported names, #private fields |
In Python, the choice between Protocol and abc.ABC is a real one. PEP 544 defines protocols as structural: "subtyping with respect to a protocol is always structural." Adapters need no import of the port and fakes are trivial. Abstract base classes are nominal: an adapter must inherit from the port, which documents the relationship in code, and Python refuses to instantiate a subclass that misses an abstract method. The platform I mentioned used abstract base classes throughout, wired by hand in a small factory per bounded context, with no injection framework. Percival and Gregory make the same choice of "manual DI": "a pattern called Composition Root (a bootstrap script to you and me)".
How much structure do you need?
For most small services, less than the templates suggest; for code with real business rules, usually more than it has. Jeffrey Palermo was explicit about his own pattern: "This architecture is not appropriate for small websites. It is appropriate for long-lived business applications as well as applications with complex behavior." My rule of thumb is to scale the structure with two things: how long the code will live, and how much it costs when a rule is wrong.
| Situation | What I would use | Why |
|---|---|---|
| A script or a notebook that lives for days | One module | Nothing to protect yet. |
| A thin CRUD service over a database | The framework's defaults; separate files for routes and queries | Percival and Gregory: "you don't need a domain model or a repository". Fowler: "A small program may just put separate functions for the layers into different files." |
| A service with real rules (promotion, pricing, eligibility) | Domain, use cases, ports, a composition root, one layers contract | The rules get microsecond tests and one place to live. |
| Several entry points: HTTP, CLI, a queue worker, a workflow engine | The same, plus a framework-free composition root and thin adapters | Each entry point reuses the use cases instead of calling routes. |
| Many contexts and teams in one repository | Layers inside each context, independence contracts between contexts, a small shared kernel | Contexts can be tested and changed apart. |
| Existing code that breaks the rules | Contracts with a recorded list of current violations that may only shrink | You adopt the rule today and pay the debt down over time. |
Moving an existing codebase is a different job from starting a new one. These habits came from a Python platform that moved to this shape over several months, one bounded context at a time:
- Migrate one context at a time. Choose one well-structured context as the reference and copy its shape for new work. Leave a legacy context alone until it needs real change.
- Build inwards out. Write the domain and its tests first, then the use cases, then the adapters. Normalise foreign input at the edge, so a change in an upstream schema stops at the adapter.
- Map errors once, at the outermost layer. Keep the exception type intact through every wrapper, and decide in one function which errors are permanent and which are worth retrying. When a wrapper erased the type, permanent errors got retried.
- Keep workflow and queue handlers thin. A handler converts the wire format, calls exactly one use case and converts back. The workflow engine's library stays out of the domain and the application layer.
- Move shared code on the second copy. When a helper appears in a second context, move it to a small shared kernel and delete the copies.
- Delete what nothing calls. Some use cases written while sketching the first scaffold were never used. They were removed rather than kept "for later".
Mistakes to look for in review
| Mistake | Symptom | Fix |
|---|---|---|
| The composition root imports a framework | A CLI or worker loads the web stack | Keep wiring framework-free; add a forbidden contract |
| Rules live in use cases; entities are bags of fields | Use cases full of if statements about the business | Move each rule onto the entity it protects |
| An interface for everything | A port with one implementation and no fake | Add a port for a slow, external or swappable dependency, not for every class |
| ORM rows used as entities | Domain code imports the ORM; tests need a database | Map rows to domain objects in the adapter |
| Layers that only forward calls | Three classes in a row with the same method name | Merge them; a use case that does nothing is not a layer |
| Error mapping in many places | The same refusal returns 409 here and 500 there | One translation function per delivery mechanism, at the edge |
| Package files that re-export everything | Importing a small module pulls in heavy libraries | Import from the module that defines the name, or export lazily |
| Rules without checks | The structure erodes a little with every commit | Contracts in CI from the first day |
The second row is the hardest to spot, because it looks like success. Fowler: "The basic symptom of an Anemic Domain Model is that at first blush it looks like the real thing." The folders are right, the use cases exist, and every rule lives in a service while the entities only carry data. Architecture Patterns with Python makes the same point about its own pattern: "Putting too much logic into the service layer can lead to the Anemic Domain antipattern."
A checklist
- Can you test every business rule without a database, a web server or a network?
- Does the domain import anything outside the standard library? Name each exception.
- Does every entry point (HTTP, CLI, worker, workflow) call use cases rather than other entry points?
- Is there exactly one place per entry point that turns errors into status codes or retries?
- Does each port have a fake, and does one contract suite run against both the fake and the real adapter?
- Is the dependency rule checked on every build or every pull request?
- When a rule changes, can you name the files that will change before you open them?
Limits of this post
The lab is small: 238 lines of production code, three endpoints, four rules. At this size the flat version is perfectly readable, and the costs of layering show more clearly than its benefits; the benefits grow with the number of rules and entry points, which a lab this size cannot show. The timings come from one laptop, as medians of 100 to 5,000 runs, and they are meant for comparing levels with each other, not for quoting as absolutes. Martin's metrics were defined for classes in C++ packages, and counting Python modules is my adaptation. The research on coupling is correlational, and I found no study that measures Clean Architecture itself against an alternative. Treat this post as a careful argument with measurements, not as proof.
Sources and further reading
Where the ideas come from
- D. L. Parnas, On the Criteria To Be Used in Decomposing Systems into Modules, Communications of the ACM, 1972. Information hiding: modules built around the decisions likely to change.
- Robert C. Martin, The Dependency Inversion Principle (1996) and Stability, C++ Report columns, archived copies. Inversion, and the I, A and D metrics.
- Alistair Cockburn, Hexagonal architecture (2005). Ports and adapters, and why a layer needs a check.
- Jeffrey Palermo, The Onion Architecture, part 1 (2008). The same rule, and its limits for small sites.
- Robert C. Martin, The Clean Architecture (2012) and Screaming Architecture (2011). The Dependency Rule, and structure that names the use cases.
Books with code
- Harry Percival and Bob Gregory, Architecture Patterns with Python, free online. Read the chapters on the repository, the service layer and dependency injection, including their trade-off tables.
- Sam Keen, Clean Architecture with Python, Packt, and its code. Martin's four layers in Python, with architecture tests in chapter 10.
- Tom Hombergs, Get Your Hands Dirty on Clean Architecture. Ports and adapters in a Java and Spring codebase.
- Eric Evans, Domain-Driven Design. Modelling the domain itself, and bounded contexts.
- Sairyss, domain-driven-hexagon. A large TypeScript example of the same ideas.
Tools and language references
- PEP 544, Protocols and the import-linter contract types.
- The Cargo Book on workspaces and dependency resolution; the Rust Reference on visibility and privacy.
- The TypeScript Handbook on type compatibility; dependency-cruiser and eslint-plugin-boundaries.
Evidence on coupling and erosion
- Puppet and DORA, 2017 State of DevOps Report, and DORA on loosely coupled teams. Survey data on coupling between services and teams.
- MacCormack, Rusnak and Baldwin, Exploring the Structure of Complex Software Designs, working paper version of the 2006 Management Science article. Propagation cost, and the Mozilla redesign.
- Li, Liang, Soliman and Avgeriou, Understanding software architecture erosion: a systematic mapping study (2022). 73 studies.
- Oyetoyan, Cruzes and Conradi, Transition and defect patterns of components in dependency cycles (2014). Cycles and defects in four systems.
- Le, Karthik, Laser and MedvidoviΔ, Architectural Decay as Predictor of Issue- and Change-Proneness (2021). Ten open-source systems.
- Mo, Cai, Kazman, Xiao and Feng, Decoupling Level (2016). A metric for how well a design splits into replaceable modules.
- Sas, Avgeriou and Uyumaz, On the evolution and impact of architectural smells (2022). Nine industrial projects, with developer interviews.
Limits and critiques
- Martin Fowler, Presentation Domain Data Layering and Anemic Domain Model. Why to layer, at what granularity, and the most common failure.