Skip to Content
Mengty Learns
Architecture

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.

explanationintermediateTested with typescript 7.0.2Updated Nov 26, 2026

1. Intent

TL;DR

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:

  1. Slow, brittle tests: Testing placeOrder requires spinning up Postgres or stubbing SQL client internals.
  2. 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.
Direct imports lock OrderService to one transport and one database driver.

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 (Order entity, pricing rules) and use cases (PlaceOrderUseCase), plus both Inbound and Outbound Ports (TypeScript interfaces).
  • Driven (Secondary) Adapters sit on the right: PostgresOrderRepository for production, or InMemoryOrderRepository for 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

Overview of Hexagonal Order Service: Ports & Adapters. 8 steps.
Overview8 steps in this flow

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.

Both left and right adapters depend on the core's interfaces; the core imports neither.

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;
  }
}
Run it: labs/arch-order-service

Swap 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:hexagonal

8. When to use / when to avoid

When to use
  • 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.
When to avoid
  • 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

Pros
  • 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.
Cons
  • 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