Sign inGet started
Skills / Software-architecture

Hexagonal Architecture

Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases.

Hexagonal Architecture (Ports and Adapters) is a software architectural pattern that isolates your application's business logic from all external concerns — databases, frameworks, UIs, and third-party services. Introduced by Alistair Cockburn, the pattern enables the same application core to be driven by tests, batch scripts, CLI tools, or HTTP clients interchangeably. It produces a codebase where infrastructure is swappable, the core is always testable in isolation, and architectural boundaries are explicit and mechanically enforceable.

By Alistair Cockburn · Free
Specimen 01 · Live diagnosisHexagonal Architecture
Input

“I have a Spring Boot service where my service classes directly autowire JpaRepository interfaces. Testing is painful — I have to spin up an H2…”

Diagnosis
Hexagonal Architecture draws a hard boundary between your business logic and everything external to it — databases, HTTP layers, message queues, all of it.
Full transcript ↓
Calibrated referenceagent-skills.ai
The gap

Keep business logic pure — swap any database, UI, or API without touching the core

Hexagonal Architecture structures an application around three explicit zones: the Application Core (the hexagon), which contains pure domain and business logic with zero dependencies on infrastructure or frameworks; Ports, which are typed interfaces defining the contracts at the application boundary — split into Primary/Driving Ports (use-case interfaces that external actors call) and Secondary/Driven Ports (infrastructure contracts the core requires, such as repository or notification interfaces); and Adapters, which are concrete implementations of those ports for specific technologies (a Spring REST controller implementing a primary port, a JPA repository implementing a secondary port). The central non-negotiable constraint is the Dependency Rule: all dependencies point inward. The core never imports or references adapter code. This makes the core testable in complete isolation by swapping real adapters for in-memory test doubles, and makes infrastructure interchangeable without modifying business logic. The hexagon shape itself is intentional — each side represents a distinct port, signaling that many different drivers and technologies can connect to the core without any single one being privileged.

The problem

Most codebases tightly couple business logic to infrastructure — service classes directly import JPA repositories, domain objects reference HTTP request types, and swapping a database means rewriting core logic. This makes the application impossible to unit-test without spinning up real infrastructure, and every technology change ripples through the entire codebase. Hexagonal Architecture solves this by making the coupling explicit and enforceably one-directional: infrastructure always adapts to the core, never the reverse.

The solution

You walk away with a clear architectural boundary — named port interfaces defining your application's contracts, adapter stubs implementing them per technology, and a test double pattern that lets the entire core run in milliseconds with zero infrastructure. Your business logic survives any infrastructure change because it never knew the infrastructure existed.

You bring
  • A description of your application's domain and its key use cases
  • Existing code, a class diagram, or a project structure to audit or migrate
  • Your target language or framework (Java, Python, TypeScript, Go, etc.)
  • The specific infrastructure you need to isolate (SQL database, REST API, message queue, etc.)
You get
  • Named primary and secondary port interface definitions ready to commit to your codebase
  • Adapter class skeletons for your specific technology stack (Spring, SQLAlchemy, Mongoose, Stripe SDK, etc.)
  • A recommended project directory structure that enforces the hexagonal boundary at the filesystem level
  • A dependency-direction compliance checklist with pass/fail verdicts for every boundary in your codebase
In action

Watch the methodology work.

Three specimens from a single real session: the same situation, unaided and calibrated, the full transcript, and the skill answering live in the channel where the work happens.

Fig.01The same situation, two ways
Specimens A · B
Specimen AVague
Unaided

“Your `OrderService` has `@Autowired OrderJpaRepository repo`, `@Autowired EmailClient emailClient`, and `@Autowired ProductCatalogRestClient catalog` as direct fields. Every unit test requires a full Spring context, an H2 in-memory database, and live API credentials. Changing from SQL to NoSQL means modifying the service class. A bug in the email service fails order placement tests.”

×Vague — nothing concrete to act on.
Specimen BCalibrated
With Hexagonal Architecture

