Hexagonal Architecture
Put the business logic at the centre with no dependencies on frameworks or databases; everything else plugs in through ports and adapters.
Description
In hexagonal architecture the domain core, your business rules, depends on nothing external. It defines ports: interfaces for what it needs (OrderRepository, PaymentGateway) and what it offers (PlaceOrder). Adapters on the outside implement those ports: an HTTP controller drives the core, a Postgres repository and a Stripe client are driven by it.
Dependencies always point inwards. You can test the core with in-memory adapters in milliseconds, swap a database or a vendor by writing a new adapter, and upgrade frameworks without touching business rules. Clean Architecture and Onion Architecture are variations of the same idea.
System design
Hexagonal Architecture system design diagram
- HTTP controller (gateway): driving adapter.
- Domain core (service): rules + ports.
- Postgres adapter (database): implements OrderRepository.
- Stripe adapter (external service): implements PaymentGateway.
- In-memory fakes (function): for tests.
- Step 1: HTTP controller → Domain core: PlaceOrder port.
- Step 2: Domain core → Postgres adapter: OrderRepository port.
- Step 3: Domain core → Stripe adapter: PaymentGateway port.
- Step 4: In-memory fakes → Domain core: same ports, no I/O.
- The HTTP controller turns a request into a call on the core's PlaceOrder port. It's an adapter that drives the core.
- The core saves through the OrderRepository port; the Postgres adapter implements it. The core never imports Postgres.
- It charges through the PaymentGateway port; swapping Stripe for another provider means writing one new adapter.
- In tests, in-memory fakes plug into the same ports, so business rules run in milliseconds without a database or network.
When to use it
Use it when
- The domain logic is valuable and complex, and will outlive the current frameworks and vendors.
- You want fast, reliable unit tests of business rules without databases or HTTP.
- You integrate with external systems that may change: payment providers, messaging, storage.
Avoid it when
- It's a thin CRUD app with little logic. The ports and adapters add ceremony with no payoff.
- A short-lived prototype where speed beats structure.
Pitfalls
- Interfaces for everything, even things that will never change, creating boilerplate. Add ports where there's a real boundary.
- Framework types (ORM entities, HTTP request objects) leaking into the core, breaking the inward-only rule.
- Mapping fatigue: converting between DTOs, domain objects and persistence models everywhere. Keep mappings at adapters only.
Alternatives
Layered Architecture
Choose it when the app is simple and the database-centric flow is fine.
Modular Monolith
Choose it when the main problem is splitting a big app by business area; use hexagonal inside each module.
Adapter
Choose it when you need the same idea for a single integration, not a whole architecture.