Course contents

10. Software Architecture Lesson 3 of 10

Hexagonal Architecture

Ports and adapters in 3D: drive one core from HTTP, a queue and tests, and swap the SQL adapter for a test double while the database is down.

15 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • The application core talks to the outside world only through ports defined in its own language.
  • Driving adapters (HTTP, queue consumers, tests) call driving ports; driven adapters (database, payments) implement driven ports.
  • Every adapter depends on the core; the core depends on no adapter.
  • New channels and new technologies are new adapters, not changes to the core.
  • Test doubles plug into driven ports, so rules can be tested without infrastructure; adapters still need integration tests.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Hexagonal architecture, introduced by Alistair Cockburn in 2005 and also called ports and adapters, places the application (its use cases and business rules) in the middle and lets it interact with the outside world only through ports: interfaces defined by the application, in its own vocabulary.

  • Driving (primary) ports describe what the application offers: IPlaceOrder.
  • Driven (secondary) ports describe what the application needs: IOrderStore, IPayments.

Adapters connect a port to a technology. Driving adapters (an HTTP endpoint, a queue consumer, a CLI, a test) call driving ports. Driven adapters (an EF Core store, a payment SDK wrapper, an SMTP sender) implement driven ports. The hexagon shape has no meaning beyond leaving room to draw several ports.

Why it exists

Cockburn's goal was to let an application be driven equally by users, programs, automated tests or batch scripts, and to develop and test it in isolation from its eventual devices and databases. Business logic tangled with UI and database code cannot be tested without them, and every new channel tends to copy logic. Separating the core behind ports means one core can serve many channels and many technologies.

How it works

Ports in the core.

// Ordering.Core
public interface IPlaceOrder { Task<OrderId> Handle(PlaceOrder command, CancellationToken ct); }
public interface IOrderStore { Task Save(Order order, CancellationToken ct); }
public interface IPayments { Task<ChargeResult> Charge(OrderId id, Money amount, CancellationToken ct); }

Adapters outside. An ASP.NET Core endpoint maps JSON to a PlaceOrder command and calls IPlaceOrder. A hosted service reading a queue does the same for marketplace orders. SqlOrderStore : IOrderStore uses EF Core; CardPayments : IPayments wraps the provider's SDK.

Configuration. The host chooses the adapters, typically with dependency injection: production registers SqlOrderStore; a test registers InMemoryOrderStore. The core's code is identical in both.

Dependencies versus calls. At runtime the core calls the payment adapter. In source code the adapter references the core's port. Every arrow points at the hexagon, which is the same dependency inversion clean architecture builds on.

Test doubles. Because driven ports are small, application-shaped interfaces, fakes are easy to write: a list behind IOrderStore, a stub that approves charges behind IPayments. Tests then drive the core through its driving port with no network or database.

When to use it

  • Applications with several entry points (API, messages, scheduled jobs) that must share one set of rules.
  • Systems whose infrastructure is likely to change or has variants per environment or market.
  • When fast, reliable tests of business rules matter.
  • As the structure inside a service or module that has real domain logic.

When not to

  • Thin CRUD services where the "core" would just forward to the database.
  • Throwaway prototypes.
  • When ports would mirror one technology's API exactly; then they add a layer without decoupling anything.

Trade-offs

Choice You gain You pay
Ports in the application's language Replaceable adapters, technology-free core Designing the abstraction; mapping at each adapter
Test doubles behind driven ports Fast, deterministic tests Doubles can drift from real behaviour; adapters need their own tests
Many fine-grained ports Precise seams More interfaces and wiring to navigate
Few coarse ports Less ceremony Bigger adapters, broader fakes

Alternatives

  • Clean / onion architecture: the same inversion, with prescribed inner rings (entities, use cases).
  • Layered architecture: simpler, but the domain depends on data access.
  • Vertical slices: organise by feature; slices may still use ports where they need to isolate infrastructure.
  • Functional core, imperative shell: pure business functions in the middle, all I/O in a thin outer shell; similar goals with less interface ceremony.

