Home / Technology / Hexagonal Architecture in Practice: An Example in a Project

Hexagonal Architecture in Practice: An Example in a Project

Hexagonal architecture, also called ports and adapters, is an architectural style that isolates an application’s business rules from the database, the web interface and external services: the core defines ports (interfaces) and the infrastructure plugs into them through adapters. The result is a system where business rules can be tested without starting anything, and technology can change without rewriting what matters.

This guide shows the idea at work in a sample project created for this article (it is not a client case): an orders API with a credit limit, in Java. You will see the domain, the ports, the adapters, the wiring, the tests, the folder structure, how it compares with Clean Architecture and Onion and, just as candidly, the cases where hexagonal architecture is overkill.

Hexagonal architecture in practice: person from behind wearing headphones at a monitor showing code in a dark room

What Is Hexagonal Architecture (Ports and Adapters)?

Hexagonal architecture is a pattern in which the application has a core with the business rules, surrounded by ports (interfaces that say what the core offers and what it needs) and adapters (implementations that connect those ports to concrete technologies, such as HTTP, databases or queues).

The pattern was proposed by Alistair Cockburn in 2005, according to the AWS prescriptive guidance, and the original intent, described in Cockburn’s article, is to let an application be driven equally by users, other programs, automated tests or scripts, and to be developed and tested in isolation from the devices and databases it will eventually run on. In 2024, Cockburn published a book on the subject with Juan Manuel Garrido de Paz, according to Wikipedia.

Two points avoid confusion. First, the name: “hexagonal” comes from the way the component is drawn, not from a rule of six sides; the number of ports is up to you. Second, the more precise name is ports and adapters, which Cockburn himself later adopted; both terms mean the same thing.

What Problem Does Hexagonal Architecture Solve?

It solves the coupling between business rules and infrastructure: when order logic knows the web framework, the ORM and the billing provider, every technology change cuts across the whole system, and every test needs a database, a network and configuration.

A common scenario: a service starts simple, with a controller, a service and a repository. Over time, the credit check depends on a framework annotation, a SQL query decides a business rule, and the service calls the billing provider’s SDK directly. Changing the provider becomes a project; testing the credit rule requires a database; and the only way to know something broke is to run the whole application.

AWS describes the effect of that mix: business logic embedded in the database and the UI leads to tightly coupled architectures that block database migrations and user experience modernization. Hexagonal architecture attacks exactly that, by letting you design the system by purpose (what it does) and not by technology (how it does it).

The Concepts in Five Minutes

The concepts come down to five: core, inbound port, outbound port, adapter and wiring. The rule that ties them together is the direction of dependencies: outer code knows inner code, never the other way around. Below, each concept and where it shows up in our example (table as an editorial proposal by NextAge).

Concept What it is In the example
Core Business rules (domain) and orchestration of use cases (application), with no framework Customer, Order and PlaceOrderService
Inbound port (driving) Interface that describes what the outside world can ask of the core PlaceOrder
Outbound port (driven) Interface that describes what the core needs from the outside world CustomerRepository, OrderRepository, BillingGateway, Notifier
Adapter Implementation that connects a port to a technology OrderController (REST), JPA adapter, billing gateway adapter
Wiring The place where concrete adapters are connected to the core A Spring configuration class

Thoughtworks (May 21, 2026) sums up the principle: the core business logic should never depend directly on infrastructure tools. In code terms, this is the dependency inversion principle: the core defines the interface, and the adapter, which lives outside, implements it. Inbound adapters (such as a REST controller) call inbound ports; outbound adapters (such as a JPA repository) implement outbound ports.

The Sample Project: Orders With a Credit Limit

The example is an API that registers orders for B2B customers. The central rule: an order cannot be placed if the customer’s used credit, plus the order total, exceeds the credit limit. When an order is placed, the system saves it, issues the charge and notifies the customer.

This project is fictional and educational, created for this article; it does not represent a client or a real system. It was chosen because it has the three elements that justify the pattern: a business rule that matters (the credit limit), more than one output (database, billing, notification) and points likely to change (today’s billing gateway may be another one tomorrow, and the notification may become a queue).

On naming: the code is in Java 17 or later, and the ideas apply equally to .NET, Node or Python. Only the adapters use Spring; the core is plain Java.

Step by Step: From the Domain to the Tests

The build goes from the inside out: first the domain, then the ports and the use case, then the adapters and the wiring, and finally the tests. This order ensures the core exists and works before any technology decision is made.