“Your `OrderService` depends only on `OrderRepository`, `NotificationService`, and `ProductCatalog` — three interfaces it owns in the domain package. A 4-line JUnit test constructs it with `InMemoryOrderRepository` and `NoOpNotificationService` and runs in under 50ms with no infrastructure. Swapping Postgres for MongoDB means writing a new `MongoOrderRepository` adapter — zero changes to the core. The compliance checklist shows zero dependency-direction violations.”

Specific, grounded, and ends with one clear next step.
Fig.02A real session, unedited
In-app · assistant
Hexagonal ArchitectureClaude
Hexagonal Architecture
Hexagonal Architecture draws a hard boundary between your business logic and everything external to it — databases, HTTP layers, message queues, all of it. The core makes no imports from infrastructure; infrastructure adapts to the core via typed port interfaces. What are we working with today — an existing codebase to audit or migrate, or a new service you're designing from scratch?
I have a Spring Boot service where my service classes directly autowire JpaRepository interfaces. Testing is painful — I have to spin up an H2 database for every unit test. I've heard Ports and Adapters fixes this.
That's the classic secondary port violation: your application core (the service classes) is directly coupled to a Spring Data infrastructure interface. In hexagonal terms, you need a secondary port — a plain Java interface like `OrderRepository` that the core owns and depends on — and then a secondary adapter (`JpaOrderRepository implements OrderRepository`) that lives in the infrastructure layer and does the Spring Data work. Your service class gets the `OrderRepository` port injected; it never sees JPA.
What does your service layer look like — can you share the class or describe its dependencies?
It's an OrderService with an `@Autowired OrderJpaRepository repo` field, a `ProductCatalogService catalogService` that calls a REST API, and an `EmailClient emailClient` for notifications. All three are framework or infrastructure things.
You have three secondary port candidates. Here's how to classify and extract them:
Secondary Ports (interfaces the core defines and owns — zero framework imports):- `OrderRepository` — persistence contract: `save`, `findById`, `findByCustomer`- `ProductCatalog` — external catalog contract: `findProduct`, `checkAvailability`- `NotificationService` — outbound notification contract: `sendOrderConfirmation`
Secondary Adapters (infrastructure implementations in your adapter package):- `JpaOrderRepository implements OrderRepository` — wraps your existing `OrderJpaRepository`- `RestProductCatalog implements ProductCatalog` — wraps your catalog HTTP client- `SmtpNotificationService implements NotificationService` — wraps your `EmailClient`
For testing: You create `InMemoryOrderRepository implements OrderRepository` with a plain `HashMap` — no H2, no Spring context, zero setup time.
Shall I generate the actual port interface definitions and an `InMemoryOrderRepository` test adapter in Java, plus the recommended directory structure?
Yes please — the full set.
Here are the port interfaces and project structure:
Secondary port interfaces (in `com.example.orders.domain.port` — no framework imports):```javapublic interface OrderRepository { Order save(Order order); Optional<Order> findById(OrderId id); List<Order> findByCustomer(CustomerId customerId);}
public interface NotificationService { void sendOrderConfirmation(Order order, CustomerEmail email);}
public interface ProductCatalog { Optional<Product> findProduct(ProductId id); boolean isAvailable(ProductId id, Quantity quantity);}```
In-memory test adapter:```java// src/test — no Spring, no H2, no annotationspublic class InMemoryOrderRepository implements OrderRepository { private final Map<OrderId, Order> store = new HashMap<>(); public Order save(Order order) { store.put(order.id(), order); return order; } public Optional<Order> findById(OrderId id) { return Optional.ofNullable(store.get(id)); } public List<Order> findByCustomer(CustomerId id) { return store.values().stream().filter(o -> o.customerId().equals(id)).collect(toList()); }}```
Project structure:```src/main/java/com/example/orders/ domain/ model/ ← Order, OrderId, Product (pure domain objects — no annotations) port/ ← OrderRepository, NotificationService, ProductCatalog usecase/ ← PlaceOrderUseCase (business logic, depends only on ports) adapter/ web/ ← OrderController (Spring REST — primary adapter) persistence/ ← JpaOrderRepository (Spring Data — secondary adapter) notification/ ← SmtpNotificationService (secondary adapter) catalog/ ← RestProductCatalog (secondary adapter)src/test/java/ domain/ ← Unit tests: new PlaceOrderUseCase(inMemoryRepo, ...) — zero Spring```
The rule: nothing in `domain/` may import from `adapter/`. Your `PlaceOrderUseCase` unit tests now run in under 100ms with zero infrastructure dependencies.
This is exactly what I needed. One thing I keep confusing — how is this different from Uncle Bob's Clean Architecture?
They share the same core principle — dependencies point inward — but differ in scope and internal structure.
Hexagonal Architecture (Cockburn, 2005): Defines the application boundary using ports and adapters, with a primary/secondary split based on who initiates interaction. It says nothing about how to structure the interior of the hexagon — that's deliberately left to you.
Clean Architecture (Uncle Bob, 2012): Adds explicit concentric rings inside the core — Entities (enterprise business rules), Use Cases (application business rules), Interface Adapters, and Frameworks. It prescribes the internal layering that hexagonal architecture leaves open.
In practice: Cockburn's hexagon maps roughly to Uncle Bob's Entities + Use Cases rings combined. Clean Architecture's Interface Adapters ring is Cockburn's adapter layer. The key difference: if you need a prescription for structuring the core's internals, Clean Architecture provides it. If you already have a working domain model and just need to isolate it from infrastructure, hexagonal architecture is the right scope.
You can — and many teams do — apply both: hexagonal boundaries at the application edge, Clean Architecture rings inside the hexagon.
Reply to Hexagonal Architecture
What the skill is doing
01Port/Adapter Boundary Audit
02Port Interface Generator
03Adapter Skeleton Builder
Fig.03The same skill, in the channel you already use
WhatsApp · live
9:41
HAHexagonal Architecturetyping…
Messages are end-to-end encrypted. No one outside of this chat can read them.
Today
I have a Spring Boot service where my service classes directly autowire JpaRepository interfaces. Testing is painful — I have to spin up an H2 databas…9:14✓✓
Hexagonal Architecture draws a hard boundary between your business logic and everything external to it — databases, HTTP layers, m…9:14
The core makes no imports from infrastructure; infrastructure adapts to the core via typed port interfaces.9:15
What are we working with today — an existing codebase to audit or migrate, or a new service you're designing from scratch?9:15
Message

