Skip to content
notes.vinhnq.com

Search

OOP & DesignMid25 min read

Codebase architecture: layered, hexagonal, onion, clean and functional core

Review 17 cards
On this page

Codebase architecture series: 1. Layered, hexagonal, onion, clean · 2. DDD and package structure

A Spring Boot project that has run for three years often has a service package with 80 classes calling each other, JPA entities going straight out as JSON, and a discount rule you can’t unit test without a database. The cause is a codebase that grew without any rule about what is allowed to depend on what. After this post you can explain why a project splits its folders the way it does, know where a new piece of logic goes, and keep that rule as the team grows.

Read first if needed: IoC and Dependency Injection (how Spring assembles objects) and the Adapter and Factory patterns. Part 2 goes into DDD and splitting packages by domain, with an exercise that builds the skeleton of a flight-booking codebase.

1. Flow of control and dependency direction

Key idea: code runs from the business logic to the database, but the source code doesn’t have to depend in that direction. Put the interface on the business side and the database ends up depending on the business logic.

  • Flow of control: the order in which code runs when a request arrives. HTTP enters the controller, the controller calls the business logic, the business logic calls the database, and the result travels back out.
  • Dependency direction: class A imports class B, knows B’s name, and has to be recompiled when B changes.

In traditional layered architecture the two coincide: business logic calls the repository, so it depends on the repository. The later architectures separate them with the Dependency Inversion Principle (the D in SOLID).

flowchart LR
  subgraph Traditional
    S1[OrderService] -->|calls and imports| R1[JpaOrderRepository]
  end
  subgraph Inverted
    S2[OrderService] -->|calls| P[OrderRepository interface]
    A2[JpaOrderRepositoryAdapter] -->|implements| P
  end

On the right, OrderService still calls into storage at runtime, but its source code only knows OrderRepository, an interface that lives on its own side. It is the JPA adapter that has to know about that interface.

2. Layered architecture

Key idea: split code into horizontal layers; requests flow top to bottom and don’t skip layers. Simple, but business logic depends on persistence, so the database becomes the centre of the design.

2.1. The idea

The classic version has four layers: presentation (controllers), business (services), persistence (repositories), database. The number isn’t fixed: a small app merges layers, a large one adds more.

The main rule is the closed layer: a controller doesn’t call a repository directly, it goes through a service. The benefit is layers of isolation: changing how data is stored only touches the persistence layer.

flowchart TB
  P[Presentation: controller, DTO] --> B[Business: service]
  B --> PE[Persistence: repository]
  PE --> D[(Database)]

2.2. Open layers

An open layer is one that requests are allowed to bypass: a deliberate exception that should be written down in the architecture docs.

Open layers: letting requests bypass a shared layer

The problem the slides raise: the business layer contains many shared components (sending email, formatting money, checking permissions). Keep them in the same layer and services end up calling each other in a tangle.

The solution is to add a shared services layer and mark it open: the business layer may call it, but requests may also bypass it and go straight to persistence. An open layer is a deliberate exception and should be documented. Otherwise, after a few months every layer is “open” and the rule means nothing.

2.3. Pros and cons

Pros: simple, everyone understands it, and Spring Boot projects take roughly this shape by default; each layer can be tested by mocking the one below.

The cons the slides list are “hard to scale” and “layers depend on each other”. More concretely:

  • Business logic depends on persistence: services import JPA entities and Spring Data repositories. Testing a discount rule needs JPA.
  • Split by technical concern, not by business capability: one feature change touches controller, service and repository. “Hard to scale” means hard for people (many teams editing the same packages), not hard for the runtime.
  • Sinkholes: requests pass through the layers without any layer doing anything (the service only calls the repository). Not wrong, but a sign that the layer is redundant for that use case.

3. Hexagonal architecture (ports and adapters)

Key idea: the application sits in the middle, everything that goes in or out sits at the edges. The application defines its own interfaces (ports) and concrete technologies plug in through implementations (adapters), so swapping a technology doesn’t touch the core.

3.1. The idea