H3: Step 1: The Domain, With No Dependencies

The domain holds the business rules and imports nothing from a framework, a database or the web. In the example, the credit limit rule lives inside Customer, and not in a service, a controller or a SQL query.

java
public class Customer {
    private final String id;
    private final BigDecimal creditLimit;
    private BigDecimal creditUsed;

    public Customer(String id, BigDecimal creditLimit, BigDecimal creditUsed) {
        this.id = id;
        this.creditLimit = creditLimit;
        this.creditUsed = creditUsed;
    }

    // Business rule: no framework, no database
    public void reserveCredit(BigDecimal amount) {
        BigDecimal newTotal = creditUsed.add(amount);
        if (newTotal.compareTo(creditLimit) > 0) {
            throw new CreditLimitExceededException(id);
        }
        this.creditUsed = newTotal;
    }

    public String id() { return id; }
    public BigDecimal creditUsed() { return creditUsed; }
}

The order is a simple record, with a factory that generates the identifier:

java
public record Order(String id, String customerId, BigDecimal total) {
    public static Order create(String customerId, BigDecimal total) {
        return new Order(UUID.randomUUID().toString(), customerId, total);
    }
}

Notice what is missing: no annotations, no Spring or JPA imports. If the credit rule changes (for example, to count open orders), the change lives in one place and can be tested in milliseconds. This is the central idea of the pattern: what changes for business reasons stays separate from what changes for technology reasons.

Step 2: Ports and the Use Case

Ports are interfaces that belong to the core. The inbound port describes the use case; the outbound ports describe what the core needs from the outside world. The use case orchestrates: it loads, applies the rule, saves and notifies, without knowing how any of that is done.

java
// Inbound port (driving)
public interface PlaceOrder {
    Order execute(Command command);
    record Command(String customerId, BigDecimal total) {}
}

// Outbound ports (driven)
public interface CustomerRepository {
    Customer findById(String id);
    void save(Customer customer);
}
public interface OrderRepository { void save(Order order); }
public interface BillingGateway { void issueCharge(String orderId, BigDecimal amount); }
public interface Notifier { void orderPlaced(Order order); }

The use case implements the inbound port and receives the outbound ports through its constructor:

java
public class PlaceOrderService implements PlaceOrder {
    // fields and constructor receive CustomerRepository, OrderRepository,
    // BillingGateway and Notifier (constructor injection)

    @Override
    public Order execute(Command command) {
        Customer customer = customers.findById(command.customerId());
        customer.reserveCredit(command.total());          // rule in the domain
        Order order = Order.create(customer.id(), command.total());
        orders.save(order);
        customers.save(customer);
        billing.issueCharge(order.id(), order.total());
        notifier.orderPlaced(order);
        return order;
    }
}

A design caution: name ports by intent (PlaceOrder, BillingGateway), not by table or technology. A post by Alexander Petrov (January 2026) describes the mistake of defining ports per entity or table, which multiplies interfaces without reflecting what the business does.

Step 3: Adapters and Wiring

Adapters are the only part that knows technology. The inbound adapter translates HTTP into the inbound port; the outbound ones implement the ports with a database, a gateway and email. The wiring, in a single place, connects everything. (The Spring snippets below are illustrative and simplified.)

The inbound adapter, a REST controller, converts the request into a command and calls the port:

java
@RestController
@RequestMapping("/orders")
class OrderController {
    private final PlaceOrder placeOrder;   // depends on the port, not on the service

    OrderController(PlaceOrder placeOrder) {
        this.placeOrder = placeOrder;
    }

    @PostMapping
    ResponseEntity<OrderResponse> place(@RequestBody OrderRequest req) {
        Order order = placeOrder.execute(
            new PlaceOrder.Command(req.customerId(), req.total()));
        return ResponseEntity.status(HttpStatus.CREATED).body(new OrderResponse(order.id()));
    }

    record OrderRequest(String customerId, BigDecimal total) {}
    record OrderResponse(String id) {}
}

The outbound persistence adapter translates between the domain model and the JPA entity; the entity stays at the edge, and the domain never sees it:

java
@Repository
class CustomerJpaAdapter implements CustomerRepository {
    private final CustomerJpaRepository jpa;   // Spring Data, works with CustomerEntity

    public Customer findById(String id) {
        CustomerEntity e = jpa.findById(id).orElseThrow();
        return new Customer(e.getId(), e.getCreditLimit(), e.getCreditUsed());
    }
    // save(...) converts Customer back into a CustomerEntity
}