Failure modes

  • Leaky ports: IQueryable, EF entities or HTTP status codes appear in port signatures, so the core depends on a technology after all.
  • Fakes that lie: an in-memory store that ignores uniqueness constraints or transactions lets bugs pass that the real database would reject.
  • Port per class: every helper gets an interface, so the seams no longer mark real boundaries.
  • Logic in adapters: business decisions drift into controllers or repositories, and different channels behave differently.

In production

Keep driving adapters thin: parse, authorise, map, call the port, map the result. Put transactions and orchestration in the core's use cases. Test the core with doubles, and test each driven adapter with integration tests against the real technology (Testcontainers for databases and brokers, the provider's sandbox for payments). Contract tests between the double and the real adapter help keep fakes honest.

Common misconceptions

  • "Hexagonal means six ports." The hexagon is just a drawing with room for several ports.
  • "Ports are repositories." Driven ports include any outside need: payments, clocks, messaging, notifications. Driving ports describe the application's use cases.
  • "Test doubles replace integration tests." They test the rules. Only the real adapter against real infrastructure proves the mapping and the SQL.
  • "The core calls nothing outside." It calls through ports at runtime; it just does not reference the implementations.

Interview angle

Draw the core with a driving port on one side and driven ports on the other, put adapters around it and point every dependency at the core. Explain how this enables multiple channels and fast tests, and contrast it with layered architecture's downward dependency on data. Strong answers mention test doubles and their limits, port design in the domain's language, and the relationship to clean and onion architecture.

Model assumptions

