Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Hexagonal Architecture

Intent

Isolate core business logic in the center and reach everything outside it — UI, databases, external APIs — only through explicit ports (interfaces) with adapters on each side.

When It Helps

  • Business rules matter more than any single framework, database, or delivery mechanism.
  • You need to swap infrastructure (e.g. change database vendor, add a CLI beside the web UI) without rewriting logic.
  • Tests should drive the core through ports using fake adapters instead of booting real infrastructure.

Structure

flowchart LR
  subgraph Outside["Outside world"]
    UI["Web UI"]
    DB[("Database")]
    API["External API"]
  end
  subgraph Hexagon["Application"]
    PA["Driving adapters<br/>(controllers, CLI)"] --> PI[["Driving ports<br/>(use-case interfaces)"]]
    PI --> CORE(["Core logic"])
    CORE --> PO[["Driven ports<br/>(storage / notify interfaces)"]]
    PO --> DA["Driven adapters<br/>(SQL repo, HTTP client)"]
  end
  UI --> PA
  DA --> DB
  DA --> API

Rules

  1. Core logic depends only on port interfaces it defines; it never imports an adapter, framework, or driver directly.
  2. All inbound calls (UI, CLI, tests) enter through driving ports and their adapters.
  3. All outbound calls (persistence, messaging, third-party APIs) leave through driven ports and their adapters.
  4. Swapping an adapter (e.g. in-memory store for a SQL store) must not require changes to the core.

Illustrative Snippet

Illustrative pseudocode — not runnable.

# sketch of the port / adapter boundary

port OrderStore:            # driven port, defined by the core
  function save(order) -> id

core OrderService(store: OrderStore):
  function place(items):
    order = build_order(items)   # pure logic, no SQL here
    return store.save(order)      # talks only to the port

adapter SqlOrderStore implements OrderStore:   # driven adapter
  function save(order):
    return database.insert("orders", order)

adapter InMemoryOrderStore implements OrderStore:  # test adapter
  function save(order):
    return fake_list.append(order)

Basic Recap

Hexagonal architecture places application behavior behind ports that describe what the core needs or offers. Driving adapters translate web requests, commands, or tests into those ports, while driven adapters connect storage and external systems. Dependencies point toward the core, so infrastructure choices remain replaceable. The pattern is most useful when several delivery mechanisms share meaningful business rules.

Complex Scenario

A subscription business accepts payments from a web app, a partner API, and an offline reconciliation job. All three paths must apply the same credit-limit and duplicate-payment rules. The core owns contracts for payment storage, a payment provider, and receipt publication; provider-specific authentication and database transactions stay in adapters. A new partner adapter must not change the payment policy.

flowchart LR
  Web["Web controller"] --> UseCase[["Charge subscription port"]]
  Partner["Partner API adapter"] --> UseCase
  Job["Reconciliation adapter"] --> UseCase
  UseCase --> Core["Payment policy core"]
  Core --> Store[["Payment store port"]]
  Core --> Provider[["Payment provider port"]]
  Core --> Receipts[["Receipt port"]]
  Store --> SQL["SQL adapter"] --> DB[("Payments DB")]
  Provider --> PSP["Provider adapter"] --> API["Payment provider"]
  Receipts --> Outbox["Outbox adapter"] --> Queue[("Receipt queue")]

Failure walkthrough. The payment provider times out after accepting a charge, and each adapter retries the same request with a new provider key. Customers receive duplicate charges while the web path occupies workers waiting for receipts. Mitigate this by carrying one stable idempotency key through every driving port, using bounded provider timeouts and circuit breaking, and publishing receipts through a transactional outbox after the stored result commits.

Edge cases — concurrency requires a uniqueness constraint on the payment key, retries require provider-safe replay, and partial failure requires an explicit accepted_unknown state for ambiguous provider responses. Ordering between a charge and its receipt should come from outbox records, not adapter timing.

Sketch (illustrative pseudocode, not runnable):

port ChargeSubscription:
  execute(command{idempotency_key, account, amount}) -> result

core PaymentPolicy:
  execute(command):
    existing = payments.find_by_key(command.idempotency_key)
    return existing if present
    authorize_credit(command.account, command.amount)
    return payments.record_pending(command)

adapter ProviderGateway:
  charge(pending):
    response = provider.post(charge, key=pending.idempotency_key, timeout=2s)
    return classify(response, timeout_as="accepted_unknown")

Trade-offs

  • Benefit: business logic stays independent of frameworks and infrastructure, so adapters are swappable and the core is easy to test.
  • Cost: more interfaces and adapter classes than plain layering, which can feel like ceremony for simple CRUD apps.

When to Use / When Not to Use

Use when:

  • Core logic must run with swapped UI/DB/providers or with in-memory fakes.

Avoid when:

  • Single fixed stack with no swap need — Layered is simpler.

Anti-pattern / Failure Mode

  • Misuse: Ports defined per adapter instead of per domain need, leaking infrastructure into the core.
  • Review signal: Core importing adapter packages.

Failure Modes / Trade-offs

  • Port proliferation: every entity gets a repository, notifier, and mapper interface despite having only one plausible implementation. Review signals are one-line ports and tests that only verify mocks.
  • Leaky contracts: a port exposes SQL transactions, HTTP responses, or provider error classes. The core then changes whenever an adapter changes, defeating the boundary.
  • Adapter anarchy: business rules move into controllers or provider clients because those locations are convenient. Compare behavior across driving adapters to expose drift.
  • Practical trade-off: isolated core tests are fast and infrastructure can evolve independently, but mapping, dependency wiring, and failure translation add real maintenance cost.

Contract review. Every port should use domain vocabulary and state its idempotency, transaction, and failure semantics; adapter-specific optional parameters are a leakage warning.

Composition review. Keep construction of adapters in one composition root so tests and production cannot accidentally wire different policy dependencies.

Recovery review. Reconcile accepted_unknown payments with a status-query adapter or provider report instead of letting operators guess whether to retry.

  • Testing trade-off: fake adapters clarify core behavior, but contract tests against real infrastructure remain necessary for serialization, timeouts, and constraints.
  • Security trade-off: narrow ports limit exposed credentials, though too many generic pass-through methods can silently grant adapters excessive capability.
  • Diagnostics trade-off: translation at each boundary improves isolation but requires correlation identifiers on core commands and adapter logs to preserve an end-to-end trace.

Constraint-based use / avoid

ConstraintRecommendation
Multiple UIs, jobs, or partner APIs sharing rulesUse driving ports to keep behavior consistent across entry points.
Frequent provider or database replacementUse driven ports where substitution is a demonstrated requirement.
Tiny team building short-lived CRUD with one databaseAvoid a full port per dependency; direct application services are cheaper to understand.
Compliance requires deterministic policy tests and audit evidenceUse a pure core plus recording fake adapters, while keeping signed audit persistence outside it.
  • Onion — same inward-dependency spirit with the domain model at the center instead of ports.
  • Clean — same isolation goal with stricter concentric rings around entities and use cases.
  • Layered — simpler stacked alternative when you do not need swappable adapters.
  • Test Isolation — ports make fakes trivial.
  • Modular Monolith Orders — hexagonal boundaries inside one deployable.