Moving a layered service to hexagonal
Refactor a legacy layered billing service into pure domain entities, application ports, and decoupled infrastructure adapters.
Contentsand lesson path
On this page
- Diagnosing the Couplings in a Layered Service
- Executable Implementation: Pure Core, Ports, and Adapters
- Architectural Verification and Boundary Rules
Lessons of Clean & Hexagonal Architecture
- Which way dependencies point: layers, the MVC family, ports and adapters Concept · 25 min
- Driving ports, driven ports and the composition root Concept · 20 min
- Moving a layered service to hexagonal Lab · 30 min
- Testing the core with in-memory adapters Lab · 20 min
- When a plain layered design is the better choice Concept · 10 min
- Dependency rule check Knowledge check · 6 questions
What you will learn
- Restructure a service into domain core, application ports and infrastructure adapters with all dependencies pointing inward.
- Test domain and application logic without a database or network by substituting adapters.
Prerequisites: Software Design Principles
01. Diagnosing the Couplings in a Layered Service
Consider a typical enterprise billing service in a legacy layered application. In the legacy implementation, an InvoiceService class imports the SQL database ORM session, executes database queries directly, mutates invoice rows, calls an external SMTP email client inline, and returns HTTP response dictionaries.
This arrangement exemplifies the classic architectural traps of the traditional layered architecture:
- Database Schema Entanglement: Business logic calculations (such as summing line items and verifying paid state invariants) are commingled with ORM transaction commit statements and SQL foreign keys.
- Untestable Business Rules: Because the service directly calls
smtp_client.send_mail()and executes SQL queries, writing an automated unit test for invoice settlement requires spinning up a live PostgreSQL database and configuring a test mail server. - Fragile Boundary Contracts: Any update to the email provider or database driver risks breaking core financial calculations.
- Hidden Temporal Coupling: The legacy service implicitly assumed that database connections were established before method invocation, and that email transport sockets were active. If network latency spiked during email dispatch, the database transaction remained open, holding row-level locks and exhausting database connection pools for concurrent operations.
In this hands-on lab, we systematically refactor this tightly coupled service into a pristine hexagonal structure consisting of a pure domain core, driving and driven ports, and replaceable infrastructure adapters.
The Three Phases of Hexagonal Refactoring Refactoring toward hexagonal architecture should proceed along three distinct boundaries:
- Phase 1: Extract the Pure Domain Core: Isolate
InvoiceLineandInvoiceinto pure dataclasses. These entities enforce business rules (calculating line item totals and guarding themark_paid()invariant) without importing any third-party framework or persistence library. - Phase 2: Declare Application Ports: Define the abstract interfaces that express what the core needs from the outside world:
InvoiceRepositoryPortfor persisting invoices, andNotificationPortfor dispatching customer payment receipts. Declare theSettleInvoiceUseCasePortas the driving boundary. - Phase 3: Author Infrastructure Adapters and Use Case Service: Implement
SettleInvoiceServiceas the use case interactor depending solely on port protocols. Implement in-memory adapters for repository storage and notification delivery to verify the entire use case without external dependencies.
The Strangler Fig Migration Pattern In production systems, engineering teams rarely have the luxury of halting feature development for six months to perform a complete architectural rewrite. Instead, teams apply Martin Fowler's Strangler Fig Application pattern to migrate layered codebases incrementally.
Rather than refactoring all fifty services simultaneously, select a single critical use case experiencing frequent change or painful test slowness—such as invoice settlement. Carve out a pure hexagonal boundary for that specific use case, leaving adjacent legacy services untouched. Over successive development sprints, route incoming requests through the new driving ports, gradually strangling the legacy layered routines until the old monolithic modules can be safely decommissioned without operational disruption.
02. Executable Implementation: Pure Core, Ports, and Adapters
Review the complete, runnable Python implementation below. Observe that the Invoice domain entity and SettleInvoiceService use case interactor depend strictly on in-memory abstractions. Zero database drivers or network sockets are required.
from dataclasses import dataclass
from typing import Protocol, List, Optional, Dict
from datetime import datetime
@dataclass
class InvoiceLine:
description: str
quantity: int
unit_price: float
@property
def total(self) -> float:
return round(self.quantity * self.unit_price, 2)
@dataclass
class Invoice:
invoice_id: str
customer_id: str
lines: List[InvoiceLine]
issued_at: datetime
paid: bool = False
@property
def total_amount(self) -> float:
return round(sum(line.total for line in self.lines), 2)
def mark_paid(self) -> None:
if self.paid:
raise ValueError(f"Invoice {self.invoice_id} is already paid.")
self.paid = True
class InvoiceRepositoryPort(Protocol):
def save(self, invoice: Invoice) -> None: ...
def find_by_id(self, invoice_id: str) -> Optional[Invoice]: ...
class NotificationPort(Protocol):
def send_payment_receipt(
self, customer_id: str, amount: float
) -> None: ...
class SettleInvoiceService:
def __init__(
self,
repository: InvoiceRepositoryPort,
notifier: NotificationPort,
) -> None:
self._repository = repository
self._notifier = notifier
def execute(self, invoice_id: str) -> bool:
invoice = self._repository.find_by_id(invoice_id)
if invoice is None:
raise ValueError(f"Invoice not found: {invoice_id}")
invoice.mark_paid()
self._repository.save(invoice)
self._notifier.send_payment_receipt(
invoice.customer_id, invoice.total_amount
)
return True
class InMemoryInvoiceRepository:
def __init__(self) -> None:
self._storage: Dict[str, Invoice] = {}
def save(self, invoice: Invoice) -> None:
self._storage[invoice.invoice_id] = invoice
def find_by_id(self, invoice_id: str) -> Optional[Invoice]:
return self._storage.get(invoice_id)
class InMemoryNotificationAdapter:
def __init__(self) -> None:
self.sent_messages: List[Dict[str, object]] = []
def send_payment_receipt(
self, customer_id: str, amount: float
) -> None:
self.sent_messages.append(
{"customer_id": customer_id, "amount": amount}
)
def main() -> None:
repo = InMemoryInvoiceRepository()
notifier = InMemoryNotificationAdapter()
service = SettleInvoiceService(repo, notifier)
inv = Invoice(
invoice_id="INV-2026-001",
customer_id="CUST-408",
lines=[
InvoiceLine("Cloud Hosting", 1, 120.0),
InvoiceLine("SSL Certificate", 2, 25.0),
],
issued_at=datetime(2026, 11, 9, 12, 0, 0),
)
repo.save(inv)
print(f"Pre-settlement total: ${inv.total_amount:.2f}, paid={inv.paid}")
service.execute("INV-2026-001")
updated = repo.find_by_id("INV-2026-001")
print(f"Post-settlement status: paid={updated.paid}")
msg = notifier.sent_messages[0]
print(f"Receipt sent to {msg['customer_id']} for ${msg['amount']:.2f}")
print("Contract test: PASSED (100% in-memory, 0 network calls)")
if __name__ == "__main__":
main()
Pre-settlement total: $170.00, paid=False
Post-settlement status: paid=True
Receipt sent to CUST-408 for $170.00
Contract test: PASSED (100% in-memory, 0 network calls)
03. Architectural Verification and Boundary Rules
Concrete Architectural Gains Following this refactoring, the application realizes immediate architectural benefits:
- Independent Deployability and Testability: The entire settlement workflow executes in under five milliseconds in automated test runners. Because no real database or SMTP client is involved, tests are completely deterministic and immune to network flakes.
- Interchangeable Persistence: Swapping the underlying persistence store from PostgreSQL to MongoDB or DynamoDB requires authoring a single new adapter class implementing
InvoiceRepositoryPort. The domain entities and application use cases remain completely untouched. - Strict Enclosure of Frameworks: The ORM, email client, and HTTP server are relegated to the outer infrastructure boundary. The core domain code is pure Python that can run in any execution environment.
The Entity Annotation Dilemma: Purity vs. Pragmatism
During hexagonal refactoring, a frequent architectural debate centers on entity annotations. In frameworks like Hibernate, JPA, or SQLAlchemy, entities often carry @Entity, @Table, and @Column annotations directly on class declarations.
A strict purist insists that any framework annotation inside the domain core breaks the Dependency Rule, demanding separate persistence entities with explicit bidirectional mapping layers. However, when database schemas closely mirror domain aggregates and the team is small, maintaining duplicate entity classes and hundreds of lines of mapping boilerplate can impose excessive cognitive friction.
A pragmatic architectural heuristic suggests: if the domain model and database schema share identical structures and the framework annotations do not pull heavy runtime engine dependencies into core unit tests, keeping annotations can be an acceptable trade-off. However, as soon as domain logic diverges from the database schema—such as when an aggregate spans five normalized tables or requires complex value object transformations—separating pure domain entities from persistence adapter models becomes mandatory.
Enforcing Boundary Fitness Functions
To ensure that developers do not inadvertently reintroduce outward dependencies into the core, engineering teams establish automated architectural fitness functions using tools such as import-linter (Python) or dependency-cruiser (TypeScript). These linters fail the continuous integration build if any file inside the domain or application layer imports modules from the infrastructure adapter packages.
A sample import-linter contract defines contracts such as forbidden_modules: [infrastructure, adapters] for packages located under domain and application. In TypeScript projects, equivalent rules in .dependency-cruiser.js prevent domain modules from resolving paths matching src/infrastructure or node_modules/typeorm. By integrating fitness function assertions into the automated pull request validation pipeline, architectural drift is eliminated before code reaches shared branches, guaranteeing long-term architectural integrity and strict modular isolation across team boundaries.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.