Proposed by Alistair Cockburn in 2005. Think socket and plug: the appliance defines the socket, and whoever wants to connect makes a plug that fits.

  • Driving side (the active side, on the left): things that call into the application: HTTP controllers, Kafka consumers, CLIs, jobs, and also tests. The port is a use case interface (PlaceOrderUseCase); the adapter is the controller that calls it.
  • Driven side (the passive side, on the right): things the application calls out to: the database, a message broker, a payment API, email. The port is an interface the application needs (OrderRepository, PaymentGateway); adapters implement it with JPA, Kafka, an HTTP client.
flowchart LR
  WEB[REST controller] --> IN[Inbound port: PlaceOrderUseCase]
  KAFKA[Kafka consumer] --> IN
  TEST[Test] --> IN
  IN --> APP[Application]
  APP --> OUT1[Outbound port: OrderRepository]
  APP --> OUT2[Outbound port: PaymentGateway]
  JPA[JPA adapter] -.implements.-> OUT1
  VNPAY[VNPay adapter] -.implements.-> OUT2

The hexagon has nothing to do with the number six: it just gives you enough sides to draw many ports and escapes the “top/bottom” picture of layered architecture.

3.2. A short example

// application: knows only the ports
public interface PaymentGateway {                   // outbound port, lives in the core
    PaymentLink createLink(OrderId id, Money amount);
}

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 PlaceOrderResult place(PlaceOrderCommand cmd) {
        Order order = Order.place(cmd.customerId(), cmd.lines());   // business rules live in the domain
        orders.save(order);
        return new PlaceOrderResult(order.id(), payments.createLink(order.id(), order.total()));
    }
}

// adapter: knows the port and the technology
@Component
class VnpayPaymentGateway implements PaymentGateway {
    private final RestClient http;
    VnpayPaymentGateway(RestClient http) { this.http = http; }
    public PaymentLink createLink(OrderId id, Money amount) { /* sign the parameters, call VNPay */ return null; }
}

Testing PlaceOrderService only needs a fake PaymentGateway (a lambda or a 3-line class) and an in-memory repository. No Spring, no database, and it runs in a few milliseconds.

3.3. Pros and cons

  • Pros: loose coupling; a core testable independently of external services; adapters that are easy to swap (change payment provider, add a GraphQL or Kafka entry point without touching the core). Netflix has described moving a data source from a monolith to a microservice by writing only a new adapter.
  • Cons: a learning curve; more interfaces and mapping classes; for CRUD (create, read, update, delete) it is almost all pass-through code.

4. Onion architecture

Key idea: concentric circles with the domain model at the centre, and dependency arrows pointing only towards the centre. Onion adds to hexagonal the structure of the inside.

Proposed by Jeffrey Palermo in 2008 as an evolution of layered architecture, it solves two problems: layers depending on each other in a chain, and business logic tightly coupled to infrastructure.

flowchart TB
  UI[Outer ring: UI, Infrastructure, Tests] --> AS[Application Services]
  AS --> DS[Domain Services]
  DS --> DM[Domain Model]
  • Domain Model at the centre: entities, value objects, business rules. Depends on nothing.
  • Domain Services: business rules involving several entities, and the repository interfaces.
  • Application Services: orchestrate use cases.
  • Outer ring: UI, infrastructure (database, files, external APIs), tests. This is where the inner interfaces get implemented.

Nothing in an inner ring knows anything about an outer ring. The database is no longer the bottom of a stack of layers but a detail in the outer ring.

Compared with hexagonal: hexagonal only talks about the inside/outside boundary and ports/adapters, and says nothing about the inside of the hexagon. Onion adds exactly that part.

Pros: the business logic is at the centre, loosely coupled, easy to test. Cons: more complex, has to be learned, and it’s easy to “build every ring” even for features with no business logic at all.

5. Clean architecture

Key idea: clean architecture puts hexagonal and onion into one diagram with one rule: dependencies point only inwards. Data crosses the boundary as DTOs, and repository interfaces are declared inside and implemented outside.

5.1. A repackaging, not a new invention