The same skill, where the work happens.

No new app to learn. The methodology runs over the WhatsApp Business API, so the answer lands as a reply in the thread you’re already in — same rigour, zero context-switch.

Reads the situation, names the pattern, returns one concrete next move.
Delivered in seconds, inside a conversation that already exists.
Specimen · WhatsApp Business API · live
Capabilities

What it does, specifically.

Each capability is a distinct move drawn straight from the source methodology — not a generic assistant guessing.

CapabilityC-01

Port/Adapter Boundary Audit

Analyzes your existing code structure and identifies every place where the Dependency Rule is violated — core classes importing adapter-layer code, domain objects referencing framework annotations, or service layers directly instantiating infrastructure clients. Each violation is classified, explained, and paired with a concrete remediation step.

Based on Cockburn's non-negotiable constraint that the application core must contain zero references to adapter-layer code; violations are binary pass/fail against this rule, making them detectable by simple import scanning.
CapabilityC-02

Port Interface Generator

Takes your use cases and infrastructure dependencies and produces typed interface definitions for both primary ports (the use-case interfaces external drivers call) and secondary ports (the infrastructure contracts the core requires, such as OrderRepository or NotificationService). Output is in your chosen language with idiomatic naming conventions.

Implements Cockburn's port taxonomy: Primary/Driving ports represent what the application offers to external actors; Secondary/Driven ports represent what the application demands from infrastructure — each expressed as a typed interface owned by and residing in the core.
CapabilityC-03

Adapter Skeleton Builder

Generates concrete adapter class stubs — both primary adapters (REST controllers, CLI handlers, test harness drivers) and secondary adapters (JPA/SQLAlchemy repositories, SMTP notification clients, in-memory test doubles) — wired to the generated port interfaces. Each adapter is self-contained and interchangeable without modifying the core.

Adapters in Cockburn's model are the only layer permitted to import framework or infrastructure code; generating named, separate adapter classes keeps that contamination isolated from the core and makes each technology independently replaceable.
CapabilityC-04

Hexagonal Migration Planner

Produces a step-by-step migration plan for extracting a specific layer (database access, HTTP layer, external API client) from an existing codebase into the ports-and-adapters model. Each step is incremental and preserves behavior while progressively introducing the boundary, with a test strategy at each stage.

Cockburn's pattern is applicable one port-adapter pair at a time: identify the dependency, extract a secondary port interface, move concrete code into an adapter, update the core to depend only on the interface — each step independently verifiable.
CapabilityC-05

Architecture Pattern Disambiguator

Provides precise, concrete comparisons between Hexagonal Architecture and adjacent patterns — Clean Architecture (Uncle Bob), Onion Architecture (Jeffrey Palermo), and traditional Layered Architecture — mapping their terminology to each other and identifying where they diverge in practice, so teams adopt the right pattern with accurate vocabulary.

Addresses a known challenge Cockburn's pattern faces: it predates Clean Architecture (2012) and Onion Architecture (2008), and shared vocabulary (layers, rings, adapters) creates confusion; this capability anchors each pattern to its specific structural constraints and non-negotiable rules.
Tested

Graded before it shipped.

Every skill is scored against independent scenarios for methodology fidelity before it goes live — not vibes, a rubric.

What it produces
OutputD-01

Hexagonal Boundary Diagram

A labeled architecture diagram showing the application core (hexagon) at the center, named ports on each face, and adapters on the perimeter connected to their external technologies — suitable for technical documentation or team onboarding.

OutputD-02

Port Interface Definitions

Typed primary and secondary port interfaces in your chosen language, with method signatures derived from your use cases and infrastructure dependencies — ready to paste into your codebase with zero infrastructure imports.

OutputD-03

Adapter Skeleton Set

Concrete adapter class templates for each port — including a lightweight in-memory test adapter and a real infrastructure adapter stub — wired to the port interfaces and ready to fill with technology-specific logic.

OutputD-04

Project Directory Blueprint

A recommended folder and package structure that enforces the hexagonal boundary at the filesystem level, customized to your language and build tool (Maven, Gradle, Poetry, npm, etc.) with notes on which import directions are permitted.

OutputD-05

Dependency-Direction Compliance Checklist

A checklist of the pattern's non-negotiable rules with pass/fail status for your codebase: core imports only ports, adapters depend on ports not each other, no framework annotations in the core, and all infrastructure is wired at startup via dependency injection.

The source

Grounded in the original work.

Every answer traces back to a real source and the practitioner who wrote it — not a secondhand summary. Here is the source of record.

Source authorA-01

Alistair Cockburn

Alistair Cockburn is one of the 17 original signatories of the Agile Manifesto (2001) and a software methodology pioneer. He introduced Hexagonal Architecture in a 2005 article that became a canonical reference in software engineering, and is also the creator of the Crystal family of agile methods and the author of 'Writing Effective Use Cases' and 'Agile Software Development.' He developed Hexagonal Architecture while working as a software architect and consultant, observing that test-driven applications could be generalized by treating tests as interchangeable drivers of an isolated application core.

Status · Inspired by Alistair Cockburn’s work — not yet claimed. Are you Alistair Cockburn?
Primary sourceS-01

Hexagonal Architecture (alistair.cockburn.us, 2005)

by Alistair Cockburn

Co-author of the Agile Manifesto (2001); inventor of Hexagonal Architecture and Crystal Methods; author of 'Writing Effective Use Cases'; software architect and methodology researcher.

Read the original ↗
Citationalistair.cockburn.us
In the build queue

Be first to run it.

Hexagonal Architecture is being built right now. Leave your email and we’ll tell you the moment it goes live.

Notify meEmail
At launchI have a Spring Boot service where my business logic directly imports JPA repositories and HTTP clients, making it impossible to unit test without a full Spring context. Can you audit my dependencies for hexagonal violations and generate the port interfaces I need to extract?