Hexagonal Architecture: Ports & Adapters Pattern for Decoupled, Testable Systems
This article introduces Hexagonal Architecture (Ports & Adapters), explaining its core components—domain model, inbound/outbound ports, and adapters—and demonstrates how it isolates business logic from infrastructure, enabling easier testing, multiple entry points, and low-cost technology swaps, with comparisons to Layered, Clean, and CQRS architectures.
Reading font
In backend architecture evolution, the traditional three-layer architecture (Controller-Service-Repository) often maintains a clear structure early on. As business iterates, two typical problems emerge:
Business logic leakage: Parameter validation, permission checks, and process orchestration scatter across controllers and services; domain rules are no longer centralized, leading to inconsistent implementations across different entry points (web, scheduled tasks, messaging).
Technology implementation seepage: Services directly depend on ORM sessions, annotations, or transaction APIs, so changing the persistence solution requires modifying business code.
The common root cause is that high-level modules (business logic) depend on low-level modules (databases, web frameworks) at compile time. To solve this "business-technology coupling", Hexagonal Architecture (Ports & Adapters) was proposed by Alistair Cockburn in 2005.
What Is Hexagonal Architecture?
The core idea: completely isolate core business logic from all external dependencies, define interaction contracts via "ports", and fulfill technical implementations via "adapters". The hexagon shape symbolizes that the system can accept external components from any direction, without the fixed top-down dependency direction of layered architectures. The number of sides is irrelevant; a more accurate name is "Ports and Adapters".
1) Domain Model
Located at the center of the hexagon, containing entities, value objects, domain services, and business rules. This layer introduces no framework dependencies, no annotations, and no references to ORM or HTTP libraries. Its testability does not rely on a runtime environment.
2) Ports
Ports are interfaces defined by the domain layer, describing the interaction contracts between the application and the outside world. They are divided by call direction:
Driving Ports (Inbound Ports): Declare capabilities the application provides, e.g., a "Create Order" interface. Used by external callers; signatures use domain concepts and command objects.
Driven Ports (Outbound Ports): Declare resources the application needs, e.g., a "Save Order Data" interface. Called by the domain layer; implemented externally.
Port interfaces must not contain HTTP request objects, database connections, framework annotations, or other infrastructure types.
3) Adapters
Adapters implement ports and handle protocol conversion:
Primary Adapters (Driving Adapters): Convert external requests into calls to driving ports. Examples: REST controllers, gRPC services, CLI commands, message listeners.
Secondary Adapters (Driven Adapters): Implement driven ports, converting domain-layer calls into concrete technical operations. Examples: JPA repositories, Kafka producers, third-party API clients.
Characteristics of Hexagonal Architecture
Business logic decoupled from technology implementation: The domain core focuses solely on business rules, unaware whether persistence uses MySQL or PostgreSQL, or whether callers use HTTP or RPC. Technical details are encapsulated in adapters; swapping tech stacks only requires replacing adapter implementations without touching domain code.
Low-cost unit testing of domain logic: Unit tests for domain logic need no database startup or external service connections. Providing test doubles (e.g., in-memory implementations) for outbound ports enables pure domain verification, significantly reducing test execution cost and complexity.
Multiple entry points reuse the domain core: The same domain core can simultaneously support web, mobile, mini-programs, open APIs, internal RPC, scheduled tasks, CLI, etc. Each entry point only needs a corresponding driving adapter; domain logic is not re-implemented.
Explicit dependency direction, adhering to Dependency Inversion Principle (DIP): All compile-time dependencies point toward the domain layer. Outer layers depend on inner layers; inner layers do not depend on outer layers. This clarifies the separation between domain logic and technical implementation for new team members.
Supports domestic technology adaptation and multi-environment deployment: In scenarios like indigenous innovation (信创) transformation or multi-cloud deployment requiring heterogeneous databases and middleware, hexagonal architecture offers clear advantages: only new adapters for the target tech stack are needed; the domain core remains unaffected.
Comparison with Mainstream Architectural Patterns
Hexagonal architecture is compared with Layered (MVC), Clean (Onion), and CQRS architectures:
Traditional Layered Architecture (Layered / MVC)
Typically divides by technical responsibility into Controller, Service, DAO/Repository, and Database layers. Call flow is top-down; the Service layer directly depends on persistence implementations. Changing databases or ORMs often requires adjusting business code. Business logic easily couples with technical details, and unit testing costs are higher due to external resource dependencies. Advantages: intuitive structure, low learning curve, suitable for simple CRUD systems with stable tech stacks.
Hexagonal Architecture (Ports & Adapters)
Centers on the domain core, using inbound and outbound ports to declare application capabilities and external resource needs. Concrete technologies (REST, MQ, MySQL, Redis) are implemented by adapters. Compile-time dependencies uniformly point to the center. The domain core retains only pure business logic, unaware of upper-layer protocols or lower-layer storage choices. Features: pure business logic, easy testing, pluggable adapters. Suitable for complex domain logic, need for multiple entry-point reuse, or infrastructure replacement requirements.
Clean Architecture (Clean Architecture / Onion Architecture)
Uses concentric circles: from inside out — Entities, Use Cases, Interface Adapters, Frameworks & Drivers. Dependency rule: outer layers depend on inner layers. Inner layers are stable and abstract; outer layers lean toward concrete implementations. Compared to hexagonal, it emphasizes stricter layering and boundary constraints, with finer-grained layers and stricter dependency rules. Suits large complex projects but has a steeper learning curve and higher design cost.
CQRS (Command Query Responsibility Segregation)
Separates write and read paths completely. Write side uses Commands, domain model, and event store to handle state changes and write to write database. Read side uses Queries and DTO projections to query read database directly. Both sides can independently choose technologies and scale, enabling read/write performance optimization. However, it introduces eventual consistency, projection updates, and event handling complexity. Suits systems with extreme read/write disparity, high concurrency, or need for event-driven audit capabilities.
The comparison across key dimensions:
Originator: Layered — common practice; Hexagonal — Alistair Cockburn (2005); Clean — Robert C. Martin; CQRS — Greg Young.
Core philosophy: Layered — responsibility-based layering; Hexagonal — port/adapter isolation; Clean — concentric dependency rule; CQRS — read/write separation.
Business independence: Layered — weak; Hexagonal — strong; Clean — strong; CQRS — relatively strong.
Dependency direction: Layered — top-down; Hexagonal — toward center; Clean — outside-in; CQRS — independent pipelines.
Technology replacement cost: Layered — high; Hexagonal — low; Clean — low; CQRS — medium.
Learning curve: Layered — low; Hexagonal — medium; Clean — high; CQRS — high.
Best paired with: Layered — simple CRUD; Hexagonal — DDD; Clean — DDD; CQRS — Event Sourcing (ES).
Note: Hexagonal and Clean architectures share the same essence (dependency inversion + business-centric). Hexagonal emphasizes the practical "port-adapter" pattern; Clean emphasizes strict concentric layering. In practice, they are often combined.
Applicable Scenarios
Hexagonal architecture provides decoupling of business logic from technology, testability without external dependencies, reduced infrastructure replacement cost, and domain model evolution unaffected by framework upgrades. However, ports and adapters introduce additional abstraction, increasing code volume and indirection. Teams must possess dependency inversion and domain modeling skills; otherwise "directory structure matches but dependency direction is wrong" situations arise. For systems with simple domain logic and stable infrastructure, these abstractions yield no real benefit.
Therefore, hexagonal architecture suits: complex domain logic requiring long-term maintenance; realistic needs to replace databases, message middleware, or external services; core business logic requiring high-coverage automated tests; same business logic reused across multiple entry points (web, messaging, batch processing).
Cockburn's original motivation was solving business logic leaking into UI code and systems bound to specific databases causing testing difficulties. These two problems remain prevalent in medium-to-large systems today.
References:
The Hexagonal (Ports & Adapters) Architecture, Alistair Cockburn 2005
https://blog.csdn.net/luo15242208310/article/details/124708008
Layered/Hexagonal/Clean/Onion Architecture Horizontal Comparison
For questions about attribution, corrections or content rights, please contactand we will review it promptly.