Robert C. Martin (2012) combined hexagonal, onion and a few other architectures into four rings:

  • Entities: the enterprise’s core business rules, the least likely to change.
  • Use cases: application rules that orchestrate entities for each scenario.
  • Interface adapters: controllers, presenters, gateways; they convert data between the form convenient for use cases and the form convenient for the outside world.
  • Frameworks and drivers: web, database, UI, devices.

Two points the slides stress:

  1. Never violate the dependency rule (dependencies point inwards). This is the whole architecture; everything else is detail.
  2. There is no fixed number of rings. Four is just an example.
Herberto Graça’s Explicit Architecture diagram and a factory for adapters

Herberto Graça’s “Explicit Architecture” diagram (the slides use it as an illustration) puts everything together: driving adapters on the left, driven adapters on the right, ports at the boundary, the application and domain layers inside, plus a command bus, a query bus and an event bus. It is a reference map, not a template to follow; the author himself says “understand all of it, but only use what you need”.

The slides mention “creating a factory for a service’s adapters”: one place (bean configuration in Spring, or a factory) decides which adapter is plugged into which port. For example, choosing by environment: FakePaymentGateway for tests, VnpayPaymentGateway for production.

5.2. Crossing the boundary: two problems

Problem 1: the controller touches entities. The use case returns an entity and the controller returns it as JSON. The outer ring (web) now depends on the details of an inner ring, and every entity change leaks into the API.

Solution: data crosses the boundary as simple data structures (DTOs, commands, results). A use case accepts a Command and returns a Result that the use case layer itself defines; the controller maps the HTTP request to a command and the result to a response.

Problem 2: the domain needs to persist data. A use case needs to save a Booking. Calling JpaBookingRepository directly means an inner ring depends on an outer ring, which breaks the rule.

Solution: declare the repository interface in the inner ring (next to the domain) and implement it in the outer ring. At runtime Spring injects the adapter; at compile time the inner ring only knows the interface. This is exactly the inverted picture from section 1.

The two problems in detail: where DTOs live, the JPA adapter code, separating the domain model from the JPA entity
// inner ring: package booking.domain.port
public interface BookingRepository {
    Optional<Booking> findById(BookingId id);
    void save(Booking booking);
}

// outer ring: package booking.adapter.out.persistence
@Repository
class JpaBookingRepositoryAdapter implements BookingRepository {
    private final SpringDataBookingJpa jpa;          // Spring Data interface, known only to the adapter
    private final BookingEntityMapper mapper;
    JpaBookingRepositoryAdapter(SpringDataBookingJpa jpa, BookingEntityMapper mapper) { this.jpa = jpa; this.mapper = mapper; }

    public Optional<Booking> findById(BookingId id) { return jpa.findById(id.value()).map(mapper::toDomain); }
    public void save(Booking booking) { jpa.save(mapper.toEntity(booking)); }
}

5.3. When to use clean architecture

  • Pros according to the slides: independence from frameworks, databases and external services; easier maintenance and collaboration; easier testing; flexibility; easier extension.
  • Cons: it takes time to set up; frameworks force you to break the rule in a few places (Spring and JPA annotations); it is complex, has to be learned, and is easy to get wrong (all the layers exist but the logic still sits in the controller).

The choice should start from your architectural drivers (business rules, deadline, team size, quality attributes), not from hype: see Pragmatic software architecture: architectural drivers.

6. Functional architecture: a pure core, I/O at the edges

Key idea: write business rules as pure functions: data in, decisions out. All I/O lives in the shell: read first, call the core, then write.

A pure function gives the same output for the same input (deterministic) and has no side effects (no external state changes, no I/O). Functional architecture applies that idea to the whole application:

  • Core domain: only pure functions that express business rules.
  • I/O at the edges: read the data (database, HTTP) first, then write the result afterwards. Dependencies go one way; the core never calls out.

Mark Seemann calls this shape the “impureim sandwich”: an impure layer, a pure filling, an impure layer.

// pure core: no repository, no clock, no I/O exceptions
record CancelDecision(boolean cancel, String reason) {}

