Backend Engineer Guide: Hexagonal (Ports & Adapters) & Clean Architecture in Python & Go

When business rules—such as pricing calculations, subscription state transitions, or loan underwriting—are written directly inside Django `Model.save()` methods, FastAPI route functions, or Celery task bodies, the codebase quickly becomes impossible to unit-test without spinning up PostgreSQL, Redis, and three external HTTP mocks. By structuring backend services around Hexagonal Architecture (Ports & Adapters) and Domain-Driven Design (DDD), core domain logic remains 100% pure Python or Go—executing 1,000 unit tests in under 200 milliseconds. As a Senior Backend Engineer, here is how I apply pragmatic Clean Architecture in production.

1. Decoupling Domain Use-Cases from ORM & Payment Gateways via `Protocol` Ports

In Python, `typing.Protocol` defines structural interface ports without rigid abstract-base-class inheritance ceremony. The application service depends only on the `Protocol` port, allowing tests to inject an in-memory adapter while production injects the PostgreSQL/Stripe adapter:

from dataclasses import dataclass
from decimal import Decimal
from typing import Protocol

@dataclass(frozen=True)
class InvoiceRecord:
    invoice_id: str
    tenant_id: str
    amount_usd: Decimal
    is_paid: bool

class InvoiceRepositoryPort(Protocol):
    def get_for_update(self, invoice_id: str) -> InvoiceRecord | None: ...
    def mark_paid(self, invoice_id: str, payment_ref: str) -> InvoiceRecord: ...

class SettleInvoiceUseCase:
    def __init__(self, repo: InvoiceRepositoryPort) -> None:
        self.repo = repo

    def execute(self, invoice_id: str, paid_amount: Decimal, payment_ref: str) -> InvoiceRecord:
        invoice = self.repo.get_for_update(invoice_id)
        if invoice is None:
            raise LookupError(f"Invoice {invoice_id} not found")
        if invoice.is_paid:
            return invoice
        if paid_amount < invoice.amount_usd:
            raise ValueError("Partial settlement not permitted for this invoice tier")
        return self.repo.mark_paid(invoice_id, payment_ref)

2. Pragmatic Modular Monoliths Before Premature Microservices

Clean Architecture boundaries inside a single deployment artifact (a Modular Monolith) give teams all the testability and team-ownership benefits of microservices without distributed network latency—while making it trivial to extract a high-load module into a standalone Go or Python microservice later.

3. Hire a Senior Backend Architect for Python & Go Systems

Untangling a tightly coupled monolith or designing clean microservice boundaries? Explore my Backend Engineer Pillar Guide, review my Legacy Monolith Refactoring Guide, or book a 1-Day Backend Architecture Sprint.


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 15+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs