Clean Architecture + DDD + Hexagonal
Backend architecture combining DDD tactical patterns, Clean Architecture dependency rules, and Hexagonal ports/adapters for maintainable, testable systems.
When to Use (and When NOT to)
| Use When |
Skip When |
| Complex business domain with many rules |
Simple CRUD, few business rules |
| Long-lived system (years of maintenance) |
Prototype, MVP, throwaway code |
| Team of 5+ developers |
Solo developer or small team (1-2) |
| Multiple entry points (API, CLI, events) |
Single entry point, simple API |
| Need to swap infrastructure (DB, broker) |
Fixed infrastructure, unlikely to change |
| High test coverage required |
Quick scripts, internal tools |
Start simple. Evolve complexity only when needed. Most systems don't need full CQRS or Event Sourcing.
CRITICAL: The Dependency Rule
Dependencies point inward only. Outer layers depend on inner layers, never the reverse.
Infrastructure → Application → Domain
(adapters) (use cases) (core)
Violations to catch:
- Domain importing database/HTTP libraries
- Controllers calling repositories directly (bypassing use cases)
- Entities depending on application services
Design validation: "Create your application to work without either a UI or a database" — Alistair Cockburn. If you can run your domain logic from tests with no infrastructure, your boundaries are correct.
Quick Decision Trees
"Where does this code go?"
Where does it go?
├─ Pure business logic, no I/O → domain/
├─ Orchestrates domain + has side effects → application/
├─ Talks to external systems → infrastructure/
├─ Defines HOW to interact (interface) → port (domain or application)
└─ Implements a port → adapter (infrastructure)
"Is this an Entity or Value Object?"
Entity or Value Object?
├─ Has unique identity that persists → Entity
├─ Defined only by its attributes → Value Object
├─ "Is this THE same thing?" → Entity (identity comparison)
└─ "Does this have the same value?" → Value Object (structural equality)
"Should this be its own Aggregate?"
Aggregate boundaries?
├─ Must be consistent together in a transaction → Same aggregate
├─ Can be eventually consistent → Separate aggregates
├─ Referenced by ID only → Separate aggregates
└─ >10 entities in aggregate → Split it
Rule: One aggregate per transaction. Cross-aggregate consistency via domain events (eventual consistency).
Directory Structure
src/
├── domain/ # Core business logic (NO external dependencies)
│ ├── {aggregate}/
│ │ ├── entity # Aggregate root + child entities
│ │ ├── value_objects # Immutable value types
│ │ ├── events # Domain events
│ │ ├── repository # Repository interface (DRIVEN PORT)
│ │ └── services # Domain services (stateless logic)
│ └── shared/
│ └── errors # Domain errors
├── application/ # Use cases / Application services
│ ├── {use-case}/
│ │ ├── command # Command/Query DTOs
│ │ ├── handler # Use case implementation
│ │ └── port # Driver port interface
│ └── shared/
│ └── unit_of_work # Transaction abstraction
├── infrastructure/ # Adapters (external concerns)
│ ├── persistence/ # Database adapters
│ ├── messaging/ # Message broker adapters
│ ├── http/ # REST/GraphQL adapters (DRIVER)
│ └── config/
│ └── di # Dependency injection / composition root
└── main # Bootstrap / entry point
DDD Building Blocks
| Pattern |
Purpose |
Layer |
Key Rule |
| Entity |
Identity + behavior |
Domain |
Equality by ID |
| Value Object |
Immutable data |
Domain |
Equality by value, no setters |
| Aggregate |
Consistency boundary |
Domain |
Only root is referenced externally |
| Domain Event |
Record of change |
Domain |
Past tense naming (OrderPlaced) |
| Repository |
Persistence abstraction |
Domain (port) |
Per aggregate, not per table |
| Domain Service |
Stateless logic |
Domain |
When logic doesn't fit an entity |
| Application Service |
Orchestration |
Application |
Coordinates domain + infra |
Anti-Patterns (CRITICAL)
| Anti-Pattern |
Problem |
Fix |
| Anemic Domain Model |
Entities are data bags, logic in services |
Move behavior INTO entities |
| Repository per Entity |
Breaks aggregate boundaries |
One repository per AGGREGATE |
| Leaking Infrastructure |
Domain imports DB/HTTP libs |
Domain has ZERO external deps |
| God Aggregate |
Too many entities, slow transactions |
Split into smaller aggregates |
| Skipping Ports |
Controllers → Repositories directly |
Always go through application layer |
| CRUD Thinking |
Modeling data, not behavior |
Model business operations |
| Premature CQRS |
Adding complexity before needed |
Start with simple read/write, evolve |
| Cross-Aggregate TX |
Multiple aggregates in one transaction |
Use domain events for consistency |
Implementation Order
- Discover the Domain — Event Storming, conversations with domain experts
- Model the Domain — Entities, value objects, aggregates (no infra)
- Define Ports — Repository interfaces, external service interfaces
- Implement Use Cases — Application services coordinating domain
- Add Adapters last — HTTP, database, messaging implementations
DDD is collaborative. Modeling sessions with domain experts are as important as the code patterns.
Reference Documentation
| File |
Purpose |
| references/LAYERS.md |
Complete layer specifications |
| references/DDD-STRATEGIC.md |
Bounded contexts, context mapping |
| references/DDD-TACTICAL.md |
Entities, value objects, aggregates (pseudocode) |
| references/HEXAGONAL.md |
Ports, adapters, naming |
| references/CQRS-EVENTS.md |
Command/query separation, events |
| references/TESTING.md |
Unit, integration, architecture tests |
| references/CHEATSHEET.md |
Quick decision guide |
Sources
Primary Sources
Pattern References
Implementation Guides
1---2name: clean-ddd-hexagonal3description: Apply Clean Architecture + DDD + Hexagonal patterns to backend services. Use when designing APIs, microservices, domain models, aggregates, repositories, bounded contexts, or scalable backend structure. Triggers on DDD, Clean Architecture, Hexagonal, ports and adapters, entities, value objects, domain events, CQRS, event sourcing, repository pattern, use cases, onion architecture, outbox pattern, aggregate root, anti-corruption layer. Language-agnostic (Go, Rust, Python, TypeScript, Java, C#).4---5
6# Clean Architecture + DDD + Hexagonal
7
8Backend architecture combining DDD tactical patterns, Clean Architecture dependency rules, and Hexagonal ports/adapters for maintainable, testable systems.
9
10## When to Use (and When NOT to)
11
12| Use When | Skip When |
13|----------|-----------|
14| Complex business domain with many rules | Simple CRUD, few business rules |
15| Long-lived system (years of maintenance) | Prototype, MVP, throwaway code |
16| Team of 5+ developers | Solo developer or small team (1-2) |
17| Multiple entry points (API, CLI, events) | Single entry point, simple API |
18| Need to swap infrastructure (DB, broker) | Fixed infrastructure, unlikely to change |
19| High test coverage required | Quick scripts, internal tools |
20
21**Start simple. Evolve complexity only when needed.** Most systems don't need full CQRS or Event Sourcing.
22
23## CRITICAL: The Dependency Rule
24
25Dependencies point **inward only**. Outer layers depend on inner layers, never the reverse.
26
27```
28Infrastructure → Application → Domain
29 (adapters) (use cases) (core)
30```
31
32**Violations to catch:**
33- Domain importing database/HTTP libraries
34- Controllers calling repositories directly (bypassing use cases)
35- Entities depending on application services
36
37**Design validation:** "Create your application to work without either a UI or a database" — Alistair Cockburn. If you can run your domain logic from tests with no infrastructure, your boundaries are correct.
38
39## Quick Decision Trees
40
41### "Where does this code go?"
42
43```
44Where does it go?
45├─ Pure business logic, no I/O → domain/
46├─ Orchestrates domain + has side effects → application/
47├─ Talks to external systems → infrastructure/
48├─ Defines HOW to interact (interface) → port (domain or application)
49└─ Implements a port → adapter (infrastructure)
50```
51
52### "Is this an Entity or Value Object?"
53
54```
55Entity or Value Object?
56├─ Has unique identity that persists → Entity
57├─ Defined only by its attributes → Value Object
58├─ "Is this THE same thing?" → Entity (identity comparison)
59└─ "Does this have the same value?" → Value Object (structural equality)
60```
61
62### "Should this be its own Aggregate?"
63
64```
65Aggregate boundaries?
66├─ Must be consistent together in a transaction → Same aggregate
67├─ Can be eventually consistent → Separate aggregates
68├─ Referenced by ID only → Separate aggregates
69└─ >10 entities in aggregate → Split it
70```
71
72**Rule:** One aggregate per transaction. Cross-aggregate consistency via domain events (eventual consistency).
73
74## Directory Structure
75
76```
77src/
78├── domain/ # Core business logic (NO external dependencies)
79│ ├── {aggregate}/
80│ │ ├── entity # Aggregate root + child entities
81│ │ ├── value_objects # Immutable value types
82│ │ ├── events # Domain events
83│ │ ├── repository # Repository interface (DRIVEN PORT)
84│ │ └── services # Domain services (stateless logic)
85│ └── shared/
86│ └── errors # Domain errors
87├── application/ # Use cases / Application services
88│ ├── {use-case}/
89│ │ ├── command # Command/Query DTOs
90│ │ ├── handler # Use case implementation
91│ │ └── port # Driver port interface
92│ └── shared/
93│ └── unit_of_work # Transaction abstraction
94├── infrastructure/ # Adapters (external concerns)
95│ ├── persistence/ # Database adapters
96│ ├── messaging/ # Message broker adapters
97│ ├── http/ # REST/GraphQL adapters (DRIVER)
98│ └── config/
99│ └── di # Dependency injection / composition root
100└── main # Bootstrap / entry point
101```
102
103## DDD Building Blocks
104
105| Pattern | Purpose | Layer | Key Rule |
106|---------|---------|-------|----------|
107| **Entity** | Identity + behavior | Domain | Equality by ID |
108| **Value Object** | Immutable data | Domain | Equality by value, no setters |
109| **Aggregate** | Consistency boundary | Domain | Only root is referenced externally |
110| **Domain Event** | Record of change | Domain | Past tense naming (`OrderPlaced`) |
111| **Repository** | Persistence abstraction | Domain (port) | Per aggregate, not per table |
112| **Domain Service** | Stateless logic | Domain | When logic doesn't fit an entity |
113| **Application Service** | Orchestration | Application | Coordinates domain + infra |
114
115## Anti-Patterns (CRITICAL)
116
117| Anti-Pattern | Problem | Fix |
118|--------------|---------|-----|
119| **Anemic Domain Model** | Entities are data bags, logic in services | Move behavior INTO entities |
120| **Repository per Entity** | Breaks aggregate boundaries | One repository per AGGREGATE |
121| **Leaking Infrastructure** | Domain imports DB/HTTP libs | Domain has ZERO external deps |
122| **God Aggregate** | Too many entities, slow transactions | Split into smaller aggregates |
123| **Skipping Ports** | Controllers → Repositories directly | Always go through application layer |
124| **CRUD Thinking** | Modeling data, not behavior | Model business operations |
125| **Premature CQRS** | Adding complexity before needed | Start with simple read/write, evolve |
126| **Cross-Aggregate TX** | Multiple aggregates in one transaction | Use domain events for consistency |
127
128## Implementation Order
129
1301. **Discover the Domain** — Event Storming, conversations with domain experts
1312. **Model the Domain** — Entities, value objects, aggregates (no infra)
1323. **Define Ports** — Repository interfaces, external service interfaces
1334. **Implement Use Cases** — Application services coordinating domain
1345. **Add Adapters last** — HTTP, database, messaging implementations
135
136**DDD is collaborative.** Modeling sessions with domain experts are as important as the code patterns.
137
138## Reference Documentation
139
140| File | Purpose |
141|------|---------|
142| [references/LAYERS.md](references/LAYERS.md) | Complete layer specifications |
143| [references/DDD-STRATEGIC.md](references/DDD-STRATEGIC.md) | Bounded contexts, context mapping |
144| [references/DDD-TACTICAL.md](references/DDD-TACTICAL.md) | Entities, value objects, aggregates (pseudocode) |
145| [references/HEXAGONAL.md](references/HEXAGONAL.md) | Ports, adapters, naming |
146| [references/CQRS-EVENTS.md](references/CQRS-EVENTS.md) | Command/query separation, events |
147| [references/TESTING.md](references/TESTING.md) | Unit, integration, architecture tests |
148| [references/CHEATSHEET.md](references/CHEATSHEET.md) | Quick decision guide |
149
150## Sources
151
152### Primary Sources
153- [The Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) — Robert C. Martin (2012)
154- [Hexagonal Architecture](https://alistair.cockburn.us/hexagonal-architecture/) — Alistair Cockburn (2005)
155- [Domain-Driven Design: The Blue Book](https://www.domainlanguage.com/ddd/blue-book/) — Eric Evans (2003)
156- [Implementing Domain-Driven Design](https://openlibrary.org/works/OL17392277W) — Vaughn Vernon (2013)
157
158### Pattern References
159- [CQRS](https://martinfowler.com/bliki/CQRS.html) — Martin Fowler
160- [Event Sourcing](https://martinfowler.com/eaaDev/EventSourcing.html) — Martin Fowler
161- [Repository Pattern](https://martinfowler.com/eaaCatalog/repository.html) — Martin Fowler (PoEAA)
162- [Unit of Work](https://martinfowler.com/eaaCatalog/unitOfWork.html) — Martin Fowler (PoEAA)
163- [Bounded Context](https://martinfowler.com/bliki/BoundedContext.html) — Martin Fowler
164- [Transactional Outbox](https://microservices.io/patterns/data/transactional-outbox.html) — microservices.io
165- [Effective Aggregate Design](https://www.dddcommunity.org/library/vernon_2011/) — Vaughn Vernon
166
167### Implementation Guides
168- [Microsoft: DDD + CQRS Microservices](https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/)
169- [Domain Events](https://udidahan.com/2009/06/14/domain-events-salvation/) — Udi Dahan