# Apply Hexagonal Architecture

> Use when business logic is tangled with frameworks, databases, HTTP handlers, or third-party SDKs — making it hard to unit test, swap infrastructure, or reuse l

- Skill: `jeffreytse/apply-hexagonal-architecture` (Agent Skill)
- Install (CLI): `npx get-skill add jeffreytse/apply-hexagonal-architecture`
- Raw SKILL.md: https://api.skillmd.com/api/skills/jeffreytse/apply-hexagonal-architecture/raw
- Safety review: pending
- Works with: any agent that reads SKILL.md (Claude Code, Claude.ai, Cursor, Codex, Windsurf, 60+ more)
- Category: Coding & Dev Tools
- Author: jeffreytse (https://skillmd.com/u/jeffreytse)
- Updated: 2026-12-03
- Page: https://skillmd.com/skills/jeffreytse/apply-hexagonal-architecture

---

---
name: apply-hexagonal-architecture
description: Use when business logic is tangled with frameworks, databases, HTTP handlers, or third-party SDKs — making it hard to unit test, swap infrastructure, or reuse logic across entry points (API, CLI, queue consumer) — and you want a backend structure where the domain does not depend on infrastructure.
source: 'Cockburn, "Hexagonal Architecture (Ports and Adapters)", alistair.cockburn.us, 2005; Martin, "Clean Architecture", 2017; Palermo, "The Onion Architecture", 2008; Freeman & Pryce, "Growing Object-Oriented Software, Guided by Tests", 2009; Netflix Technology Blog, "Ready for changes with Hexagonal Architecture", 2020'
tags: [project-structure, ports-and-adapters, clean-architecture, dependency-inversion, backend, testability]
related: [apply-solid-principles, apply-adapter-pattern, apply-domain-driven-design, apply-module-boundary-enforcement, design-backend-project-structure]
---

# Apply Hexagonal Architecture

Put the business logic at the center and make everything else (HTTP, databases, message brokers, external APIs) a replaceable adapter that plugs into interfaces ("ports") the core defines. Dependencies always point inward.

## Why This Is Best Practice

**Adopted by:**
- Netflix (their studio engineering team moved data sources without touching business logic, as described on their tech blog in 2020).
- The pattern is the basis of Clean Architecture (Martin) and Onion Architecture (Palermo), and is widely used with DDD.
- Supported directly by frameworks and guidance from Spring, NestJS, and the AWS Prescriptive Guidance "hexagonal architecture pattern".

**Impact:**
- The domain can be unit tested in milliseconds without databases or network, which supports a fast, broad base of the test pyramid (Freeman & Pryce, 2009).
- Infrastructure changes (Postgres to DynamoDB, REST to gRPC, a different payment provider) become new adapters instead of rewrites.

**Why best:**
- In a typical layered application, the "service" layer imports ORM models and SDK clients, so infrastructure leaks into business rules.
- Inverting the dependency (the core owns the interface, infrastructure implements it) keeps the most valuable and slowest-changing code free of the fastest-changing code.

Sources: Cockburn, A. (2005), "Hexagonal Architecture". Martin, R.C. (2017), *Clean Architecture*, Prentice Hall. Palermo, J. (2008), "The Onion Architecture". Freeman, S. & Pryce, N. (2009), *GOOS*, Addison-Wesley. Netflix Technology Blog (2020).

## Steps

1. **Identify the core (domain + application).** Entities, value objects, business rules, and use cases ("PlaceOrder", "RefundPayment"). The core must not import frameworks, ORMs, HTTP, or SDKs.

2. **Define ports as interfaces owned by the core:**
   - **Driving (inbound) ports** are what the outside world can ask the app to do: `PlaceOrderUseCase.execute(cmd)`.
   - **Driven (outbound) ports** are what the app needs from the outside world: `OrderRepository`, `PaymentGateway`, `Clock`, `EventPublisher`.
   Name them in domain language (`PaymentGateway`, not `StripeClient`).

3. **Write adapters at the edge:**
   - **Inbound adapters:** HTTP controllers, gRPC handlers, CLI commands, queue consumers. They translate requests into commands and call the use case.
   - **Outbound adapters:** `PostgresOrderRepository`, `StripePaymentGateway`, `KafkaEventPublisher`. They implement driven ports.

4. **Lay out folders to make the direction visible**, per feature or module:
   ```
   orders/
     domain/          # entities, value objects, domain services, domain errors
     application/     # use cases, ports (interfaces), DTOs/commands
     adapters/
       in/http/       # controllers, request/response mapping
       in/messaging/
       out/persistence/
       out/payment/
   ```
   The rule is `adapters → application → domain`, never the reverse.

5. **Wire everything in a composition root.** One place (`main`, the DI container config, `app.module.ts`) creates concrete adapters and injects them into use cases. The core never instantiates infrastructure.

6. **Map at the boundary.** Adapters convert between transport/persistence models (DTOs, ORM rows) and domain objects. Don't leak ORM entities or HTTP request types into the core.

7. **Test in layers:**
   - Domain and use cases: fast unit tests with in-memory fakes for the ports.
   - Adapters: integration tests against real infrastructure (Testcontainers, sandbox APIs).
   - A few end-to-end tests through an inbound adapter.

8. **Enforce the dependency rule** with an architecture test (ArchUnit, import-linter, eslint-plugin-boundaries). See `apply-module-boundary-enforcement`.

## Rules

- Dependencies point inward. The domain imports nothing from adapters.
- The core owns its port interfaces. Infrastructure implements them.
- Each port is shaped by the core's needs, not by a vendor API.
- Only the composition root knows about concrete adapters.
- Keep it per feature or module. Hexagons can be small.

## Common Mistakes

- **Ports that mirror the vendor SDK.** `PaymentGateway.createStripeCharge()` leaks the vendor. Model the capability: `charge(amount, customer)`.
- **Anemic domain plus fat use cases.** All rules sit in use-case classes and entities are bags of getters. Put invariants on entities and value objects.
- **Using ORM entities as domain entities.** Framework annotations and lazy loading leak in. Map, or accept the trade-off consciously.
- **Interface for everything.** Adding a port for pure in-core helpers adds ceremony with no benefit. Ports exist only at the I/O boundary.
- **Generic folder names across the whole app** (`/domain`, `/infrastructure` at the root holding every feature). Combine with `apply-package-by-feature` so each feature has its own hexagon.

## Examples

**Order service:** `PlaceOrder` use case depends on `OrderRepository`, `InventoryService`, and `EventPublisher` ports. Production wires `PostgresOrderRepository`, `HttpInventoryClient`, and `SnsEventPublisher`. Unit tests wire in-memory fakes and run in under a second. Moving events from SNS to Kafka touched one adapter file and the composition root.

**Same logic, two entry points:** a REST controller and a nightly batch CLI both call `RecalculateInvoices`, so no logic is duplicated.

## When NOT to Use

- **Simple CRUD services** with little business logic. A thin layered or vertical-slice design is cheaper (see `apply-vertical-slice-architecture`).
- **Prototypes and spikes** whose infrastructure won't change and whose lifespan is short.
- **Teams new to the pattern under heavy deadlines.** Start with a feature-first layout and introduce ports where infrastructure actually varies or testing hurts.

