Lesson 2 of 9 · 26m
Hexagonal Architecture: Ports and Adapters That Earn Their Keep
Model the application as a core surrounded by explicit ports, then adapt databases, queues, HTTP, and clocks without contaminating business logic.
Hexagonal architecture sounds abstract until you have had to replace a payment provider during an incident. Then the point becomes obvious: your business workflow should not care whether money arrives through Stripe, Adyen, a batch file, or a test double. The core exposes ports. Infrastructure implements adapters. Nothing else is magic.
Name ports by application need, not vendor capability
A port is an interface the application needs. It should use domain vocabulary, not the vocabulary of the external system.
from typing import Protocol
class PaymentAuthorization(Protocol):
def authorize(self, order_id: str, amount: Money, method: PaymentMethod) -> Authorization:
...
class OrderRepository(Protocol):
def get_for_update(self, order_id: str) -> Order:
...
def save(self, order: Order) -> None:
...PaymentAuthorization is better than StripeClient because the use case wants authorization, not Stripe. That distinction is what keeps vendor details at the edge.
Adapters translate, they do not decide
An adapter converts protocols, data formats, errors, and timeouts. It should not quietly invent business policy.
class StripePaymentAuthorization:
def __init__(self, client: stripe.PaymentIntentClient):
self.client = client
def authorize(self, order_id: str, amount: Money, method: PaymentMethod) -> Authorization:
try:
intent = self.client.create(
amount=amount.minor_units,
currency=amount.currency.lower(),
payment_method=method.provider_token,
idempotency_key=f"authorize-{order_id}",
metadata={"order_id": order_id},
)
except stripe.error.RateLimitError as exc:
raise ProviderUnavailable("stripe rate limited") from exc
if intent.status == "requires_action":
return Authorization.requires_action(intent.id, intent.client_secret)
if intent.status == "succeeded":
return Authorization.approved(intent.id)
return Authorization.declined(intent.id, intent.status)The adapter translates Stripe states into domain states. It does not decide whether a declined payment cancels the order; that belongs to the use case or domain.
Keep the core executable without infrastructure
A useful core test boots nothing:
def test_approved_payment_confirms_order():
orders = InMemoryOrderRepository()
payments = FakePaymentAuthorization(outcome="approved")
service = ConfirmOrder(orders=orders, payments=payments)
service.execute("ord_123")
assert orders.get("ord_123").status == "confirmed"This is not about test purity. It means a developer can reproduce business behavior quickly when production is on fire. Fast, boring tests are an architectural feature.
Do not put every interface in the core
Some interfaces belong to the outside world. A web controller can depend directly on a serializer. A reporting worker can depend on a query store. Hexagonal architecture does not mean every class gets an interface; it means dependencies crossing the application boundary are explicit. Interfaces without alternate implementations or meaningful substitution are often speculative complexity.
The real cost: mapping duplication
You will maintain domain objects, persistence rows, API schemas, and sometimes event contracts. That duplication is not waste when it prevents an incompatible concern from infecting everything. The trade is local repetition for global freedom. Make the mappings obvious and test them, especially around money, timestamps, identifiers, and enum states.
Field notes
- Put anti-corruption translation in adapters when integrating legacy systems; do not import legacy names into the domain because it is convenient.
- A port returning framework exceptions forces every caller to know the framework. Translate errors at the boundary.
- Do not mock what you own only because mocks are fashionable; use fakes for ports when behavior matters.
- Inject clocks, randomness, and request IDs as infrastructure capabilities. Hidden nondeterminism destroys reproducibility.
- When a port grows twenty methods, it is probably a vendor SDK in disguise. Split it by use case.
Was this lesson helpful?