The walk-throughs, the second driver and the dependency view are scripted illustrations with hand-placed packets, slowed to 30–40 ms per hop. The live steps are simulated: adapters, ports and the core are servers joined by 0 ms links (in-process calls); ports take essentially no time and are drawn as nodes only to make the path visible; the core takes about 1 ms. The shopper is 20 ms away, the payment provider 30 ms (20 ms of work), SQL Server 1 ms (5 ms per query, 8 connections). The core saves an order before charging it. Test doubles are in-memory components taking about 0.05 ms. Shopper arrivals are random (Poisson); tests send calls at a constant rate. Numbers show behaviour and orders of magnitude, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. An application core with ports

    Hexagonal architecture puts the application, its use cases and business rules, in the middle and lets it talk to the outside only through ports. A port is an interface named in the application’s own language.

    IPlaceOrder is a driving port: what the outside can ask the application to do. IOrderStore and IPayments are driven ports: what the application needs from the outside. The core contains no HTTP, no SQL, no SDKs.

    Scene: Inside the dashed hexagon area: the Ordering core with the driving port IPlaceOrder on its left and the driven ports IOrderStore and IPayments on its right.

    Key idea: The core talks to the world only through ports it defines in its own terms.

  2. 2. Driving adapters on the left, driven on the right

    Adapters translate between a port and a technology. Driving (primary) adapters start the conversation: the HTTP adapter turns POST /orders into a call on IPlaceOrder, the queue consumer turns a message into the same call, and a test calls the port directly.

    Driven (secondary) adapters are called by the application: the SQL adapter implements IOrderStore with EF Core, the payment adapter implements IPayments with the provider’s SDK.

    Scene: Three conversations start on the left: a shopper request into the HTTP adapter, a message into the queue consumer and a test calling the driving port. Then the core’s driven ports call the SQL adapter and the payment adapter on the right.

    Key idea: Driving adapters call into the application; driven adapters are called by it.

  3. 3. One order through the hexagon

    The shopper posts an order. The HTTP adapter maps the request to a PlaceOrder command and calls IPlaceOrder. The core applies its rules, saves the order as pending through IOrderStore, which the SQL adapter turns into an INSERT, and then charges the card through IPayments, which the payment adapter turns into a provider API call.

    The answer goes back the same way. (Scripted illustration; in-process hops are slowed down.)

    Scene: A request travels from the shopper through the HTTP adapter and IPlaceOrder into the core, out through IOrderStore and the SQL adapter to SQL Server and back, then out through IPayments and the payment adapter to the payment provider and back, before the answer returns to the shopper.

    Key idea: A request enters through a driving adapter and port, and leaves through driven ports and adapters.

  4. 4. Another driver, the same port

    Orders from a marketplace arrive as messages. A queue consumer, another driving adapter, reads each message and calls the same IPlaceOrder port.

    From the port inward, nothing differs: the same core code, the same driven ports. Adding a channel meant writing one adapter, not a second copy of the order logic.

    Scene: A message travels from the marketplace queue to the queue consumer, which calls IPlaceOrder. The core then follows exactly the same path as for the web order, and the consumer acknowledges the message at the end.

    Key idea: New ways to drive the application are new adapters on an existing port.

  5. 5. Every dependency points at the hexagon

    Now look at source-code dependencies instead of calls. Driving adapters reference the port they call, so their arrows point in. Driven adapters implement the core’s ports (SqlOrderStore : IOrderStore), so their arrows point in too, against the direction of the calls.

    The core references none of the adapters. That is what makes them interchangeable.

    Scene: The arrows now show dependencies. Pulses travel along five arrows, all into the hexagon: from the three driving adapters to IPlaceOrder, and from the SQL and payment adapters to the ports they implement.

    Key idea: All adapters depend on the core; the core depends on no adapter.

  6. 6. In production: real adapters, real latency

    Back to runtime calls, now simulated: shoppers place 20 orders per second. Each takes about 130 ms. Almost all of it is outside the core: 40 ms of network to the shopper, about 80 ms for the payment provider (network plus its own work), and about 7 ms for SQL Server.

    The core and the ports add about a millisecond. The architecture shapes the code; the adapters’ technologies set the latency.

    Scene: Shoppers send 20 orders per second through the HTTP adapter, the core, the SQL adapter and the payment adapter. Every order succeeds in about 130 ms, mostly spent on the network and at the payment provider.

    Key idea: Ports are in-process calls; the cost lives in the adapters and what they talk to.

  7. 7. SQL Server is down, and the tests fail too

    SQL Server goes down. Every order now fails: the core saves before it charges, so no card is charged for an order that was never stored.

    The test suite is running too, at 10 calls per second, through the real SQL adapter. Every one of those tests fails as well, although nothing is wrong with the order rules. Tests that need a running database and a payment sandbox are slow, flaky and test the wrong thing.

    Scene: SQL Server is offline. Orders from shoppers and calls from the test suite all fail at the SQL adapter; the payment provider receives nothing.

    Key idea: Tests wired to real infrastructure fail for infrastructure reasons, not because the rules are wrong.

  8. 8. Swap the driven adapters for test doubles

    The test project plugs different adapters into the same ports: an InMemoryOrderStore (a list) for IOrderStore and a FakePayments that approves every charge for IPayments. Production traffic is paused; the suite runs at 50 calls per second.

    SQL Server is still down, yet every test passes, each in about a millisecond, all of it the core’s own work: no network, no database, no provider. The core cannot tell the difference, which is the point.

    Scene: The two driven ports now connect to an in-memory store and a fake payment service. The test suite calls the core at 50 calls per second and every call succeeds in about a millisecond, while SQL Server is still offline and unused.

    Key idea: Because the core only knows ports, test doubles plug in where the real adapters were.

  9. 9. Ports in the middle, adapters at the edge

    SQL Server is back and the real adapters are plugged in again: orders succeed in about 130 ms. Hexagonal architecture gives you one core reachable through many driving adapters and served by replaceable driven adapters, with every dependency pointing at the core.

    It is the same inversion as clean architecture, without prescribing inner rings. Keep a few integration tests for the real adapters: test doubles prove the rules, not the SQL.

    Scene: The real SQL and payment adapters are connected again and SQL Server is healthy. Shoppers send 20 orders per second and all succeed in about 130 ms.

    Key idea: One core, many adapters: swap the technology at the edge without touching the rules.