static CancelDecision decideCancel(Ride ride, Instant now) {
    if (ride.status() != RideStatus.WAITING) return new CancelDecision(false, "already " + ride.status());
    if (now.isBefore(ride.createdAt().plus(Duration.ofMinutes(10)))) return new CancelDecision(false, "not due");
    return new CancelDecision(true, "no driver in 10 minutes");
}

// shell: read, decide, write
void handleTimeout(RideId id) {
    Ride ride = rides.findById(id).orElseThrow();                 // I/O
    CancelDecision d = decideCancel(ride, clock.instant());        // pure
    if (d.cancel()) rides.cancelIfWaiting(id, d.reason());         // I/O
}
  • Pros: a clear testing boundary: unit tests for the core (no mocks, just input/output), integration tests for the shell. The domain is fully isolated from infrastructure.
  • Cons: shifting from object-oriented/imperative thinking to functional takes time, and few teams do it properly.
A pure core in Java 21 and why you should pass a Clock

You don’t need Haskell or Scala. In Java 21, records + sealed interfaces + pattern matching are enough to write most business rules as pure functions, even inside a hexagonal codebase: pure domain services, with the application service as the shell.

7. A quick comparison

Key idea: the three in the middle are almost the same thing: domain inside, infrastructure outside, interfaces on the inside, implementations on the outside. They differ mostly in naming and in how much detail they give about the inside.

Layered Hexagonal Onion Clean Functional core
Centre Database at the bottom The application Domain model Entities Pure functions
Dependency direction Top to bottom Inwards through ports Towards the centre Inwards Shell → core
What it says about the inside Horizontal layers Nothing Domain / domain services / app services Entities / use cases Pure / impure
Upfront cost Low Medium Medium Medium–high Depends on the team’s skills
Good fit for CRUD, small projects Many entry/exit points Complex business logic Same as onion Heavy calculation rules

8. Enforce the architecture with tests, not reviews

Key idea: a dependency rule is only worth something if nobody breaks it, and eyeball reviews easily miss a single import line. Turn the rules into tests that run in CI.

ArchUnit reads bytecode and checks rules like a unit test, for example “the domain doesn’t depend on adapters, Spring or JPA”. I ran these rules (ArchUnit 1.4.1) against the flight-booking skeleton from part 2: all of them passed.

For Spring Boot there is also Spring Modulith. It checks that modules (top-level packages under the root package) only call each other through their public APIs, generates module documentation and diagrams, and lets you test each module in isolation (@ApplicationModuleTest).

ArchUnit: the rule code, the result of a deliberate violation, and the composition-root trap
@AnalyzeClasses(packages = "com.example.flightbooking")
class ArchitectureTest {

    @ArchTest
    static final ArchRule domainIsPure = noClasses().that().resideInAPackage("..domain..")
        .should().dependOnClassesThat().resideInAnyPackage(
            "..application..", "..adapter..", "org.springframework..", "jakarta.persistence..");

    @ArchTest
    static final ArchRule onion = onionArchitecture()
        .domainModels("..domain.model..")
        .domainServices("..domain.service..", "..domain.port..")
        .applicationServices("..application..")
        .adapter("web", "..adapter.in.web..")
        .adapter("persistence", "..adapter.out.persistence..")
        .ignoreDependency(resideInAPackage("..config.."), DescribedPredicate.alwaysTrue());
}

Adding a class in domain.service with a field of type InMemoryBookingRepository (an adapter) made the first rule fail, pointing at the offending line:

FAIL domain is framework-free and depends on nothing outward
     Field <...domain.service.LeakyFare.repo> has type <...adapter.out.persistence.InMemoryBookingRepository>

Exercises

Exercise 1: spot the violations in a real codebase

Task: a project has the packages api.rest, app, domain.<feature>.{entity, repository, service, dto} and infrastructure.{repository, util}. An inspection finds:

  • (a) 5 classes in domain.*.service import infrastructure.util.DateUtil.
  • (b) Interfaces in domain.*.repository extend JpaRepository.
  • (c) domain.homestay.repository.HomestayDetailRepository is a plain interface whose implementation lives in infrastructure.repository.

Assess each point.

