Hexagonal Architecture (Ports & Adapters) Explained: When to Use It in 2026

Hexagonal architecture (ports and adapters) explained with a practical example — what problem it solves, how it differs from layered and clean architecture, and when it's actually worth the extra structure.

Hexagonal Architecture (Ports & Adapters) Explained: When to Use It in 2026
On this page

I inherited a codebase a few years back where every business rule was tangled directly into database calls and HTTP handlers — testing a pricing rule meant spinning up a real database, and swapping the payment provider meant touching code in a dozen unrelated files. Hexagonal architecture is the pattern that’s meant to prevent exactly that, and it keeps showing up in 2026 architecture roundups next to microservices and event-driven design for a reason. Here’s what it actually is, stripped of the diagram jargon.

The Problem Hexagonal Architecture Solves

Most codebases start clean and then slowly let infrastructure leak into business logic. A function that calculates a discount starts innocently, then someone adds a database lookup inline, then a logging call tied to a specific vendor’s SDK, then an HTTP status code check because the caller happens to be a REST handler. Two years later, that “discount calculation” can’t run without a live database connection, can’t be unit tested without mocking three unrelated libraries, and can’t be reused if you add a CLI tool or a message-queue consumer that needs the same logic.

Hexagonal architecture — coined by Alistair Cockburn in 2005 as “ports and adapters” — addresses this with one rule: your business logic should never depend on infrastructure code, only on interfaces it defines itself. Everything external — databases, web frameworks, message queues, third-party APIs — becomes a plug-in behind an interface, not a hardwired dependency.

Hexagonal architecture ports and adapters diagram showing core domain isolated from infrastructure

Ports and Adapters: The Core Vocabulary

The name comes from the shape people draw it in — a hexagon (arbitrary shape, just “more than two sides” to signal “many possible external connections”) with the business logic in the center and connections poking out to the world.

  • The core (or domain) — your actual business logic. No imports from a web framework, no SQL, no HTTP library. It only knows about its own types and the interfaces it defines.
  • Ports — interfaces defined by the core, describing what it needs from the outside world or what it offers to the outside world. A port is just a contract — an interface or abstract class — owned by the domain layer.
  • Adapters — concrete implementations of ports that talk to actual infrastructure. A PostgresOrderRepository adapter implements an OrderRepository port. A StripePaymentAdapter implements a PaymentGateway port.

The critical detail that trips people up: ports are defined by the core, not by the infrastructure. The database doesn’t dictate the interface the business logic uses — the business logic dictates what shape of interface it needs, and the database adapter conforms to that shape. This is dependency inversion applied structurally across the whole codebase, not just within one class.

A Worked Example

Here’s the discount-calculation problem from the intro, restructured hexagonally in Python:

# --- core/ports.py — interfaces owned by the domain ---
from abc import ABC, abstractmethod
from dataclasses import dataclass

@dataclass
class Order:
    id: str
    total: float
    customer_id: str

class OrderRepository(ABC):
    @abstractmethod
    def get(self, order_id: str) -> Order: ...

class DiscountRule(ABC):
    @abstractmethod
    def apply(self, order: Order) -> float: ...


# --- core/service.py — pure business logic, zero infrastructure imports ---
class PricingService:
    def __init__(self, orders: OrderRepository, discount: DiscountRule):
        self.orders = orders
        self.discount = discount

    def final_price(self, order_id: str) -> float:
        order = self.orders.get(order_id)
        return order.total - self.discount.apply(order)


# --- adapters/postgres_repo.py — infrastructure, implements the port ---
class PostgresOrderRepository(OrderRepository):
    def __init__(self, db_connection):
        self.db = db_connection

    def get(self, order_id: str) -> Order:
        row = self.db.execute("SELECT * FROM orders WHERE id = %s", (order_id,))
        return Order(id=row["id"], total=row["total"], customer_id=row["customer_id"])


# --- adapters/loyalty_discount.py — another swappable implementation ---
class LoyaltyDiscount(DiscountRule):
    def apply(self, order: Order) -> float:
        return order.total * 0.1 if is_loyal_customer(order.customer_id) else 0

PricingService never imports psycopg2, never imports anything Postgres-specific, and doesn’t know or care whether DiscountRule is loyalty-based, seasonal, or a flat coupon. Testing it means passing in fakes:

class FakeOrderRepository(OrderRepository):
    def get(self, order_id: str) -> Order:
        return Order(id=order_id, total=100.0, customer_id="c1")

class FlatDiscount(DiscountRule):
    def apply(self, order: Order) -> float:
        return 10.0

def test_final_price():
    service = PricingService(FakeOrderRepository(), FlatDiscount())
    assert service.final_price("o1") == 90.0

No database, no mocking framework, no network call — a unit test that runs in milliseconds and tests exactly one thing: the pricing math. Swapping Postgres for MongoDB, or Stripe for a different payment provider, means writing a new adapter class — the core service code doesn’t change at all.

Hexagonal architecture testable core business logic with fake adapters example

Driving vs Driven Ports: The Distinction People Skip

