Hexagonal Architecture (Ports & Adapters)
Isolate core business logic inside ports and plug in external drivers—REST, CLI, Postgres, or in-memory fakes—as interchangeable adapters.
1. Intent
Put your application core at the center, surrounded by explicit ports (interfaces) and adapters (REST, CLI, Postgres, in-memory fakes), so the business logic can be driven and tested identically without a real database or HTTP server.
2. Problem
In a traditional layered Order service, OrderService imports OrderRepo (which imports the Postgres driver). Two things break down as the app matures:
- Slow, brittle tests: Testing
placeOrderrequires spinning up Postgres or stubbing SQL client internals. - Rigid entry points: Adding a CLI command, a queue consumer, or a webhook that places orders forces you to untangle HTTP assumptions from the service layer.
3. Solution
Alistair Cockburn's Ports & Adapters (Hexagonal Architecture) draws a clear boundary around the application core:
- Driving (Primary) Adapters sit on the left: REST controllers, CLI commands, or automated tests. They call into the core through an Inbound Port.
- The Application Core contains the Domain (
Orderentity, pricing rules) and use cases (PlaceOrderUseCase), plus both Inbound and Outbound Ports (TypeScript interfaces). - Driven (Secondary) Adapters sit on the right:
PostgresOrderRepositoryfor production, orInMemoryOrderRepositoryfor fast tests. They implement an Outbound Port.
Notice the asymmetry: the core defines the outbound port interface, and the database adapter implements it. Dependencies always point inward toward the core.
4. Real-world analogy
5. Flow: watch it work
Toggle between Production (Postgres) and Unit Test (InMemory) to see how the exact same domain core runs with different driven adapters.
Hexagonal Order Service: Ports & Adapters
Press Start or tap any step dot to trace the path.
▸All steps (8)
6. Structure: Dependency Rule
All source-code dependencies point inward toward the Hexagon. Adapters depend on Ports; Ports and Domain never import Adapters.
7. Code
// --- Core Domain & Ports (src/core/) ---
export interface OrderItem {
sku: string;
priceCents: number;
qty: number;
}
export interface Order {
id: string;
customerId: string;
totalCents: number;
}
export interface PlaceOrderPort {
execute(customerId: string, items: OrderItem[]): Promise<Order>;
}
export interface OrderRepoPort {
save(order: Order): Promise<Order>;
}
export class PlaceOrderService implements PlaceOrderPort {
constructor(private readonly repo: OrderRepoPort) {}
async execute(customerId: string, items: OrderItem[]): Promise<Order> {
if (items.length === 0) throw new Error('Empty order');
const totalCents = items.reduce((sum, i) => sum + i.priceCents * i.qty, 0);
return this.repo.save({ id: crypto.randomUUID(), customerId, totalCents });
}
}
// --- Driven Adapter: Postgres (src/adapters/driven/postgres-order-repo.ts) ---
export class PostgresOrderRepo implements OrderRepoPort {
async save(order: Order): Promise<Order> {
// Runs SQL INSERT INTO orders ...
return order;
}
}
// --- Driven Adapter: In-Memory for tests (src/adapters/driven/in-memory-order-repo.ts) ---
export class InMemoryOrderRepo implements OrderRepoPort {
public readonly store = new Map<string, Order>();
async save(order: Order): Promise<Order> {
this.store.set(order.id, order);
return order;
}
}labs/arch-order-serviceSwap PostgresOrderRepo for InMemoryOrderRepo in tests with zero database, and compare with Layered and Clean.
cd labs/arch-order-service && npm install && npm run typecheck && npm test && npm run start:hexagonal8. When to use / when to avoid
- Your domain logic has meaningful rules and you want fast, isolated unit tests without databases.
- You support multiple entry points (REST API, CLI, background queue) for the same core use cases.
- External integrations (payment gateways, databases, email) are likely to change or need test fakes.
- The service is pure CRUD pass-through where ports only mirror database tables.
- You are building a short-lived script or prototype where extra interfaces slow you down.
9. How to implement
Define the domain model and ports inside core/
Write Order, PlaceOrderPort, and OrderRepoPort using only TypeScript types—no HTTP or SQL imports.
Implement the use case against outbound ports
Inject OrderRepoPort into PlaceOrderService via its constructor.
Build driving and driven adapters outside core/
Place REST controllers in adapters/driving/ and PostgresOrderRepo / InMemoryOrderRepo in adapters/driven/.
Wire adapters at the composition root
Instantiate new PlaceOrderService(new PostgresOrderRepo()) in main.ts for production, and swap in InMemoryOrderRepo in tests.
10. Pros / Cons
- Domain logic is 100% decoupled from frameworks, HTTP, and database drivers.
- Test suites run in milliseconds by plugging in an InMemory adapter.
- Easy to add new driving adapters (e.g. GraphQL or CLI) without duplicating business rules.
- More files and mapping between domain objects and database/HTTP DTOs.
- Can feel over-engineered for simple CRUD endpoints with no real domain rules.
11. Relations
12. Check yourself
Check Yourself
1. Where should the OrderRepoPort interface live in a Hexagonal TypeScript project?
2. In the Test (InMemory) variant, what acts as the Driving adapter?
Sources
Related Notes
Layered (N-Tier) Architecture
Organize an application into horizontal layers—Presentation, Business, and Data—where each layer only calls the layer directly below it.
Onion Architecture
How Onion Architecture organizes code into concentric rings around the Domain Model so all dependencies point inward.