# Hexagonal

**Also known as:** Ports & Adapters  
**Category:** Application Architecture (Mid)  
**Complexity:** 3/5  
**Guide:** https://layra4.dev/architectures/application/hexagonal

*A core in the middle, ports on its edge, adapters plugged in from any side.*

Hexagonal architecture, also called Ports and Adapters, splits an app into an inside and an outside. The inside is the core: domain and use cases. On its edge are ports, interfaces the core owns, such as PlaceOrder or OrderRepository. Outside are adapters, one per technology: an HTTP controller, a Postgres repository, an in-memory fake.

There is no top or bottom. Driving adapters (HTTP, CLI, tests) call into the core; driven adapters (database, email, clock) are called by it. Both are simply outside. So the whole app can run in a test with in-memory adapters. The six sides mean nothing; a hexagon is just a shape with room for many ports.

> **In one sentence.** No top and no bottom: the core defines a port for everything that calls it and everything it calls, so HTTP, SQL and tests are all just adapters.

## Origin (2005)

Named by Alistair Cockburn so that an application could be driven equally by users, programs and tests. “Hexagonal Architecture Explained” (Cockburn and Garrido de Paz, 2024) is the full treatment.

## Inside, edge, outside

### The core (the inside)

The domain and its use cases. It imports nothing from outside, no framework and no SDK, and it is the only place business decisions are made.

- Pure domain and use cases
- Compiles with zero infrastructure

### Port (an interface the core owns)

A contract on the edge, in domain language: what the app offers (driving port) or what it needs (driven port).

- Named after intent, never technology
- The unit you swap, and the unit you test

> interface OrderRepository { save(o: Order): Promise<void> }

### Adapter (one per technology)

The translator between one port and one technology. It converts formats and makes no business decisions.

- Many adapters can serve one port
- An in-memory fake is a real adapter

> class PostgresOrderRepository implements OrderRepository { … }

### Driving vs. driven (who calls, who is called)

Driving adapters call the app: HTTP, CLI, queue consumers, tests. Driven adapters are called by it: Postgres, Stripe, the clock. The core cannot tell drivers apart, so a test is just another driver.

## Doing ports and adapters well

### Name ports after intent, not technology

OrderRepository, PaymentGateway, Clock — never SqlOrderStore. A technology in the name means the core knows about it, and the port can have only one adapter.

### The core owns the ports

Port interfaces live inside, next to the domain. Put them in infrastructure and the arrow flips back: you have rebuilt Layered with extra files.

### Give every port an in-memory fake

The fake proves the port really hides the technology, and it is what tests plug in. A port that could only ever have one adapter is usually a leaked detail.

### Wire concretes once, in the composition root

Use cases receive their ports. One file at the edge builds the adapters and picks them per environment: Postgres in production, in-memory in tests.

## Diagrams

Rendered as geometry on the guide page; not reproducible as text.

- `ports-and-adapters` — see https://layra4.dev/architectures/application/hexagonal

## One module, hexagon-shaped

```
src/orders/
domain/                         # the inside — pure model
  order.ts                      # the Order and its rules
  ports.ts                      # core-owned interfaces — OrderRepository, PaymentGateway
application/
  place-order.ts                # (deps) => (input) — speaks only in ports
infrastructure/                 # driven adapters
  pg-order-repo.ts              # OrderRepository over Postgres
  in-memory-order-repo.ts       # the same port in memory — tests plug in here
interfaces/                     # driving adapters
  http.ts                       # routes → use cases; no business logic
index.ts                        # composition root — the only file naming concretes
```

domain/ and application/ are the inside; interfaces/ drives it and infrastructure/ is driven by it. In a modular monolith, each module can be its own small hexagon.

## Examples

### The core — a port and a use case

```typescript
// domain/ports.ts — owned by the core, domain language only
export interface OrderRepository {
  save(order: Order): Promise<void>;
}

// application/place-order.ts — speaks only in ports
export const placeOrder =
  ({ orders }: { orders: OrderRepository }) =>
  async (cmd: PlaceOrder): Promise<OrderId> => {
    const order = Order.create(cmd);     // rules live inside
    await orders.save(order);
    return order.id;
  };
```

