Hexagonal Architecture: Beyond Traditional Layers (and Organized Chaos)
๐ฏ Introduction: Separating Business from the Tech Circus
Hexagonal Architecture โ also known as Ports and Adapters โ is not just another fancy way of saying "layers". It represents a shift in how we structure applications that must survive years, multiple frameworks, and several architectural "refactors of faith".
Proposed by Alistair Cockburn, it tackles a recurring issue: business logic polluted by infrastructure concerns such as controllers, ORMs, SDKs, message brokers, and databases.
Typical problem in classical architectures
- Controllers mixing validation, SQL and business rules.
- Use cases coupled to specific frameworks.
- Tests that require half your infrastructure stack to run.
- Refactors scarier than deleting production logs.
๐๏ธ Fundamental Concepts
- Domain: Business rules, framework-agnostic.
- Ports: Contracts defining what the system needs or exposes.
- Adapters: Implementations that connect to the outside world.
โก Practical Implementation: Order Management System
src/
โโโ domain/
โ โโโ entities/
โ โโโ value-objects/
โ โโโ repositories/
โ โโโ services/
โโโ application/
โ โโโ use-cases/
โ โโโ ports/
โ โโโ dtos/
โโโ infrastructure/
โ โโโ web/
โ โโโ persistence/
โ โโโ messaging/
โโโ main.ts
๐ง Domain Layer
The domain holds the intelligence. Rules are self-contained and resilient.
๐งฉ Value Objects
Encapsulate validation and immutability for atomic concepts like Email or Money.
๐ช Ports
Interfaces defining system interaction points without exposing implementation.
๐ฏ Use Cases
Coordinate domain operations and enforce workflows.
๐งฑ Adapters
Concrete implementations: REST controllers, ORM repositories, external APIs.
๐งช Testing
- Fast domain-level tests
- Mocked application tests
- Robust integration tests
๐ Measurable Benefits
Test coverage: 30% โ 85%
Deploy frequency: 1/week โ 5/day
Defect rate: 15% โ 2%
๐ Migration Strategy
- Extract domain
- Isolate use cases
- Implement adapters
โ When to use Hexagonal Architecture
- Complex enterprise systems
- Long-term scalable applications
- Teams prioritizing maintainability
โ When to avoid
- Quick MVPs
- Simple CRUDs
- Time-constrained prototypes
Hexagonal Architecture is not an end, but a means to create sustainable software systems that evolve without fear. Fewer dependencies, more control, and significantly fewer 3 AM production nightmares.