Pattern · Ports & adapters
Hexagonal Architecture
Isolate business logic from infrastructure. Swap databases, APIs, or UIs without touching the core.
Overview
Hexagonal Architecture (Ports and Adapters) puts the domain model at the center. Everything external — databases, HTTP, queues, CLIs — connects through ports (interfaces) and adapters (implementations). The core never knows what's outside.
Core Concepts
Domain Core
Business logic, entities, and use cases. Has zero dependencies on frameworks, databases, or HTTP.
Ports
Interfaces defined by the core. Input ports (what the core exposes). Output ports (what the core needs).
Primary Adapters
Drive the application. REST controllers, Lambda handlers, CLI commands, SQS consumers.
Secondary Adapters
Serve the application. Database repositories, S3 clients, SES email, external API wrappers.
Key Benefits
- Testability — unit test business logic with mock adapters, no database needed
- Replaceability — swap DynamoDB for RDS without touching a single use case
- Clarity — explicit boundaries between what the app does vs. how it connects
- Framework independence — business rules don't know or care about Express or FastAPI
AWS Implementation
- Primary adapters: API Gateway, Lambda handlers, SQS consumers, EventBridge rules
- Secondary adapters: DynamoDB repos, S3 adapters, SES email, Secrets Manager
- Core: Lambda Layers for shared business logic, ECS for containerized apps
Comparison
| Aspect | Hexagonal | Layered | Clean Architecture |
|---|---|---|---|
| Testability | Excellent | Good | Excellent |
| Flexibility | High | Medium | High |
| Complexity | Medium | Low | High |
| Learning Curve | Medium | Low | High |