Hexagonal Architecture (Ports and Adapters)
Isolating domain logic from frameworks and infrastructure with ports and adapters, so the core can be tested and evolved independently of databases, APIs and messaging.
Intent
Proposed by Alistair Cockburn, hexagonal architecture puts the application core (domain and use cases) at the center. The core defines ports (interfaces) for what it needs and what it offers. Adapters implement ports for specific technologies: REST controllers, Kafka listeners, JPA repositories, external API clients.
flowchart LR REST[REST adapter] --> IN1((Inbound port:<br/>PlaceOrderUseCase)) KAFKA[Kafka listener adapter] --> IN1 IN1 --> CORE[Domain + application services] CORE --> OUT1((Outbound port:<br/>OrderRepository)) CORE --> OUT2((Outbound port:<br/>PaymentGateway)) OUT1 --> JPA[JPA adapter] --> DB[(PostgreSQL)] OUT2 --> PSP[PSP REST adapter] --> EXT[Payment provider]
Java example
// Inbound port
public interface PlaceOrderUseCase { OrderId place(PlaceOrderCommand cmd); }
// Outbound ports
public interface OrderRepository { void save(Order order); Optional<Order> find(OrderId id); }
public interface PaymentGateway { PaymentResult authorize(Money amount, PaymentToken token); }
// Application service: no Spring, JPA or HTTP types here
public class PlaceOrderService implements PlaceOrderUseCase {
private final OrderRepository orders;
private final PaymentGateway payments;
public PlaceOrderService(OrderRepository orders, PaymentGateway payments) { this.orders = orders; this.payments = payments; }
@Override
public OrderId place(PlaceOrderCommand cmd) {
Order order = Order.create(cmd.customerId(), cmd.lines());
PaymentResult r = payments.authorize(order.total(), cmd.paymentToken());
if (!r.approved()) throw new PaymentDeclined(r.reason());
order.markPaid(r.reference());
orders.save(order);
return order.id();
}
}
// Adapter (infrastructure)
@Repository
class JpaOrderRepository implements OrderRepository {
private final SpringDataOrders jpa;
JpaOrderRepository(SpringDataOrders jpa) { this.jpa = jpa; }
public void save(Order o) { jpa.save(OrderEntity.from(o)); }
public Optional<Order> find(OrderId id) { return jpa.findById(id.value()).map(OrderEntity::toDomain); }
}Unit tests use in-memory fakes for ports; adapter tests use Testcontainers.
Pros and cons
| Pros | Cons |
|---|---|
| Domain logic testable without infrastructure | More interfaces and mapping code |
| Swap technologies (DB, broker) with less impact | Overkill for simple CRUD services |
| Clear dependency direction | Teams may over-abstract |
Interview questions
When is hexagonal architecture not worth it?
For thin CRUD services or short-lived prototypes where the domain logic is trivial; the indirection costs more than it saves.
Hexagonal vs layered architecture?
Layered architectures often let domain code depend on persistence. Hexagonal inverts that: infrastructure depends on the domain's ports, so the domain is independent of frameworks.