Hexagonal architecture

Also known as: ports and adapters

On this page 7

Hexagonal architecture, also called ports and adapters, is a software architecture style that places the application core at the center and connects it to the outside world only through explicitly defined ports, which adapters implement for specific technologies. In programming, it is a key pattern within the Architecture topic because it keeps business rules independent of databases, frameworks, user interfaces and messaging systems.

Alistair Cockburn introduced the idea in the early 2000s to solve a recurring problem: business logic leaking into user interface code and database access layers. The hexagon shape has no special meaning beyond showing that an application can have many symmetric sides, each representing a different way to interact with it.

How ports and adapters separate the core

Hexagonal architecture works by enforcing a single rule: dependencies point inward toward the core. The core contains domain entities, business rules and use cases, and it knows nothing about HTTP, SQL, message brokers or file formats. Every interaction with the outside world passes through a port, which is an interface owned and defined by the core.

An adapter is a concrete component that translates between a port and a specific technology. A REST controller translates HTTP requests into calls on a use case, while a database adapter translates repository calls into SQL statements. Because the core defines the interfaces, swapping PostgreSQL for MongoDB or a web interface for a command-line tool requires only a new adapter, not changes to business logic.

The following table describes the main building blocks and their responsibilities.

ElementResponsibilityTypical example
Application coreHolds domain model and use casesOrder pricing and validation rules
Driving portInterface the outside uses to call the corePlaceOrderUseCase interface
Driven portInterface the core uses to reach outsideOrderRepository interface
Driving adapterInvokes the core from external inputREST controller, CLI command, test
Driven adapterImplements a driven port with technologySQL repository, SMTP mail sender
ConfiguratorWires adapters to ports at startupComposition root, DI container
Building blocks of hexagonal architecture

Driving and driven sides of the hexagon

Ports fall into two groups, and distinguishing them is essential to applying the pattern correctly. Driving ports, sometimes called primary or inbound ports, describe what the application offers: the use cases that actors such as users, schedulers or other systems can trigger. Driven ports, also called secondary or outbound ports, describe what the application needs from its environment, such as persistence, notifications or payment processing.

The direction of control differs between the two sides, but the direction of source code dependency stays the same. On the driving side, the adapter calls the core directly. On the driven side, the core calls an interface, and the adapter implements it, which is a direct application of the dependency inversion principle from SOLID principles.

This table contrasts the two sides of the hexagon.

AspectDriving sideDriven side
Alternative namesPrimary, inbound, left sideSecondary, outbound, right side
Who initiatesExternal actor calls the coreCore calls external resource
Port definesOperations the core offersOperations the core requires
Adapter roleCalls the portImplements the port
Test replacementTest harness drives use casesIn-memory fakes or mocks
Comparison of driving and driven sides

Hexagonal architecture belongs to a family of dependency-inverted, domain-centric styles that share one goal: protecting business logic from infrastructure. Onion architecture and clean architecture came later and add more prescriptive inner layers, whereas classic layered architecture often lets the domain depend on the persistence layer below it.

The differences are mostly about how much internal structure each style prescribes. Hexagonal architecture says almost nothing about the inside of the core; it focuses on the boundary between inside and outside. Domain-driven design is complementary rather than competing, because it supplies the modeling techniques for the core that the hexagon protects.

StyleCore ideaInternal structureDependency direction
Hexagonal architecturePorts and adapters at the boundaryNot prescribedInward to core
Onion architectureConcentric rings around domain modelDomain, services, infrastructureInward to center
Clean architectureEntities, use cases, adapters, frameworksFour named circlesInward to entities
Layered architecturePresentation, business, data layersHorizontal layersDownward to data
MVCModel, view, controller rolesUser interface concern onlyVaries by framework
How related architecture styles differ

Applying hexagonal architecture in practice

Teams typically apply the pattern by organizing packages or modules by role: a domain module, an application module containing use cases and port interfaces, and separate adapter modules for each technology. Build tools or architecture tests such as ArchUnit can then enforce the dependency rule automatically, failing the build when a domain class imports a framework annotation.

Wiring happens in a composition root, usually at application startup, where dependency injection connects each driven port to its chosen adapter. The same core can therefore run with a real database in production and an in-memory adapter in tests, which makes use case tests fast, deterministic and free of infrastructure setup.

The decision table below summarizes when the pattern pays off.

SituationRecommendationReason
Complex, long-lived business domainStrongly recommendedRules outlive frameworks and databases
Several input channels for one logicRecommendedEach channel becomes one adapter
Expected infrastructure migrationRecommendedOnly adapters change
Simple CRUD applicationUsually unnecessaryIndirection adds cost without benefit
Short-lived prototypeNot recommendedSpeed matters more than isolation
When to choose hexagonal architecture

Limitations and common mistakes

The main trade-off is additional indirection: more interfaces, more mapping code and more files to navigate. For thin applications that mostly move data between a form and a table, this overhead can exceed the benefit, and teams sometimes produce ceremony without real isolation.

Experienced practitioners watch for several recurring errors that undermine the pattern.

MistakeConsequenceCorrection
Framework annotations in domain classesCore coupled to infrastructureMove mapping into adapters
Ports shaped like database tablesPersistence leaks into coreDesign ports around use cases
One port per adapter methodInterface explosionGroup operations by capability
Adapters calling each other directlyHidden coupling outside coreRoute interactions through the core
Sharing entities as API payloadsExternal contracts tied to domainUse dedicated transfer objects
Frequent mistakes and how to correct them

A frequent misconception is that hexagonal architecture requires exactly six ports or a specific folder layout. The number of sides is arbitrary, and the pattern is defined by the dependency rule, not by naming conventions.

Stripped to the essentials

Think of the application as a power tool with a standard socket. The tool does the real work, and different plugs let it connect to different power sources. You can travel to another country and simply change the plug adapter, while the tool itself stays exactly the same.

In software, the important business rules sit in the middle and never talk directly to databases or websites. They talk only through agreed connection points. The key idea is that technology can change without touching the rules that make the business work.

Where it is applied

A development team at a mid-sized insurance company maintains a claims processing service that must accept claims from a web portal, a mobile app and nightly batch files sent by partner brokers. The team places claim validation, fraud scoring and payout calculation in the core and defines a single driving port, SubmitClaim, plus driven ports for policy lookup, document storage and payment.

Three driving adapters translate web requests, mobile API calls and batch file records into SubmitClaim calls. When the company later moves document storage from an on-premises file server to cloud object storage, the team writes one new driven adapter in about two weeks, and the core code and its roughly 800 use case tests remain unchanged. The tests run against in-memory adapters in under a minute, which lets the team release changes to claim rules several times per week.