← Concepts

阅读中文版本

Hexagonal Architecture

Hexagonal architecture separates the domain core from the outside world through ports and adapters, so business logic is testable without infrastructure and infrastructure is replaceable.

architecture

Definition

Hexagonal architecture (ports and adapters) organizes an application as a domain core surrounded by ports — interfaces the core defines — and adapters that connect ports to technology: databases, message brokers, HTTP, CLI. The core depends on nothing outward; all dependencies point inward. Infrastructure becomes swappable detail and tests exercise the core through ports without heavy setup.

Context and scope

Applied in domain-rich services: lending rules, pricing engines, scheduling. The foundation of onion and clean architecture variants.

Common misconceptions

  • It is a folder structure — it is a dependency rule: core code never imports adapter code; folders only enforce it if review does
  • Everything becomes a port — the pattern pays where logic is rich; CRUD endpoints gain nothing but indirection
  • Ports are interfaces named after the technology — ports speak domain language; adapters are the only place technology vocabulary appears

Anti-patterns

  • Injecting ORM entities into the domain and coupling the core to the persistence framework
  • Designing ports by mirroring the database schema instead of the use cases
  • Adding a service layer that forwards to the domain unchanged and calling it hexagonal

Related concepts

Related examples

Authoritative source

https://alistair.cockburn.us/hexagonal-architecture/

What it is

The original insight: application logic and technical delivery should vary independently. The hexagon draws that boundary — inside, the domain; on the walls, ports; outside, adapters.

How it works

Driving adapters (HTTP handlers, queue consumers, CLI) invoke core operations through driving ports. The core persists and notifies through driven ports it defines. Adapters implement driven ports with concrete technology. Composition happens in one place — the application wiring — leaving the core framework-free.

When to apply

Services whose value is business rules rather than data movement, teams wanting fast domain tests without containers, and systems expecting infrastructure churn. Data-shovel services can stay simple.

Pitfalls

The pattern degenerates into anemic models with transaction scripts behind ports. Mapping layers between domain and persistence models cost code — justified only when models genuinely diverge. Adapters calling other adapters bypasses the core and recreates spaghetti outside the hexagon.