The wiring connects the adapters to the core in a single place:

java
@Configuration
class OrdersConfig {
    @Bean
    PlaceOrder placeOrder(CustomerRepository customers, OrderRepository orders,
                          BillingGateway billing, Notifier notifier) {
        return new PlaceOrderService(customers, orders, billing, notifier);
    }
}

The flow of a request, in five steps: (1) the controller receives the POST and builds the command; (2) it calls the PlaceOrder port; (3) the use case loads the customer through the outbound port; (4) the domain applies the limit rule; (5) the use case saves, charges and notifies through the outbound ports. Changing the billing gateway means writing a new adapter; the core does not change.

Step 4: Testing the Core Without a Database

Because the core only knows ports, the use case test uses in-memory implementations in place of the adapters. There is no database, no network and no Spring: the test runs in milliseconds and validates the business rule end to end.

The fake adapters are small: a repository backed by a map, a billing gateway that only counts calls. The test, in JUnit 5, looks like this:

java
@Test
void rejectsOrderAboveLimitWithoutBillingOrSaving() {
    customers.save(new Customer("c1", new BigDecimal("1000"), new BigDecimal("500")));

    assertThrows(CreditLimitExceededException.class,
        () -> useCase.execute(new PlaceOrder.Command("c1", new BigDecimal("600"))));

    assertTrue(orders.data.isEmpty());   // nothing was saved
    assertEquals(0, billing.calls);      // nothing was charged
}

This is the benefit AWS cites: unit tests without infrastructure dependencies. The division of responsibilities is clear: the domain and the use case are covered by fast tests with fakes; the adapters (JPA query, gateway call, REST serialization) get a few integration tests that check the technology is wired correctly.

In projects run by NextAge’s Software Factory, the quality stage includes dedicated QA and automated testing, as described on the service page; a core that can be tested without a database makes that work easier.

Folder Structure and Rules That Keep the Architecture Intact

The folder structure should make the direction of dependencies visible: domain and application in the center, adapters and wiring at the edge. Two or three simple rules, checked automatically, are worth more than a pretty diagram.

orders/
├── domain/             (Customer, Order, exceptions; no framework imports)
├── application/
│   ├── port/in/        (PlaceOrder)
│   ├── port/out/       (CustomerRepository, OrderRepository, BillingGateway, Notifier)
│   └── PlaceOrderService
└── adapters/
    ├── in/rest/        (OrderController)
    ├── out/jpa/        (CustomerJpaAdapter, entities)
    ├── out/billing/    (billing gateway adapter)
    └── config/         (wiring)

The rules that keep the structure standing:

  • The domain and the application import no framework, ORM or third-party SDK.
  • Transport objects (request DTOs and JPA entities) stay at the edge; the domain works with its own objects, and the adapter converts.
  • Ports are defined by intent and belong to the core, not to the infrastructure.
  • Business rules never live in an adapter: if an adapter starts deciding something about the business, the logic has leaked.
  • Check dependencies automatically (for example, with architecture tests in the pipeline), so the rule does not depend on manual review.

Hexagonal, Clean Architecture, Onion and Layers: What Is the Difference?

Hexagonal, Onion and Clean Architecture share the same principle: dependencies point inward and the domain is isolated from infrastructure. The difference is in vocabulary and granularity: hexagonal describes the core’s conversation with the outside through ports and adapters; Onion and Clean detail concentric layers.

Hexagonal Onion Clean Architecture Layered (traditional)
Origin Cockburn, 2005 Jeffrey Palermo, 2008 Robert C. Martin, 2012 Earlier; classic pattern
Metaphor Hexagon with ports Concentric rings Concentric circles Stack of layers
Focus How the core communicates with the outside Domain at the center, layers around it Business rules, use cases and entities in layers Separation by technical responsibility
Direction of dependencies Inward Inward Inward Downward (UI, business, data)

Years and authorship according to Wikipedia, which also records a criticism by Martin Fowler: the pattern’s symmetry hides the natural asymmetry between a service provider and a service consumer. In practice, many teams use hexagonal as a base and borrow the use case concept from Clean. In layered architecture, dependencies run down to the database, and that is what tends to tie business rules to infrastructure. Choose by principle, not by label: Thoughtworks argues that the principles matter more than the name.

When to Use (and When Not to Use) Hexagonal Architecture