No HTTP, SQL or vendor import. This compiles and tests with nothing running.

### The outside — two adapters, one port

```typescript
// infrastructure — two adapters for the same port
export class PostgresOrderRepository implements OrderRepository {
  constructor(private sql: Sql) {}
  async save(order: Order) { /* INSERT … */ }
}
export class InMemoryOrderRepository implements OrderRepository {
  private rows = new Map<string, Order>();
  async save(order: Order) { this.rows.set(order.id.value, order); }
}

// index.ts — composition root picks per environment
const orders = env.TEST
  ? new InMemoryOrderRepository()
  : new PostgresOrderRepository(sql);
const place = placeOrder({ orders });

// interfaces/http.ts — a driving adapter: translate, call, translate back
app.post("/orders", async (req) => ({ id: await place(parseCmd(req.body)) }));
```

Swap the adapter and the core never notices. Tests run against the Map.

## When to use

- The domain has real rules worth keeping apart from delivery and storage
- Several drivers exist or may come: HTTP, CLI, queue consumer, scheduler
- You want the whole app to run in tests on in-memory adapters

## When not to use

- Thin CRUD with no real rules: ports would be pure ceremony
- A prototype whose shape is still unknown
- One driver and one database forever: plain layers read simpler

## Benefits

- Core tests need no infrastructure: no server, no database
- UI and database are treated alike: both are replaceable adapters
- New drivers (CLI, consumer, scheduler) reuse the use cases unchanged

## Costs

- Every capability becomes an interface plus at least one adapter
- More files and explicit wiring to maintain
- Mapping at every edge: DTOs outside, domain types inside

## Pitfalls

- Ports defined in infrastructure, so the dependency arrow quietly flips back.
- Technology names in ports (SqlOrderStore): the core now knows what it must not.
- Fat adapters that make business decisions, so the logic exists once per technology.
- A mock per test instead of one shared in-memory adapter. Every refactor then breaks dozens of tests.

## Similar patterns, compared

Hexagonal, Onion and Clean are often treated as one thing, and on the main rule they are: dependencies point inward. Hexagonal is the oldest and the least prescriptive. It fixes the boundary and leaves the inside open, which the other two then fill in.

### The family at a glance