Ports come in two flavors, and conflating them is the most common source of confusion when people first read about this pattern:

  • Driving ports (primary/inbound) — how the outside world calls into your core. An HTTP controller or CLI command is an adapter that drives the PricingService by calling final_price(). The port here is the service’s own public interface.
  • Driven ports (secondary/outbound) — what the core calls out to. OrderRepository and DiscountRule above are driven ports — the core defines them and something external implements them.

Visually, driving adapters sit on the “left” of the hexagon (things that trigger your logic — a REST API, a message consumer, a scheduled job), and driven adapters sit on the “right” (things your logic depends on — a database, an external API, a cache). Both sides follow the same rule: the core defines the interface, the outside world adapts to it.

Hexagonal vs Layered vs Clean Architecture

These three get used almost interchangeably in casual conversation, and the confusion is understandable — they share the same underlying goal (isolate business logic from infrastructure) but structure the isolation differently.

Layered Architecture Clean Architecture Hexagonal Architecture
Structure Strict horizontal layers (UI → business → data) Concentric circles, dependencies point inward A core with symmetric ports on all sides
Direction of dependency Typically top-down, layers know the layer below Strict inward-only, outer circles depend on inner Core has zero outward dependencies; everything depends on it
UI and DB treatment Often distinct layers, sometimes coupled to each other Both treated as “outer” details, equally replaceable Both treated as adapters, equally replaceable
Primary weakness Layers often leak — business logic ends up calling data layer directly Can feel over-engineered for simple CRUD apps Same criticism, plus “port” vocabulary has a learning curve

The honest summary: Clean Architecture and Hexagonal Architecture are close enough in practice that many teams use the terms interchangeably — both insist the domain is dependency-free and infrastructure is swappable. Hexagonal’s specific contribution is the ports/adapters vocabulary and the visual “everything is a plug-in” framing, treating a UI and a database as symmetric concerns instead of Clean Architecture’s more explicit concentric-ring hierarchy. Layered architecture is the older, looser ancestor of both — it aims for separation but doesn’t enforce the dependency direction as strictly, which is exactly how business logic ends up calling the data layer directly in practice.

When Hexagonal Architecture Is Worth It

  • Business logic that outlives any single delivery mechanism — a pricing engine, an underwriting rule set, a matching algorithm — code you expect to call from a REST API today and a gRPC service or batch job later.
  • Codebases where infrastructure changes are likely — swapping databases, adding a second payment provider, migrating a message queue — because the adapter boundary absorbs the churn instead of the whole codebase.
  • Teams that value fast, dependency-free unit tests over integration-test-everything — the pattern makes “test the core with fakes” the natural default rather than an afterthought.
  • Domains complex enough to deserve isolation — non-trivial business rules where getting the logic right matters more than getting the plumbing done fast.

When It’s Overkill

  • Simple CRUD apps where the “business logic” really is just “save this row and return it” — wrapping that in ports and adapters adds files and indirection with no real payoff.
  • Small scripts or short-lived tools where the infrastructure never changes and testability isn’t a priority.
  • Teams unfamiliar with dependency inversion — introducing ports/adapters cold, without buy-in, tends to produce interfaces with exactly one implementation forever, which is pure overhead with none of the benefit.

The pattern earns its keep specifically when business rules are valuable enough to protect and infrastructure is volatile enough to swap. Absent both, it’s structure for structure’s sake.

FAQ

Is hexagonal architecture the same as clean architecture? They’re closely related and often used interchangeably in practice — both isolate business logic behind interfaces and keep infrastructure swappable. Hexagonal’s distinct contribution is the ports/adapters vocabulary and treating all external concerns (UI, database, third-party APIs) as symmetric plug-ins rather than an explicit ring hierarchy.

Do I need a specific framework to use hexagonal architecture? No — it’s a structural discipline, not a library. Any language with interfaces or abstract classes (Python’s ABCs, Java interfaces, TypeScript interfaces, Go interfaces) can express ports and adapters.

What’s the difference between a driving port and a driven port? A driving port is how the outside world calls into your core (e.g., a service’s public method, triggered by an HTTP controller adapter). A driven port is what your core calls out to (e.g., a repository interface, implemented by a database adapter).

Does hexagonal architecture slow down initial development? Usually yes, slightly — defining ports and writing adapter implementations is more upfront structure than calling a database client directly. The payoff comes later, in testability and in how cheaply you can swap infrastructure without touching business logic.

Can hexagonal architecture work with microservices? Yes — they solve different problems at different scales. Each microservice can internally be structured hexagonally, keeping its own business logic isolated from its own infrastructure, independent of how services communicate with each other.

Closing thought

The value of hexagonal architecture isn’t the hexagon diagram or the specific vocabulary — it’s the discipline of asking, for every piece of business logic you write, “does this actually need to know about the database, or could it just declare what it needs and let something else provide it?” Answer that question consistently enough across a codebase, and you get a system where testing is fast, swapping infrastructure is a local change, and the business rules that actually matter aren’t buried three layers deep in a database driver’s error-handling code.

Share X / Twitter LinkedIn
Previous Basics of CPP Development Mastering std::list in C++

Keep reading