Video in progress
When does hexagonal (ports and adapters) architecture pay off, and when is it unnecessary complexity?
It pays off in a system with rich, long-lived business logic and several input/output channels (REST, Kafka, batch, different providers). In plain CRUD or a short-lived service it multiplies interfaces, mappers and DTO layers for every operation, with little benefit.
📖 Answer
The idea: the domain core is in the center, and it only knows the ports (interfaces) it declares itself. Input adapters (REST controller, Kafka listener) and output adapters (JPA, HTTP client) are outside, and dependencies point only inward.
// domain: no Spring, no JPA
public interface LoadOrderPort { Order load(OrderId id); }
public interface ChargePort { ChargeResult charge(Money amount, CardToken token); }
public class PayOrderUseCase {
private final LoadOrderPort orders;
private final ChargePort payments;
public void pay(OrderId id, CardToken card) { ... }
}
// adapter
@Component
class UzcardChargeAdapter implements ChargePort { ... }
When it helps:
- the same use case is called by REST, the admin panel and a nightly batch;
- external providers get swapped (payment systems, SMS gateways);
- you want domain tests that run in milliseconds without a Spring context;
- the system will live 5+ years and framework versions will change.
When it hurts:
- the service mostly fetches data, changes it a little and returns it. For every endpoint you get
Controller → UseCase → Port → Adapter → Repositoryand four mappers: 200 lines of code for 20 lines of logic; - the team is small and writing a fast-changing prototype;
- for a "clean" domain model you are forced to separate the JPA entity from the domain object: two parallel models and mapping bugs between them.
I usually take a pragmatic middle path: I carve out ports only for external systems (payments, messaging, other services), because those really do get swapped and need to be faked in tests. For the database I keep the Spring Data repository close to the core and keep the JPA annotations on the entity. It's not "clean", but the cost/benefit ratio is good. If the system gets more complex, the boundary is already there.
Sign up to mark studied questions and save your progress.