| Pattern | What it separates | Dependencies point | What the boundary costs | Use it when |
| --- | --- | --- | --- | --- |
| [Layered Architecture](https://layra4.dev/architectures/application/layered) | Code by technical job: presentation, business logic, data access | Down: business logic imports data access | Nothing. Layers are folders and imports, not network calls | The default: a small or CRUD-style app, or a team new to the code |
| [Onion Architecture](https://layra4.dev/architectures/application/onion) | The same layers, drawn as rings around the domain | In: infrastructure imports the domain | Interfaces move into the domain, plus one place that wires them up | The business rules are worth testing without a database |
| [Clean Architecture](https://layra4.dev/architectures/application/clean-architecture) | The same rings, with business rules split into entities and use cases | In, on the output side too, through presenter interfaces | An interface and a plain data object at every crossing | A long-lived app whose framework will change |
| [N-Tier](https://layra4.dev/architectures/application/n-tier) | Where the code runs: the same layers, on separate machines | Still down, but now over a network | A network hop at each boundary: latency, serialization, partial failure | An untrusted client, separate scaling, or a hard security boundary |
| **Hexagonal** | Inside from outside: no top or bottom, ports on the edge | In from every side; callers and called systems treated the same | A port and at least one adapter per capability | Several callers or storage options, with tests as one more caller |
| [Vertical Slice](https://layra4.dev/architectures/application/vertical-slice) | One feature from another: a folder is a use case, not a technical job | Along the slice, then down into a small shared core | Some duplication between slices, and no layer for shared concerns | Work arrives one feature at a time, and each change touches every folder |

Onion, Clean and N-Tier all come from Layered. Hexagonal reaches the same inward arrows from another starting point. Four of the six are the same code with the arrows turned. N-Tier is the one that puts a network between the layers, and Vertical Slice is the one that names folders after features instead.

### Hexagonal vs Onion Architecture

The same inversion drawn differently: ordered rings versus an inside and an outside with no order. — [Onion Architecture](https://layra4.dev/architectures/application/onion)

**What is genuinely the same**

- The core owns its interfaces; infrastructure implements them
- One composition root names the concretes
- The domain runs in tests with nothing else running

**What actually differs**

- Onion orders the inside into rings; here there is only inside, edge and outside
- Hexagonal gives the driving side ports too, so HTTP, CLI and tests enter the same way
- Onion assumes a domain model in the centre; Hexagonal does not care how the inside is written

**Pick Hexagonal when:** The driving side deserves ports as much as the driven side: a CLI, a consumer and tests next to HTTP.

### Hexagonal vs Clean Architecture

Clean is this shape plus a fixed inside: the same boundary, with rings within it and the output side inverted. — [Clean Architecture](https://layra4.dev/architectures/application/clean-architecture)

**What is genuinely the same**

- Interfaces owned by the inside, adapters outside, dependencies pointing in
- Frameworks and databases are replaceable details

**What actually differs**

- Clean prescribes four rings; Hexagonal prescribes only the boundary
- Clean sends output through presenter interfaces; a driving adapter here may just take the return value
- Clean's rings are ranked; Hexagonal's sides have no order

**Pick Hexagonal when:** You want the boundary discipline without a ring layout behind it: fewer crossings, less mapping.

### Hexagonal vs Layered Architecture

The stacked ancestor. Layered ranks the outside world top to bottom; Hexagonal turns it into one boundary with ports on it. — [Layered Architecture](https://layra4.dev/architectures/application/layered)

**What is genuinely the same**

- Business rules are kept apart from delivery and I/O
- One process; the difference is in the source, not the topology

**What actually differs**

- Layered's domain sits above the database and imports it; here UI and database are both outside
- Every dependency of the core is an interface the core named, not a module below it
- Tests become a driver, not something you add a database to

**Pick Hexagonal when:** More than one driver or storage technology exists or may come, and fast tests without infrastructure are worth the extra interfaces.

### Hexagonal vs Vertical Slice

A different question, not a rival answer. Ports decide what crosses the boundary; slicing decides how code inside it is filed. The two combine. — [Vertical Slice](https://layra4.dev/architectures/application/vertical-slice)

**What is genuinely the same**

- Both reject the database as a bottom layer that everything depends on
- Both want to run a feature without starting the whole app
- Both are conventions inside one deployable

**What actually differs**

- The unit here is the port; there it is the feature folder, and a slice may own its own ports
- One core serves every feature here; there each slice chooses its own depth
- Here every capability earns an interface; there it earns a folder and may skip the interface

**Pick Hexagonal when:** You need to swap technologies, not just arrange files: several drivers or storage options exist or may come.

## Related patterns

- [Layered Architecture](https://layra4.dev/architectures/application/layered) — the stacked ancestor; Onion and Clean are its rings
- [Repository](https://layra4.dev/architectures/tactical/repository) — the most common driven port
- [Adapter](https://layra4.dev/architectures/tactical/adapter) — the GoF pattern this architecture scales up
- [Dependency Injection](https://layra4.dev/architectures/infrastructure/dependency-injection) — how adapters are plugged into ports
- [Modular Monolith](https://layra4.dev/architectures/system/modular-monolith) — each module can be its own small hexagon

## Further reading

- *Hexagonal Architecture* — Alistair Cockburn (2005) — The original article that named ports and adapters.
- *Hexagonal Architecture Explained* — Alistair Cockburn & Juan Manuel Garrido de Paz (2024) — The full book, by the pattern's author.
- *Ready for changes with Hexagonal Architecture* — Netflix Technology Blog (2020) — A production case: swapping data sources without touching the core.
