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
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.
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).
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.
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.
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.
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.
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.
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.
1---2name: apply-hexagonal-architecture3description: 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 l4---5---6name: apply-hexagonal-architecture7description: 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.8source: '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'9tags: [project-structure, ports-and-adapters, clean-architecture, dependency-inversion, backend, testability]10related: [apply-solid-principles, apply-adapter-pattern, apply-domain-driven-design, apply-module-boundary-enforcement, design-backend-project-structure]11---1213# Apply Hexagonal Architecture1415Put 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.1617## Why This Is Best Practice1819**Adopted by:**20- Netflix (their studio engineering team moved data sources without touching business logic, as described on their tech blog in 2020).21- The pattern is the basis of Clean Architecture (Martin) and Onion Architecture (Palermo), and is widely used with DDD.22- Supported directly by frameworks and guidance from Spring, NestJS, and the AWS Prescriptive Guidance "hexagonal architecture pattern".2324**Impact:**25- 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).26- Infrastructure changes (Postgres to DynamoDB, REST to gRPC, a different payment provider) become new adapters instead of rewrites.2728**Why best:**29- In a typical layered application, the "service" layer imports ORM models and SDK clients, so infrastructure leaks into business rules.30- 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.3132Sources: 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).3334## Steps35361. **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.37382. **Define ports as interfaces owned by the core:**39 - **Driving (inbound) ports** are what the outside world can ask the app to do: `PlaceOrderUseCase.execute(cmd)`.40 - **Driven (outbound) ports** are what the app needs from the outside world: `OrderRepository`, `PaymentGateway`, `Clock`, `EventPublisher`.41 Name them in domain language (`PaymentGateway`, not `StripeClient`).42433. **Write adapters at the edge:**44 - **Inbound adapters:** HTTP controllers, gRPC handlers, CLI commands, queue consumers. They translate requests into commands and call the use case.45 - **Outbound adapters:** `PostgresOrderRepository`, `StripePaymentGateway`, `KafkaEventPublisher`. They implement driven ports.46474. **Lay out folders to make the direction visible**, per feature or module:48 ```49 orders/50 domain/ # entities, value objects, domain services, domain errors51 application/ # use cases, ports (interfaces), DTOs/commands52 adapters/53 in/http/ # controllers, request/response mapping54 in/messaging/55 out/persistence/56 out/payment/57 ```58 The rule is `adapters → application → domain`, never the reverse.59605. **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.61626. **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.63647. **Test in layers:**65 - Domain and use cases: fast unit tests with in-memory fakes for the ports.66 - Adapters: integration tests against real infrastructure (Testcontainers, sandbox APIs).67 - A few end-to-end tests through an inbound adapter.68698. **Enforce the dependency rule** with an architecture test (ArchUnit, import-linter, eslint-plugin-boundaries). See `apply-module-boundary-enforcement`.7071## Rules7273- Dependencies point inward. The domain imports nothing from adapters.74- The core owns its port interfaces. Infrastructure implements them.75- Each port is shaped by the core's needs, not by a vendor API.76- Only the composition root knows about concrete adapters.77- Keep it per feature or module. Hexagons can be small.7879## Common Mistakes8081- **Ports that mirror the vendor SDK.** `PaymentGateway.createStripeCharge()` leaks the vendor. Model the capability: `charge(amount, customer)`.82- **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.83- **Using ORM entities as domain entities.** Framework annotations and lazy loading leak in. Map, or accept the trade-off consciously.84- **Interface for everything.** Adding a port for pure in-core helpers adds ceremony with no benefit. Ports exist only at the I/O boundary.85- **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.8687## Examples8889**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.9091**Same logic, two entry points:** a REST controller and a nightly batch CLI both call `RecalculateInvoices`, so no logic is duplicated.9293## When NOT to Use9495- **Simple CRUD services** with little business logic. A thin layered or vertical-slice design is cheaper (see `apply-vertical-slice-architecture`).96- **Prototypes and spikes** whose infrastructure won't change and whose lifespan is short.97- **Teams new to the pattern under heavy deadlines.** Start with a feature-first layout and introduce ports where infrastructure actually varies or testing hurts.