Use it when the system has relevant business rules, several inputs or outputs, technologies likely to change, or a long life. Avoid it in simple CRUD apps, prototypes and stable systems, where ports and adapters become extra code with no benefit. The cost is real: more classes, more mapping and a learning curve.

What the Sources Say

AWS lists as favorable situations: fully testable components, several kinds of clients using the same logic, UI or database components that change from time to time, and several input sources and output destinations. As costs, it points to maintenance overhead (the adapter code only pays off in those cases) and added latency. The Manning book Clean Applications with Hexagonal Architecture adds that the pattern tends to be worth more in systems that will grow, integrate with many technologies or outlive their first implementation, and may be overkill for simple CRUD apps and prototypes. JAVAPRO (July 2026) makes the same caveat for simple projects. For the debate on excess, Overengineering in Onion/Hexagonal Architectures, by Victor Rentea, is worth reading; it warns about applying these architectures strictly by the book.

Three Questions to Decide

An editorial proposal by NextAge:

  1. Is the business rule complex enough to deserve being tested on its own?
  2. Is there more than one input or output (API and queue, database and external service), or a technology likely to change?
  3. Will the system live for years and grow?

If the answer is “no” to all three, a simpler structure is probably enough. If it is “yes” to two or more, the pattern tends to pay off.

Common Mistakes

Defining ports per table instead of per use case; leaving business rules in the adapter; leaking database types (JPA entities) into the domain; creating an interface for everything, even when a second implementation is impossible; and forgetting the wiring, letting the core instantiate its own adapters.

When the Decision Happens (and the Legacy Case)

This decision is usually made early. In NextAge’s Software Factory, the Architecture and Design stage defines the stack, the architecture and the data model before sprint development, according to the service page.

If your case is a legacy system where business rules and database are intertwined, legacy system modernization is one of the project types handled by the Software Factory.

Frequently Asked Questions About Hexagonal Architecture

What is hexagonal architecture?

Hexagonal architecture, or ports and adapters, is a style that isolates business rules from the database, the interface and external services. The core defines ports (interfaces) and the infrastructure plugs into them through adapters, which makes testing and swapping technologies easier.

What is the difference between a port and an adapter?

A port is an interface defined by the core that describes what the application offers (inbound port) or what it needs from the outside (outbound port). An adapter is the concrete implementation of a port, tied to a technology, such as a REST controller or a JPA repository.

Is hexagonal architecture the same as Clean Architecture?

No, but they share the principle that dependencies point inward, with the domain isolated from infrastructure. Hexagonal (Cockburn, 2005) emphasizes ports and adapters; Clean Architecture (Robert C. Martin, 2012) details concentric layers and use cases. Many teams combine ideas from both.

When is hexagonal architecture not worth using?

In simple CRUD apps, prototypes and stable systems where infrastructure rarely changes, the pattern adds classes, mapping and maintenance with no clear benefit. AWS points to maintenance overhead and added latency. It pays off with complex rules, several inputs and outputs, or a long life.

Do I need DDD to apply hexagonal architecture?

It is not required, but they fit well together. AWS notes that hexagonal works especially well with Domain-Driven Design, since the core can represent the domain model of a context. Without DDD, you can still isolate business rules through ports and adapters.

Does hexagonal architecture work in monoliths and microservices?

Yes. It organizes the inside of an application, so it applies to a monolith (including a modular one) and to each service in a microservices architecture. It does not define how many services exist, but how each one separates business rules from infrastructure.

How do you test an application built with hexagonal architecture?

Test the domain and the use cases with fast unit tests, using in-memory implementations of the outbound ports. Test the adapters separately, with a few integration tests that check the connection to the database, gateway or API. This way, business rules are validated without infrastructure.

Conclusion: From the Example to Your Decision

Hexagonal architecture separates what changes for business reasons from what changes for technology reasons: the core defines ports, adapters implement them, and dependencies point inward. The gain is testability and technology freedom; the cost is extra code and discipline. It pays off when the system has relevant rules and a long life, and it is overkill for a simple CRUD app.

Before adopting it, apply the three decision questions to your case and start with the shortest path: one use case, its ports and two adapters.

If you need a team to take over the delivery of a system, from discovery to support, learn about NextAge’s Software Factory and tell us your challenge.

As últimas novidades e tendências da tecnologia.

The latest technology news and trends.

Formulario EN

Newsletter NextAge
Get the best news from the world of technology in your email!

Formulario PT

Newsletter NextAge
Receba as melhores notícias do mundo da tecnologia em seu e-mail!