Architectures: layered, hexagonal and clean
Senior Frequently asked 5 min
On this page
The question
What is the difference between layered, hexagonal and clean architecture?
30-second answer
The difference is which way dependencies point. In layered, the controller calls the service and the service calls the repository, so business rules depend on persistence. Hexagonal inverts that: the domain defines ports, and REST (Representational State Transfer) and JPA (Jakarta Persistence API) are adapters that depend on it. Clean is the same rule drawn as rings, with more named layers. Both make rules testable with no framework.
Understand it
Three architectures for "place order"
CompareLayered: controller, service, repository, with every arrow pointing down. The rules in the service depend on persistence, so the database shapes the model.
View as text
The same place order use case drawn three ways, with three rows below: what the business rules depend on, whether it can be tested with no database, and how much structure it asks for.
Layered: controller, service, repository, with every arrow pointing down. The rules in the service depend on persistence, so the database shapes the model. Three stacked boxes have arrows pointing down to the database. The rows read the persistence layer, needs a mock repository, and three folders.
Hexagonal: the domain sits in the middle and defines ports. REST and JPA are adapters outside, and every dependency arrow points in, toward the domain. The rows read only its own ports, yes with a test adapter, and ports and adapters.
Clean: the same idea in rings. Entities sit in the center, use cases around them, then adapters and frameworks. Source dependencies only point inward. Four nested rings have arrows pointing to the center. The rows read only inner circles, yes with a test adapter, and four named rings.
The same place order use case drawn three ways, with three rows below: what the business rules depend on, whether it can be tested with no database, and how much structure it asks for.
Layered: controller, service, repository, with every arrow pointing down. The rules in the service depend on persistence, so the database shapes the model. Three stacked boxes have arrows pointing down to the database. The rows read the persistence layer, needs a mock repository, and three folders.
Hexagonal: the domain sits in the middle and defines ports. REST and JPA are adapters outside, and every dependency arrow points in, toward the domain. The rows read only its own ports, yes with a test adapter, and ports and adapters.
Clean: the same idea in rings. Entities sit in the center, use cases around them, then adapters and frameworks. Source dependencies only point inward. Four nested rings have arrows pointing to the center. The rows read only inner circles, yes with a test adapter, and four named rings.
Takeaway: The real difference is which way the arrows point. In hexagonal and clean, infrastructure depends on the domain; in layered, the domain depends on infrastructure.
Ports and adapters around "place order"
Tap the partsSelect a part to see what it does.
Tap a part to see its job. Arrows are source dependencies, and every one crossing the hexagon points in, toward the domain.
View as text
A hexagon holds the domain in the middle, with an input port above it and an output port below it, both inside the hexagon. A REST adapter above the hexagon points down at the input port. Below the hexagon, a JPA adapter and a test adapter both point up at the output port.
Input port: PlaceOrder, an interface the domain owns, offering what the application does.
JPA adapter: JpaOrderStore implements OrderStore with Spring Data, and keeps annotations and SQL out of the domain.
REST adapter: OrderController turns HTTP into a call on PlaceOrder and holds no business rules.
Domain: OrderUseCase and Order hold the rules, with no Spring or JPA imports, so a plain unit test can run them.
Test adapter: InMemoryStore implements the same port with a list, so tests need no database.
Output port: OrderStore, an interface the domain owns, stating what it needs from outside.
Arrows are source dependencies, and every one crossing the hexagon points in, toward the domain.
A hexagon holds the domain in the middle, with an input port above it and an output port below it, both inside the hexagon. A REST adapter above the hexagon points down at the input port. Below the hexagon, a JPA adapter and a test adapter both point up at the output port.
Input port: PlaceOrder, an interface the domain owns, offering what the application does.
JPA adapter: JpaOrderStore implements OrderStore with Spring Data, and keeps annotations and SQL out of the domain.
REST adapter: OrderController turns HTTP into a call on PlaceOrder and holds no business rules.
Domain: OrderUseCase and Order hold the rules, with no Spring or JPA imports, so a plain unit test can run them.
Test adapter: InMemoryStore implements the same port with a list, so tests need no database.
Output port: OrderStore, an interface the domain owns, stating what it needs from outside.
Arrows are source dependencies, and every one crossing the hexagon points in, toward the domain.
Takeaway: The domain defines its ports and imports nothing from the outside. Adapters plug into those ports, so swapping REST, JPA or a test double leaves the domain untouched.
In code
record Order(String id, BigDecimal total) {
Order {
if (total.signum() <= 0) throw new IllegalArgumentException("total must be positive");
}
}
interface PlaceOrder { Order place(String id, BigDecimal total); } // input port
interface OrderStore { void save(Order order); } // output port
class OrderUseCase implements PlaceOrder {
private final OrderStore store;
OrderUseCase(OrderStore store) { this.store = store; }
@Override public Order place(String id, BigDecimal total) {
Order order = new Order(id, total);
store.save(order);
return order;
}
}class InMemoryOrderStore implements OrderStore { // a test adapter
final List<Order> saved = new ArrayList<>();
@Override public void save(Order order) { saved.add(order); }
}
var store = new InMemoryOrderStore();
PlaceOrder useCase = new OrderUseCase(store);
useCase.place("1", new BigDecimal("10")); // saved: 1 order
useCase.place("2", BigDecimal.ZERO); // IllegalArgumentException, saved: still 1
@RestController
class OrderController { // a driving adapter
private final PlaceOrder placeOrder;
OrderController(PlaceOrder placeOrder) { this.placeOrder = placeOrder; }
@PostMapping("/orders")
Order create(@RequestBody NewOrder body) { return placeOrder.place(body.id(), body.total()); }
}@AnalyzeClasses(packages = "com.shop")
class ArchitectureTest {
@ArchTest
static final ArchRule domainIsPure = noClasses().that().resideInAPackage("..domain..")
.should().dependOnClassesThat().resideInAnyPackage("org.springframework..", "jakarta.persistence..");
}Solve it
Where does the “free shipping over $50” rule belong?
In a layered Spring app the rule sits in OrderController and again in a SQL query. A new Kafka consumer also creates
orders, skips both, and charges shipping on large orders. Decide where the rule lives and how both entry points reach it.
- Classify the rule. It is business policy, not HTTP handling or storage, so it belongs in the domain, written once.
- Put it on the model.
Order.shippingCost()applies it with no Spring or JPA imports, so a plain unit test covers it. - Give every entry point one use case. The REST controller and the Kafka consumer are inbound adapters; both call
PlaceOrder, which uses the domain. - Weigh the architecture. For one entry point and CRUD, a layered service is enough. Ports and adapters pay off with several entry points, as here.
- Check. The same order through REST and through Kafka gets the same shipping cost.
record Order(List<Line> lines) { // domain: no framework imports
Money subtotal() { return lines.stream().map(Line::total).reduce(Money.ZERO, Money::plus); }
Money shippingCost() { return subtotal().isAtLeast(Money.of(50)) ? Money.ZERO : Money.of(5); }
}
class PlaceOrder { // application: the use case
private final Orders orders; // outbound port
PlaceOrder(Orders orders) { this.orders = orders; }
Receipt place(Order order) { orders.save(order); return new Receipt(order.subtotal(), order.shippingCost()); }
}
@RestController class OrderController { // inbound adapter 1
private final PlaceOrder placeOrder;
OrderController(PlaceOrder placeOrder) { this.placeOrder = placeOrder; }
@PostMapping("/orders") Receipt post(@RequestBody Order order) { return placeOrder.place(order); }
}
@Component class OrderConsumer { // inbound adapter 2
private final PlaceOrder placeOrder;
OrderConsumer(PlaceOrder placeOrder) { this.placeOrder = placeOrder; }
@KafkaListener(topics = "orders") void on(Order order) { placeOrder.place(order); }
}How to answer
- Layered is simple and fits CRUD (create, read, update, delete), but persistence tends to shape the model.
- Hexagonal has ports owned by the domain and adapters outside it.
- Clean's dependency rule says source dependencies only point inward.
- The cost is more interfaces and mapping between domain and persistence models.
Common mistakes
- Calling hexagonal better in every case; it is extra structure for a service with few rules.
- Treating hexagonal and clean as opposites; they share the same dependency rule.
Follow-up questions
Where should business logic live?
In the domain: entities and use cases, not controllers or repositories. A controller translates HTTP, and a repository translates storage. If a rule like "total must be positive" sits in a controller, another entry point can skip it, such as a message consumer. Put rules where every path passes through, ideally on the object that owns the data.
- Controllers should hold no business decisions.
- A record's compact constructor can enforce a rule on every creation.
- A service with all the logic and entities with only getters is called an anemic domain model.
See it in the infographic: Ports and adapters around "place order"
What are ports and adapters?
A port is an interface owned by the domain. An input port says what the application offers, such as PlaceOrder. An output port says what it needs, such as OrderStore. An adapter connects a port to a technology. Driving adapters such as a REST controller call in. Driven adapters such as a JPA repository implement output ports.
- Ports speak in domain terms, with no HTTP or SQL.
- A new technology means a new adapter, and no change to the domain.
- A test adapter runs the real rules with no infrastructure.
See it in the infographic: Ports and adapters around "place order"
When is a hexagonal architecture worth its cost, and when is it not?
It pays off when rules are rich and long-lived, when several channels reach the same logic, such as REST and Kafka, or when infrastructure may change. It costs extra interfaces and mapping classes, which is waste for a thin CRUD service. A good middle ground is one project with clear packages and an ArchUnit rule, adding full ports only where needed.
- Weigh the cost of mapping against how much logic there really is.
- Start simple and extract ports when a second adapter or real complexity appears.
- Enforce the boundary with tests, or it erodes.
See it in the infographic: Three architectures for "place order"
What is the Dependency Inversion Principle's role here?
It is the mechanism. Without it, the use case calls a JPA class and depends on persistence. With it, the use case owns an OrderStore interface, and the JPA class implements it. At runtime the call still goes from domain to database, but the source dependency now points from database code to the domain.
Are Spring annotations allowed in the domain?
In the strict form, no: @Entity and @Service tie the domain to frameworks, so the domain gets its own classes and adapters map them. Many teams compromise on @Service or even @Entity to avoid the mapping code. Either can be fine; what matters is deciding on purpose and enforcing it, for example with ArchUnit.
Check yourself
Show answers
- From JpaOrderStore to the domain: Correct. The adapter implements an interface the domain owns, so it depends on the domain.
- From the domain to JpaOrderStore: Incorrect. That is the layered direction, and it is what the port exists to avoid.
- Neither depends on the other: Incorrect. The adapter has to import the port to implement it.
Show answers
- An in-memory class that implements OrderStore: Correct. The domain cannot tell which adapter it has, so the rules run for real.
- An embedded database such as H2: Incorrect. That still brings persistence into the test, and a port avoids that entirely.
- Starting the full Spring context: Incorrect. The domain has no Spring dependency, so a plain new is enough.