When I first tried to implement Clean Architecture on a real project, I made almost every mistake the diagrams warn you about. I created four strict layers, added interfaces for everything, and ended up with a codebase that was harder to change than the layered MVC app it replaced. The diagrams from Robert Martin's original posts look deceptively simple — concentric circles with the dependency rule pointing inward — but they don't tell you where to put validation, how to handle transactions, or when an abstraction is actually hurting you. After applying these ideas across several Python and TypeScript systems over the last six years, I've learned that the value isn't in the ceremony. It's in the handful of constraints that keep business logic isolated when frameworks, databases, and delivery mechanisms inevitably change.
This article covers what those constraints look like in production code: how I define ports, where I draw adapter boundaries, how I keep use cases honest, and where I intentionally relax the rules. If you are familiar with dependency inversion and hexagonal architecture but have struggled to translate the theory into a maintainable folder structure, this is the practical gap that theory rarely addresses.
Why Your Framework Is Not Your Architecture: Inverting the Dependency Direction
The single most important idea in Clean Architecture is embarrassingly simple to state and surprisingly hard to enforce: source code dependencies must point inward, toward higher-level policy. Your web framework, your ORM, and your message broker are details. Your domain rules are not. In practice, this means your core entities and use cases should have no import statements that reference Flask, Django, Express, SQLAlchemy, or any other delivery infrastructure.
In my experience, the violation happens gradually. You start with a pure domain model, then someone imports an ORM base class directly into an entity to get persistence for free, or a use case accepts an HTTP request object as a parameter because it's convenient. Suddenly your business logic cannot be instantiated without bootstrapping the entire framework. I've found that a simple litmus test catches most of these slips during code review: can you import and exercise your domain and use case modules in a plain REPL without installing framework dependencies? If not, the dependency direction has flipped.
Dependency inversion is the mechanism that makes this possible. Instead of the domain depending on the database, both depend on an abstraction owned by the domain. The classic example is a repository interface. The domain defines what it needs — find_by_id, save — and the infrastructure layer provides an implementation that talks to Postgres or DynamoDB. The domain never knows which one.
Owning Abstractions Inside the Domain
A common error is to place port interfaces in the infrastructure layer. If the interface lives next to the SQLAlchemy implementation, the domain still indirectly depends on infrastructure concerns, and you have just moved the problem one file over. Ports belong to the application and domain layers. They express the language of the business, not the language of the technology. A method named execute_sql is not a port; reserve_inventory is.
I keep a strict rule: any module inside core/domain or core/application may only import from the standard library, other core modules, or explicit typing utilities. Tooling helps enforce this. In Python projects, I use import-linter to forbid imports from infrastructure.* into core.*, and in TypeScript I enforce it with ESLint boundaries. Without automated checks, entropy wins within a few sprints.
Mapping Ports and Adapters to Real Code Boundaries
Hexagonal architecture, which Alistair Cockburn originally described and which forms the basis for what many teams call clean architecture, gives you a more useful mental model than concentric circles when you are deciding where code lives. Think of your application as a hexagon with ports (interfaces) on its edges and adapters (implementations) outside. The term Domain-Driven Design: Bounded Contexts and Aggregate Roots Explained often comes up here for good reason — the shape of your ports should follow the boundaries of your bounded contexts, not the tables in your database.
In a typical service I structure the repository like this:
src/
core/
domain/
order.py # Entities, value objects, domain services
money.py # Value object, no framework imports
application/
ports/
order_repository.py # Interfaces (abstract base classes / Protocols)
payment_gateway.py
use_cases/
place_order.py # Application service orchestrating domain
infrastructure/
persistence/
sql_order_repository.py # Adapter for OrderRepository port
payments/
stripe_gateway.py # Adapter for PaymentGateway port
web/
fastapi_order_controller.py # Driving adapter (inbound)
composition/
container.py # Wires adapters to ports at startup
Notice that both driving adapters (HTTP controllers, CLI handlers, queue consumers) and driven adapters (database repositories, email senders) sit in infrastructure. They are details that plug into the hexagon. The composition root is the only place that knows about both sides and wires them together. This keeps framework bootstrapping — route registration, ORM session creation, environment variable reading — out of your use cases entirely.
Defining Ports With Protocols, Not Base Classes
For ports, I prefer structural typing where the language supports it. In Python, typing.Protocol as described in the Python Documentation lets me define an interface without forcing adapters to inherit from an abstract class defined in the core. This reduces coupling and avoids the classic diamond of abstract base classes that belong to no one. The port describes behavior, and any object that implements that behavior is acceptable.
from typing import Protocol, Optional
from core.domain.order import Order, OrderId
class OrderRepository(Protocol):
def next_identity(self) -> OrderId:
...
def find_by_id(self, order_id: OrderId) -> Optional[Order]:
...
def save(self, order: Order) -> None:
...
class PaymentGateway(Protocol):
def authorize(self, order: Order, amount_cents: int) -> str:
"""Returns an authorization code or raises PaymentDeclined."""
...
Because these protocols live in core/application/ports, an adapter in infrastructure/persistence/sql_order_repository.py can implement them without the core ever importing SQLAlchemy. The adapter imports the port, not the other way around. If you are working in TypeScript, an interface in the application layer and a class implementing it in the infrastructure layer achieves the same isolation.
Structuring Use Cases Without Turning Them Into Anemic Services
Use cases, sometimes called interactors or application services, orchestrate domain logic; they should not contain it. I have seen codebases where use cases become 300-line transaction scripts full of if-statements and calculations, while domain entities are little more than data bags with getters. That is the opposite of the goal.
A well-formed use case has a single public method, takes a plain input DTO, and returns a plain output DTO. It coordinates three things: fetching aggregates via ports, asking the domain to perform the business decision, and persisting side effects. All conditional logic that represents a business rule belongs on the entity or domain service instead.
from dataclasses import dataclass
from core.application.ports.order_repository import OrderRepository
from core.application.ports.payment_gateway import PaymentGateway
from core.domain.order import Order
@dataclass(frozen=True)
class PlaceOrderInput:
customer_id: str
line_items: list[dict]
idempotency_key: str
@dataclass(frozen=True)
class PlaceOrderOutput:
order_id: str
total_cents: int
class PlaceOrderUseCase:
def __init__(self, orders: OrderRepository, payments: PaymentGateway):
self._orders = orders
self._payments = payments
def execute(self, inp: PlaceOrderInput) -> PlaceOrderOutput:
order = Order.create(
order_id=self._orders.next_identity(),
customer_id=inp.customer_id,
line_items=inp.line_items,
)
# Domain enforces invariants: totals, stock, discounts
order.validate_or_raise()
auth_code = self._payments.authorize(order, order.total.cents)
order.mark_as_authorized(auth_code)
self._orders.save(order)
return PlaceOrderOutput(order_id=order.id.value, total_cents=order.total.cents)
Several details here are deliberate. The use case has no decorator for transactions or logging. Those are cross-cutting concerns applied by decorators or middleware outside the hexagon. It does not return an ORM object or an HTTP response. It returns a simple output structure. And it does not catch and swallow domain exceptions — PaymentDeclined or DomainValidationError propagate to the controller, which translates them into the appropriate status codes. This keeps the flow of control explicit and preserves the ability to test the use case without standing up HTTP.
Input and Output Boundaries Matter
I always define explicit input and output boundaries for use cases rather than passing domain entities directly to controllers. Controllers convert HTTP payloads to input DTOs, and convert output DTOs to HTTP responses. This prevents web details from leaking inward. For example, pagination parameters, user agent strings, and header-based feature flags should be interpreted at the adapter level and mapped to domain-meaningful fields before calling execute. The same principle applies on the way out: formatting money as "$12.34" is a presentation concern that does not belong in the domain.
Persistence Ignorance: Keeping Infrastructure at the Edges
The database is the detail most likely to contaminate your domain. ORMs are powerful, but an entity that inherits from an ORM base class carries persistence annotations, lazy-loading behavior, and session management into every test. I've found that the cleanest way to avoid this is to maintain two parallel models for a short translation distance: a pure domain entity and a persistence model that is aware of tables, columns, and indexes. The repository adapter maps between them.
This does create duplication, and I used to resist it for that reason. After maintaining systems where the domain model was forced to mirror a relational schema, however, I now consider the duplication a feature. Your domain evolves according to business rules; your schema evolves according to query patterns and migration constraints. Forcing them to be the same object means every change to one forces a change to the other.
A typical repository implementation reads an ORM record, converts it into a domain aggregate with all invariants re-established, and on save does the reverse. Importantly, the conversion validates that stored data still satisfies current domain invariants — if it doesn't, that indicates a migration gap rather than a reason to weaken the domain.
For browser-based clients, the same edge applies. When fetching data from an API, I treat fetch as a driven adapter and wrap it behind a port as documented in the MDN Web Docs Fetch API guide. The domain never calls fetch directly; the adapter does and translates the JSON response into domain types.
Handling Transactions and Unit of Work
Use cases often need to coordinate multiple ports within a single atomic operation — saving an order and publishing an integration event, for example. Rather than injecting a database session into the use case, I expose a Unit of Work port. The infrastructure adapter implements it with the actual transaction mechanism, and the composition root supplies it. The use case expresses the intent — "this should be atomic" — without knowing how atomicity is achieved. This also maps cleanly to Event-Driven Architecture: Commands, Events and Sagas where an outbox pattern is used to guarantee delivery of domain events.
Testing Strategy When the Domain Sits at the Center
Once dependencies point inward, your testing pyramid inverts in a helpful way. The fastest, most valuable tests become pure domain tests that require no mocks for infrastructure at all. Entities and value objects are just classes with methods; you instantiate them, call behavior, and assert outcomes. These tests run in milliseconds and document business rules better than any wiki page.
Use case tests sit one ring out. They verify orchestration by substituting in-memory fakes for ports. I avoid mocking frameworks here in favor of handwritten fakes that actually store state — a FakeOrderRepository that holds aggregates in a dictionary behaves more realistically than a mock that returns canned values. This style catches sequencing errors, like forgetting to save after a state transition, which strict mocks often hide.
Infrastructure adapters get thin integration tests that exercise the real technology against a test double of the external system — a temporary Postgres database, a WireMock server for payments — but these tests are fewer and intentionally slower. The goal is not to achieve 100% coverage through integration tests; it is to prove that the adapter correctly implements its port contract. If domain and use case tests already cover the rules, the adapter only needs to prove translation fidelity.
| Layer | Primary Test Type | Dependencies Required | Speed & Frequency |
|---|---|---|---|
| Domain (entities, value objects) | Unit tests, no doubles | None | Milliseconds, run on every save |
| Application (use cases) | Unit tests with in-memory fakes | Fake port implementations | Milliseconds, run on every commit |
| Infrastructure (adapters) | Integration / contract tests | Real DB, HTTP, queue | Seconds, run in CI pipeline |
| Composition Root | Smoke / end-to-end tests | Full wired system | Seconds to minutes, run pre-merge |
This separation also makes refactoring safer. When I rename a column or change a payment provider, only adapter tests and fakes need to change; domain tests remain untouched. Conversely, when a business rule changes, domain tests fail immediately at the center without needing to run the entire system.
Where Clean Architecture Strains and How I Compromise Pragmatically
Clean Architecture is not a good fit for every project. For a simple CRUD service with almost no business rules, the indirection of ports, use cases, and mappers adds overhead without corresponding value. In those cases a straightforward layered approach or even an active-record style is more economical. I also avoid applying the pattern uniformly to every feature in a larger system; I tend to isolate it to the bounded contexts where domain complexity is high and leave peripheral contexts more lightweight. That decision often intersects with broader structuring choices, which is why I point teams to Microservices vs Monolith: A Decision Framework for Teams before deciding how much isolation a context actually needs.
Even within a core context, there are practical compromises I have learned to make deliberately rather than accidentally.
Allowing Queries to Bypass the Domain
The most common strain is read performance. Rehydrating full aggregates to render a list screen or an export is wasteful when the query requires joins, projections, or denormalized views. Following Command Query Responsibility Segregation (CQRS) in a lightweight form, I let query handlers call a dedicated read port that returns purpose-built DTOs directly from the persistence layer, skipping the domain entirely. Commands — writes that change state — always go through the domain and enforce invariants; queries take a leaner path. This hybrid preserves the protective benefits where they matter most without sacrificing read efficiency.
When Not to Abstract
Not every external dependency deserves a port. If your application will realistically only ever use one implementation — say, system-clock time or a UUID generator — introducing an interface for it adds ceremony. I still isolate it behind a tiny function type rather than scattering datetime.utcnow() calls, but I do not always create a full adapter class until a second implementation appears. Similarly, validation that is purely syntactic (is this a well-formed email?) can live at the controller boundary; only semantic validation (is this customer eligible for this discount?) belongs to the domain.
The principle I follow is to abstract at the seam where you need to substitute behavior for testing or for future variation, not at every seam that exists. The dependency rule remains useful even when you don't formalize every port as an interface — the discipline of not letting infrastructure import into the domain is more important than the number of protocols you define.
Frequently Asked Questions
Is Clean Architecture the same as Hexagonal or Ports and Adapters?
They share the same core idea — isolate the domain at the center and depend on abstractions rather than details — but differ in emphasis. Hexagonal architecture, or ports and adapters, describes the pattern of ports (interfaces owned by the application) and adapters (implementations outside). Clean Architecture organizes that idea into concentric circles with an explicit dependency rule and distinguishes entities, use cases, and interface adapters. In practice I use the terms interchangeably and focus on dependency direction rather than which diagram variant I am drawing.
How do you handle cross-cutting concerns like logging, metrics, and transactions?
I keep them outside the use case. The use case expresses what should happen; infrastructure decides how it is observed and wrapped. In Python I often implement a decorator at the adapter or composition level that opens a transaction around a use case execution, logs entry and exit, and increments metrics. The domain and use case code remains unaware, which preserves testability. If a concern requires domain knowledge — for example audit logging that must capture the business reason for a change — I model it as an explicit domain event published through a port instead.
Doesn't maintaining separate domain and persistence models create a lot of mapping code?
It does add translation code, usually in the repository adapter. In my experience the cost is modest compared to the cost of coupling your entities to your schema. The mapper is typically 20-40 lines per aggregate, highly testable, and rarely changes unless the schema or business rules do. To reduce boilerplate I use simple factory methods on the domain entity — for example Order.from_state() — rather than introducing a generic mapper library that hides the conversion logic. The explicitness pays off when invariants evolve.
When should my team not adopt Clean Architecture?
If your service is primarily CRUD with little conditional logic, or if you are building a prototype where delivery speed matters more than long-term isolation, the added indirection may not justify itself. I also delay introducing ports and use cases until I see actual domain complexity or clear variation in driven adapters — such as needing to support two payment providers. Start with a modular monolith with clear module boundaries; extract ports where friction appears rather than abstracting everything upfront.