Solution to Exercise 1: assessing (a), (b) and (c)
  • (a) A clear violation: the domain depends outwards on an infrastructure utility. Fix: if DateUtil is just pure date arithmetic, it belongs in the domain (or in a shared package that depends on nothing), so move it; if it reads the system clock, replace it with an injected Clock.
  • (b) A common compromise: the domain depends on Spring Data. Acceptable for a small project, but it drags JPA entities into the domain and makes domain unit tests need Spring. The upgrade path: a plain repository interface in the domain (only the methods the business needs), with an infrastructure adapter that uses Spring Data internally.
  • (c) The correct port/adapter pattern: interface on the inside, implementation on the outside. This is the model to apply to (b).
  • Write an ArchUnit rule noClasses().that().resideInAPackage("..domain..").should().dependOnClassesThat().resideInAPackage("..infrastructure..") so that (a) doesn’t come back.

Exercise 2: extract business rules into a pure function

Task: a room-booking service checks that the check-in date isn’t in the past (using LocalDate.now()), the number of nights is ≤ 365, the number of guests is ≤ capacity, and applies a 5% discount for stays of 3 nights or more. All of it sits in one @Transactional method together with the query that locks the room calendar and the code that saves the booking. How do you split it so the rules can be unit tested without a database?

Solution to Exercise 2: a pure quote function and a @Transactional shell
record StayRequest(LocalDate checkIn, LocalDate checkOut, int guests) {}
record Quote(long nights, BigDecimal subtotal, BigDecimal discount, BigDecimal total) {}

sealed interface QuoteResult permits QuoteResult.Ok, QuoteResult.Rejected {
    record Ok(Quote quote) implements QuoteResult {}
    record Rejected(String code) implements QuoteResult {}
}

static QuoteResult quote(StayRequest r, int capacity, List<BigDecimal> nightlyPrices, LocalDate today) {
    if (r.checkIn().isBefore(today)) return new QuoteResult.Rejected("CHECKIN_IN_PAST");
    long nights = ChronoUnit.DAYS.between(r.checkIn(), r.checkOut());
    if (nights <= 0 || nights > 365) return new QuoteResult.Rejected("INVALID_NIGHTS");
    if (r.guests() <= 0 || r.guests() > capacity) return new QuoteResult.Rejected("INVALID_GUESTS");
    if (nightlyPrices.size() != nights) return new QuoteResult.Rejected("NOT_AVAILABLE");
    BigDecimal subtotal = nightlyPrices.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
    BigDecimal discount = nights >= 3 ? subtotal.multiply(new BigDecimal("0.05")) : BigDecimal.ZERO;
    return new QuoteResult.Ok(new Quote(nights, subtotal, discount, subtotal.subtract(discount)));
}

The shell (the application service, @Transactional):

  1. Lock and read the available nights, read the capacity.
  2. Call quote(..., LocalDate.now(clock)).
  3. switch on the result: return an error for Rejected; for Ok, mark the nights as booked and save the booking.

Unit tests for quote with a few dozen cases run in milliseconds. Integration tests only need a handful of scenarios for the shell (correct locking, correct saving, concurrent conflicts).

Remember

  • Can tell flow of control apart from dependency direction, and Dependency Inversion apart from Dependency Injection.
  • Can explain why hexagonal, onion and clean are the same idea, and where layered differs from them.
  • Know where repository interfaces and DTOs/commands/results go, and why JPA entities must not leave through the API.
  • Know when not to adopt clean architecture, and the three cheap habits worth keeping.
  • Know how to extract business rules into pure functions (pass a Clock) and how to enforce the rules with ArchUnit.

Interview questions

Junior

What is layered architecture? What does “closed layer” mean?

Code is split into horizontal layers by responsibility (controller, service, repository), and requests flow from top to bottom. A closed layer means a request can’t skip it.

The controller must go through the service and can’t call the repository directly. That way a change in one layer has little impact on the others.

Why shouldn’t you return JPA entities directly from an API?

Because the API gets tied to the database schema: adding a column changes the JSON.

Sensitive fields also leak easily, lazy relations cause errors on serialisation or unexpected extra queries, and bidirectional relations create cycles. Use DTOs (records) at the boundary, mapped in the controller or the use case.

Mid

