Hexagonal architecture is a software architecture pattern that separates an application's essential behavior from the technologies through which users, external systems, and infrastructure interact with it. The application communicates across its boundary through ports, which describe purposeful interactions, and adapters, which translate those interactions into particular technologies or external interfaces. Its central aim is to let application behavior be developed and tested without requiring a particular user interface, database, or deployment environment.
Origin and terminology
Alistair Cockburn described hexagonal architecture in 2005 under the alternative name ports and adapters. The proposal addressed a recurring problem: business logic becoming entangled with user-interface code or persistence mechanisms, making an application difficult to test independently of those mechanisms.
The hexagon is a diagrammatic convention, not a requirement for six components, six layers, or six interfaces. Its shape provides room to draw multiple kinds of external interaction without suggesting that an application has only a top, a middle, and a bottom. The significant distinction is between the inside, where application behavior resides, and the outside, where technology-specific interactions occur.
The architecture is not tied to a particular programming language, framework, or deployment model. It can organize a single executable, a modular application, or an individual service.
Core structure
Application core
The application core contains behavior that should remain meaningful when external technologies change. Depending on the system, this includes business rules, domain objects, validation of business invariants, and orchestration of application use cases.
For example, an order-processing core might determine whether an order can be submitted, calculate its total, and coordinate stock reservation. It should not need to understand HTTP routing, database connection configuration, or a payment provider's proprietary message format.
The pattern does not prescribe a single internal organization. The core may contain distinct domain and application layers, but that separation is an additional design choice rather than a requirement of the hexagonal diagram.
Ports
A port defines a coherent interaction across the application boundary. It describes what the application offers to an external actor or what it needs from an external capability.
Ports are often divided into two categories:
- Driving, primary, or inbound ports expose operations through which an external actor initiates application behavior, such as submitting an order or requesting an account balance.
- Driven, secondary, or outbound ports describe capabilities the application uses, such as retrieving stored orders, sending a notification, or obtaining the current time.
The terminology varies between implementations. “Inbound” and “outbound” describe responsibility for initiating an interaction, not the direction of every message or return value.
A port is an architectural contract, not a network port. It may be expressed as a programming-language interface, a function signature, a set of operations, or a messaging contract. It need not correspond one-to-one with a class, endpoint, or external system.
Adapters
An adapter connects a port to a concrete external mechanism. It translates representations and interaction styles while keeping technology-specific details outside the core.
A driving adapter might be:
- A web controller that translates an HTTP request into an application operation.
- A command-line interface that invokes the same operation.
- A message consumer that turns an incoming message into an application command.
- A test harness that directly exercises a use case.
A driven adapter might implement persistence using a relational database, call an external payment service, or provide an in-memory substitute for testing.
Several adapters can serve the same port. For example, a notification port may have email and text-message implementations, provided both satisfy the behavior the port requires.
Dependency direction and execution flow
A central implementation principle is that the core should not depend on concrete external adapters. External mechanisms depend on contracts defined by, or aligned with, the application’s needs.
This commonly uses the dependency inversion principle. Instead of an application service importing a specific database client, it depends on an abstraction such as an order repository. A database adapter implements that abstraction.
Execution flow and source-code dependency are therefore different:
- A web adapter calls an application operation.
- The application calls an outbound repository port.
- A concrete repository adapter executes a database operation.
- Results return through the same boundaries.
Although execution passes from the core into the database adapter, the core's source code need not reference the adapter's implementation.
Dependency injection is a common way to supply concrete adapters at startup, but no dependency-injection framework is required. Ordinary constructor arguments, function parameters, or explicit assembly code can establish the same relationships. The assembly location is often called the composition root.
Example: placing an order
An order application might define the following boundary:
| Element | Responsibility |
|---|---|
Inbound port: PlaceOrder |
Accept an order request and return an application-level result |
| Application service | Coordinate validation, stock reservation, and order persistence |
| Domain objects | Enforce order rules and permitted state changes |
Outbound port: OrderRepository |
Retrieve and store orders |
Outbound port: Inventory |
Request stock reservation |
| HTTP adapter | Convert requests and responses into application inputs and outputs |
| Database adapter | Implement order persistence |
| Inventory-service adapter | Translate reservation requests into the external service's protocol |
The HTTP adapter handles transport details such as request parsing and status codes. The core decides whether an order is valid. The database adapter handles queries, storage mappings, and database-specific failures.
A test can invoke PlaceOrder with in-memory adapters. Another driving adapter, such as a batch-import process, can invoke the same operation without duplicating the ordering rules.
This separation does not make external systems interchangeable automatically. A replacement must satisfy the port's behavioral contract, including relevant consistency, failure, and performance expectations.
Testing
Independent testing is a central motivation for hexagonal architecture. Business behavior can be exercised without starting a web server, connecting to a production database, or contacting an external service.
Different tests establish different properties:
- Unit tests check small pieces of domain or application behavior.
- Application-level tests drive inbound ports while substituting controlled implementations of outbound ports.
- Integration tests check concrete adapters against real infrastructure or representative external environments.
- Contract tests check whether adapters satisfy agreed interaction and behavioral expectations.
- End-to-end tests check selected complete paths through the assembled application.
Test doubles are useful but can give false confidence when their behavior differs from real infrastructure. An in-memory repository, for example, may not reproduce uniqueness constraints, concurrent updates, or transaction behavior. Hexagonal architecture makes isolation easier; it does not eliminate the need to test external integrations.
Relationship to other architectural approaches
Layered architecture
Traditional layered designs often depict presentation, business logic, and persistence in a vertical stack. Hexagonal architecture emphasizes the inside–outside boundary instead: both presentation mechanisms and persistence mechanisms are external to application behavior.
The approaches are not mutually exclusive. A layered implementation can follow hexagonal principles if its business code remains independent of concrete infrastructure.
Domain-driven design
Domain-driven design concerns modeling software around a business domain and defining appropriate model boundaries. Hexagonal architecture concerns how an application interacts with its environment. They are complementary, but neither requires the other. An application does not need a rich domain-object model to use ports and adapters.
Onion and clean architecture
Onion architecture and clean architecture share the goal of keeping central policy independent of external mechanisms. They provide more explicit concentric organizations and dependency rules. They are closely related approaches, rather than exact synonyms for hexagonal architecture.
Microservices
Hexagonal architecture is not a synonym for microservices. A service can use ports and adapters internally, and a monolithic application can do the same. The pattern does not determine deployment boundaries, service discovery, or interservice communication.
Applications and limitations
The pattern is particularly relevant when business behavior must be accessible through multiple interfaces, external integrations change over time, or substantial application testing should run independently of infrastructure.
Its main costs are additional contracts, translation code, and architectural discipline. In a small application with little business behavior, introducing an interface and adapter for every operation can add indirection without a corresponding benefit. Effective ports represent meaningful application conversations rather than mechanically wrapping every library call.
Boundary design also involves trade-offs:
- Leaking external representations: exposing database-specific objects or transport-specific response types through ports can couple the core to infrastructure despite an apparently separated directory structure.
- Overgeneralized contracts: attempting to support every possible database or provider can produce abstractions that are either too weak or unnecessarily complex.
- Transaction boundaries: separating persistence behind ports does not determine how atomic changes should be coordinated. Transaction ownership and consistency guarantees still require explicit design.
- Distributed failures: adapters cannot hide all effects of latency, partial failure, retries, and duplicate delivery. Where relevant, application behavior must account for idempotence and recovery.
- Semantic differences between adapters: two implementations with identical method signatures may differ in ordering, durability, or consistency. Those differences can matter to correctness.
- Framework coupling: persistence annotations, framework base classes, and infrastructure exception types can introduce dependencies into the core even when code is organized into separate packages.
Hexagonal architecture is therefore principally a way to manage dependency and change. It does not itself establish security, scalability, fault tolerance, or correctness; each of those properties requires additional design and verification.