Lesson 1 of 9 · 24m
Layered Architecture Without the Lies
Use layers to control dependency direction and change, not as a ceremonial folder structure that hides coupling.
Every team I have rescued said they had a layered architecture. Most had four folders and one giant dependency blob. A layer is not a directory named services; it is a promise about which direction knowledge may flow. When that promise is real, you can replace a web framework, swap persistence, or test a business rule without booting half the internet.
The dependency rule matters more than the diagram
Classic layered systems separate presentation, application, domain, and infrastructure. The rule is simple: outer layers may depend inward, inner layers must not depend outward.
HTTP controllers -> application services -> domain model
| | |
request DTOs use cases business rules
| |
serializers repositories are interfaces hereThe database adapter belongs outside the domain. If Invoice imports SQLAlchemy, Django ORM, or an HTTP client, the arrow points the wrong way and the layer is decorative.
Separate workflow from policy
Application services coordinate a use case: load objects, invoke domain behavior, save results, publish notifications. Domain objects enforce invariants. Do not blur them.
class TransferMoney:
def __init__(self, accounts, transfers, clock):
self.accounts = accounts
self.transfers = transfers
self.clock = clock
def execute(self, source_id: str, target_id: str, amount: Money) -> Transfer:
source = self.accounts.get_for_update(source_id)
target = self.accounts.get_for_update(target_id)
transfer = source.transfer_to(target, amount, occurred_at=self.clock.now())
self.accounts.save(source)
self.accounts.save(target)
self.transfers.record(transfer)
return transferThe use case knows the sequence. It does not know SQL, JSON, HTTP status codes, or message broker topics. That isolation is the payoff.
Thin controllers are a diagnostic, not a goal
A controller should translate transport into application input and translate the result back. If it contains branching business policy, the domain is leaking upward. If it is empty because all rules live in stored procedures, the domain is leaking downward.
@router.post("/transfers", status_code=201)
def create_transfer(request: TransferRequest, service: TransferMoney = Depends()):
try:
transfer = service.execute(request.source_id, request.target_id, request.amount)
except InsufficientFunds as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
return TransferResponse.from_domain(transfer)Do not worship thinness. Some validation is transport validation: malformed JSON, impossible types, missing required fields. Business validation belongs deeper.
Where layered systems rot
The usual failure is the "service layer" becoming a junk drawer: static helpers, transaction scripts, cache calls, permission checks, email sending, and ORM queries all in one file. The second failure is anemic objects: every setter public, every invariant enforced by whoever remembers. The third is test-driven erosion: because unit tests are hard, developers mock the application layer and test only controllers, hiding the missing boundary.
A practical smell test
Ask three questions. Can I execute the use case in a plain Python test without a web server? Can I change database schema without editing business rules? Can I explain what each layer is forbidden to know? If any answer is no, the architecture is not layered; it is merely sorted.
Field notes
- Transaction boundaries usually belong at the application-service edge, not inside every repository method.
- DTOs exist to protect boundaries; do not reuse the same object for request, persistence, queue payload, and API response.
- Circular imports are architecture feedback. Do not silence them with import tricks; redraw the dependency.
- A layer that exists only to pass calls through is tax. Remove it or give it a real responsibility.
- Framework annotations are not automatically evil, but scattering them through domain classes makes migration expensive.
Was this lesson helpful?