What are ports and adapters in hexagonal architecture?

Ports are interfaces defined by the application; adapters are implementations tied to a specific technology.

  • An inbound port is a use case the outside world calls (PlaceOrderUseCase); a REST controller is the adapter that calls it.
  • An outbound port is something the application needs (OrderRepository, PaymentGateway); a JPA class or HTTP client is the adapter that implements it.

The core only knows the ports, so swapping an adapter doesn’t touch the core and the core can be tested with fake adapters.

How does Dependency Inversion differ from Dependency Injection?

Dependency Inversion is a principle about dependency direction; Dependency Injection is the technique of supplying dependencies from outside.

DIP: high- and low-level modules both depend on an abstraction, and the abstraction belongs to the high-level side (the repository interface lives next to the domain). DI: dependencies are passed in, usually through the constructor, by a container like Spring. You can use DI and still violate DIP (injecting a concrete JPA class into a service).

What is the core difference between onion/clean architecture and layered architecture?

The dependency direction.

Layered: business logic depends on persistence, with the database at the bottom. Onion/clean: the domain at the centre depends on nothing, and the database is a detail in the outer ring. Repository interfaces are declared inside and implemented outside, so calls still reach the database but source-code dependencies only point inwards.

The domain needs to persist data without depending on the database. How?

Declare a repository interface on the inside (the domain or the application layer), implement it in an infrastructure adapter, and let Spring inject the adapter at runtime.

The interface only has the methods the business needs; the adapter implements them with JPA/JDBC. The domain only knows the interface. If the JPA entity is separate from the domain model, the adapter is responsible for mapping.

Senior

When would you not use clean architecture?

When the cost of the extra interfaces, mappers and layers isn’t paid back: small projects, teams of 1–3 people, short lifetimes; services that are almost pure CRUD or just move data; internal tools and libraries.

I still keep three cheap habits: packages by feature, DTOs at the boundary and repository interfaces on the inside, so any module that becomes complex can be upgraded later.

How do you keep architecture rules in place as the team grows?

Turn the rules into tests that run in CI, so violating PRs are blocked.

  • ArchUnit: the domain doesn’t import adapters or frameworks, onion checks, no dependency cycles between modules.
  • Spring Modulith for module boundaries.
  • Record decisions in ADRs. Deliberately exclude the composition root.

Reviews are then left to discuss only the justified exceptions.

Is it worth separating the domain model from the JPA entity?

It depends on how complex the aggregate is: separate when it has many business rules, share the class when the domain is thin.

Separating gives a pure domain that JPA doesn’t constrain (no-arg constructors, proxies, setters), with the schema and the model evolving independently. The price is mappers, losing natural dirty checking and lazy loading, and carrying the optimistic-lock version yourself. What’s non-negotiable is that the repository interface lives on the inside and entities never leave through the API.

How does a functional core with an imperative shell help testing?

Business rules become pure functions, so unit tests are just input/output with no mocks; the shell needs only a few integration tests.

Pure functions take data (including the current time) and return decisions, so tests are very fast and cover every branch. The shell only reads, calls the core and writes, so it needs only a few I/O scenarios. The line between unit and integration tests becomes clear.

Useful phrases for interviews

  • “The flow of control goes from the service to the database, but the source-code dependency points the other way.”
  • “The one rule we never break is the dependency rule: everything points towards the domain.”
  • “With ports and adapters, the core only knows interfaces it owns, so swapping the payment provider is just a new adapter.”
  • “Controllers and tests sit on the driving side; the database and the payment gateway sit on the driven side.”
  • “Data crosses the boundary as simple DTOs or commands, never as JPA entities.”
  • “Dependency inversion lets the repository interface live next to the domain, while the JPA adapter implements it outside.”
  • “Only the composition root is allowed to know every implementation.”
  • “We keep pricing rules as pure functions and push side effects to the edges, so unit tests need no mocks.”
  • “For a small CRUD service I’d stay with a tidy layered design; I’d only add ports where the business rules are complex.”
  • “An ArchUnit test fails the build if the domain imports an adapter, so we don’t rely on eyeball reviews.”

Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.