Clean & Hexagonal Architecture
- Explain ports and adapters, clean architecture and onion architecture, and what they have in common
- Apply the dependency rule: business logic depends on nothing outside itself
- Lay out a Go service with domain, application (use cases + ports) and adapters, wired in a composition root
- Handle database transactions and the outbox without leaking SQL into use cases
- Use the structure to test business rules fast, and recognize when the pattern is overkill
TL;DR
- All three styles say the same core thing: put business rules in the centre and make infrastructure depend on them, not the other way round.
- Hexagonal (ports & adapters, Alistair Cockburn): the application talks to the outside world only through ports (interfaces); adapters implement them for HTTP, gRPC, Kafka, Postgres, the payment switch. Driving adapters call in; driven adapters are called out to.
- Clean architecture (Robert C. Martin): concentric rings — entities, use cases, interface adapters, frameworks & drivers — with the dependency rule: source code dependencies point only inward.
- Onion (Jeffrey Palermo): domain model at the core, domain services, application services, then infrastructure and UI outside.
- In Go: define interfaces where they are used (in the application layer), implement them in adapter packages, and wire everything in
main(the composition root). - Payoff: use cases tested in milliseconds with in-memory fakes, swappable infrastructure (vendor switch, DB migration), and business rules readable without framework noise. Cost: more files and indirection — overkill for CRUD and short-lived tools.
Why it matters
A bank's transfer logic outlives its frameworks. The rules for limits, fees and holds may be 15 years old, while the delivery mechanism went from branch terminal to internet banking to mobile app to open-banking API, and the core went from mainframe to vendor package to in-house ledger. If the rules are tangled with the HTTP framework and the vendor's SDK, every channel or vendor change is a rewrite and every rule change risks breaking an integration.
In e-commerce, the same applies to payment providers (you will change or add PSPs), search engines, and message brokers. Interviewers ask "How would you structure the code of this service?" and "How do you test the checkout logic without a database?" — this page is the answer.
Core concepts
Ports and adapters (hexagonal)
- Port: a technology-agnostic interface expressed in domain terms. Inbound ports describe what the application offers (
InitiateTransfer); outbound ports describe what it needs (SaveTransfer,SendToSwitch). - Adapter: translates between a technology and a port. An HTTP adapter turns JSON into a command; a Postgres adapter turns an aggregate into rows.
- Driving (primary) adapters initiate interaction (HTTP, gRPC, CLI, consumers, tests). Driven (secondary) adapters are invoked by the application (DB, broker, external APIs, clock).
- The hexagon shape has no meaning — it just leaves room to draw many ports. The point is symmetry: the UI is "just another adapter", as is the test suite.
Clean architecture rings and the dependency rule
The dependency rule: code in an inner ring must not mention anything in an outer ring — no imports, no types, no framework annotations. Data crossing a boundary is in the form the inner ring defines (plain structs, domain types). Control can flow outward (a use case calls a repository) because the use case calls an interface it owns, which the outer ring implements — dependency inversion.
| Ring | Contains | Changes when |
|---|---|---|
| Entities | Domain model, invariants, value objects (Money, Transfer) | Business rules change |
| Use cases | Application workflows, port interfaces, transaction boundaries | A feature or process changes |
| Interface adapters | HTTP/gRPC handlers, DTO mapping, repository implementations | API shape or schema changes |
| Frameworks & drivers | Router, ORM/driver, broker client, config, main | You upgrade or replace technology |
Onion architecture
Jeffrey Palermo's onion (2008) uses similar layers: domain model at the core, domain services around it, application services next, and the outermost layer containing UI, infrastructure and tests. The emphasis is that infrastructure is at the edge and the domain has no dependencies — the same dependency rule. In interviews, treat hexagonal, onion and clean as variations on one idea; what matters is that you can apply the dependency rule and explain the trade-offs.
| Hexagonal | Onion | Clean | |
|---|---|---|---|
| Author / year | Alistair Cockburn, 2005 | Jeffrey Palermo, 2008 | Robert C. Martin, 2012 (book 2017) |
| Main metaphor | Ports and adapters around a core | Concentric layers | Concentric rings + dependency rule |
| Emphasis | Symmetry of inputs/outputs; testability | Domain model at the centre | Use cases as first-class; framework independence |
Go package layout for a transfer service
transfer/
cmd/
transfer-api/
main.go // composition root: config, adapters, wiring
internal/
domain/ // entities, value objects, domain errors; stdlib only
money.go
transfer.go
app/ // use cases and the ports they need
ports.go
initiate_transfer.go
initiate_transfer_test.go // fast tests with fakes
fakes/ // in-memory implementations of the ports
adapter/
rest/ // driving: HTTP handlers, DTOs
handler.go
kafka/ // driving: consumers of switch responses
consumer.go
postgres/ // driven: repositories, tx manager, outbox
transfer_repo.go
tx.go
outbox.go
switchgw/ // driven: national switch client (ISO 20022 / vendor API)
client.go
Rules:
domainimports only the standard library.appimportsdomain, neveradapter.adapter/...importsappanddomainto implement ports and call use cases.cmd/.../main.gois the only place that knows every concrete type.- Go's
internal/keeps other modules from importing your internals. A small architecture test or a linter such asdepguardcan enforce the inward-only rule in CI.
Ports defined by the consumer
// internal/app/ports.go
package app
import (
"context"
"example.com/transfer/internal/domain"
)
// Driven ports are declared by the application, in its own terms.
type TransferRepository interface {
Save(ctx context.Context, t *domain.Transfer) error
FindByIdempotencyKey(ctx context.Context, key string) (*domain.Transfer, error)
}
type Limits interface {
PerTransaction(ctx context.Context, customerID string) (domain.Money, error)
}
type Outbox interface {
Add(ctx context.Context, events ...domain.Event) error
}
// TxManager runs fn atomically; repositories and the outbox used inside fn
// participate in the same database transaction.
type TxManager interface {
WithinTx(ctx context.Context, fn func(ctx context.Context) error) error
}
// internal/app/initiate_transfer.go
package app
import (
"context"
"errors"
"fmt"
"time"
"example.com/transfer/internal/domain"
)
type InitiateTransferCmd struct {
IdempotencyKey string
CustomerID string
From, To string
Amount domain.Money
}
type InitiateTransfer struct {
Repo TransferRepository
Limits Limits
Outbox Outbox
Tx TxManager
Now func() time.Time
}
func (uc *InitiateTransfer) Handle(ctx context.Context, cmd InitiateTransferCmd) (*domain.Transfer, error) {
existing, err := uc.Repo.FindByIdempotencyKey(ctx, cmd.IdempotencyKey)
switch {
case err == nil:
return existing, nil // replay: same request, same result
case !errors.Is(err, domain.ErrNotFound):
return nil, fmt.Errorf("lookup idempotency key: %w", err)
}
limit, err := uc.Limits.PerTransaction(ctx, cmd.CustomerID)
if err != nil {
return nil, fmt.Errorf("load limits: %w", err)
}
// Domain enforces invariants: positive amount, same currency,
// from != to, amount within limit. Funds are reserved later by Ledger.
t, err := domain.NewTransfer(cmd.IdempotencyKey, cmd.From, cmd.To, cmd.Amount, limit, uc.Now())
if err != nil {
return nil, err
}
err = uc.Tx.WithinTx(ctx, func(ctx context.Context) error {
if err := uc.Repo.Save(ctx, t); err != nil {
return err
}
return uc.Outbox.Add(ctx, t.PullEvents()...)
})
if err != nil {
return nil, fmt.Errorf("persist transfer: %w", err)
}
return t, nil
}
The use case reads like the business process; there is no SQL, no JSON, no Kafka. The idempotency lookup and the unique constraint on the key in the database together make retries safe (see Idempotency & Exactly-Once).
Adapters
A driving adapter maps transport to command and domain errors to status codes:
// internal/adapter/rest/handler.go
package rest
import (
"encoding/json"
"errors"
"net/http"
"example.com/transfer/internal/app"
"example.com/transfer/internal/domain"
)
type Handler struct {
Initiate *app.InitiateTransfer
}
type transferRequest struct {
From string `json:"from_account"`
To string `json:"to_account"`
AmountMinor int64 `json:"amount_minor"`
Currency string `json:"currency"`
}
func (h *Handler) PostTransfer(w http.ResponseWriter, r *http.Request) {
var req transferRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid JSON body", http.StatusBadRequest)
return
}
cmd := app.InitiateTransferCmd{
IdempotencyKey: r.Header.Get("Idempotency-Key"),
CustomerID: r.Header.Get("X-Customer-ID"), // set by the gateway after auth
From: req.From,
To: req.To,
Amount: domain.NewMoney(req.AmountMinor, req.Currency),
}
t, err := h.Initiate.Handle(r.Context(), cmd)
switch {
case errors.Is(err, domain.ErrLimitExceeded), errors.Is(err, domain.ErrInvalidTransfer):
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
case err != nil:
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_ = json.NewEncoder(w).Encode(map[string]string{"transfer_id": t.ID(), "status": string(t.Status())})
}
A driven adapter implements the transaction port with pgx, carrying the transaction in the context so repositories can pick it up:
// internal/adapter/postgres/tx.go
package postgres
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
type txKey struct{}
// querier is satisfied by both pgx.Tx and *pgxpool.Pool.
type querier interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}
type TxManager struct {
Pool *pgxpool.Pool
}
func (m *TxManager) WithinTx(ctx context.Context, fn func(ctx context.Context) error) error {
tx, err := m.Pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }() // no-op after a successful commit
if err := fn(context.WithValue(ctx, txKey{}, tx)); err != nil {
return err
}
return tx.Commit(ctx)
}
// conn returns the transaction carried in ctx, or the pool outside WithinTx.
// Repositories call conn(ctx, r.pool) for every query.
func conn(ctx context.Context, pool *pgxpool.Pool) querier {
if tx, ok := ctx.Value(txKey{}).(pgx.Tx); ok {
return tx
}
return pool
}
Carrying the transaction in context is pragmatic and common in Go; the purer alternative is a callback that receives transaction-scoped repositories, WithinTx(ctx, func(r Repos) error), which makes the dependency explicit at the cost of more plumbing.
Testing benefits
// internal/app/initiate_transfer_test.go
package app_test
import (
"context"
"testing"
"time"
"example.com/transfer/internal/app"
"example.com/transfer/internal/app/fakes"
"example.com/transfer/internal/domain"
)
func TestInitiateTransferIsIdempotent(t *testing.T) {
ctx := context.Background()
repo := fakes.NewTransferRepo()
outbox := &fakes.Outbox{}
uc := &app.InitiateTransfer{
Repo: repo,
Limits: fakes.FixedLimit(domain.NewMoney(50_000_000, "VND")),
Outbox: outbox,
Tx: fakes.NoTx{},
Now: func() time.Time { return time.Date(2026, 1, 1, 9, 0, 0, 0, time.UTC) },
}
cmd := app.InitiateTransferCmd{
IdempotencyKey: "key-1", CustomerID: "C1",
From: "ACC-A", To: "ACC-B", Amount: domain.NewMoney(1_000_000, "VND"),
}
first, err := uc.Handle(ctx, cmd)
if err != nil {
t.Fatalf("first call: %v", err)
}
second, err := uc.Handle(ctx, cmd)
if err != nil {
t.Fatalf("second call: %v", err)
}
if first.ID() != second.ID() {
t.Fatalf("expected same transfer on retry, got %s and %s", first.ID(), second.ID())
}
if n := len(outbox.Events); n != 1 {
t.Fatalf("expected 1 event in outbox, got %d", n)
}
}
How the layers map to a test strategy:
| Layer | Test type | Speed | What it proves |
|---|---|---|---|
| Domain | Pure unit tests, table-driven, property-based | Microseconds | Invariants, calculations (fees, interest, rounding) |
| Use cases | Unit tests with in-memory fakes | Milliseconds | Workflow, idempotency, event emission, error handling |
| Adapters | Integration tests with real dependencies (Testcontainers Postgres/Kafka) | Seconds | SQL, mappings, transactions, serialization |
| Whole service | A few end-to-end / contract tests | Seconds–minutes | Wiring, configuration, API contract |
Most tests live in the fast layers, which keeps CI quick even for complex domains. See Testing Strategy.
When it is overkill
- CRUD services with no real rules (a reference-data service, an admin tool): handler → repository is fine.
- Short-lived code (a migration script, a one-off reconciliation report).
- Thin proxies and BFFs whose job is translation.
- Tiny teams under time pressure building a prototype to validate a market — but keep the domain logic in plain functions so you can move to ports later.
Signs you need it: business rules are duplicated across handlers, tests require a database to check a fee calculation, you are about to swap a vendor (PSP, core banking, search), or several delivery channels share the same rules.
A useful middle ground: hexagonal-lite — keep domain pure and put interfaces only where you genuinely have (or expect) more than one implementation or need a fake for tests. Do not create an interface for every struct.
Trade-offs
| Approach | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Framework-centric layered (handler → service → ORM) | Fast to start, familiar | Rules entangled with framework and DB; slow tests | CRUD, prototypes |
| Hexagonal / clean, full | Testable, swappable infrastructure, clear rules | More files, indirection, mapping code | Core domains with complex, long-lived rules (ledger, payments, pricing) |
| Hexagonal-lite | Most of the benefit, little ceremony | Requires judgment on where to add ports | Most production Go services |
| Transaction in context | Little plumbing; repositories stay simple | Implicit dependency; easy to forget to use the tx | Pragmatic Go services |
| Transaction-scoped repositories via callback | Explicit, type-safe | More boilerplate | Teams that value explicitness, critical money paths |
In practice
- Composition root:
main.goreads config, builds the pgx pool, Kafka producer and HTTP client, constructs adapters, injects them into use cases, and starts servers. No DI framework is needed in Go; explicit wiring is readable and type-checked. - DTOs at the edges: never return domain types directly as JSON; map to DTOs so internal refactors do not break the public API.
- Errors: define domain errors as sentinel values or types in
domain; adapters translate them to HTTP status, gRPC codes or retry decisions. - Clock, ID generator and randomness are ports too — inject them for deterministic tests (cut-off times, value dates and interest calculations depend on time).
- Outbox inside the same transaction as the aggregate save is the standard way to publish events reliably from a hexagonal service. See Transactional Outbox & CDC.
- More Go layout guidance in Project Layout & Clean Architecture in Go.
Common pitfalls
- Interface for everything. Every struct gets an interface "for testing". Symptom: navigation hell, interfaces with one implementation that change with it in every PR.
- Ports in the adapter package. The Postgres package defines
Repositoryand the app imports it. Symptom: the dependency arrow points outward; the app cannot compile without the DB driver. - Domain types with DB or JSON tags everywhere. Symptom: a column rename forces a domain change; API field names leak into business logic.
- Leaky ports.
FindBySQL(query string)or ports returning*sql.Rows. Symptom: SQL creeps into use cases. - Transactions forgotten. Repository calls inside the use case each auto-commit. Symptom: the transfer row is saved but the outbox event is not, after a crash.
- Anaemic core. All logic in use cases, domain is just structs. Symptom: the same rule appears in three use cases with small differences.
Interview angle
- When asked how you would structure a service, draw driving adapters → inbound port → use case → outbound ports ← driven adapters, and state the dependency rule.
- Show concrete Go knowledge: interfaces defined where consumed,
internal/, composition root inmain, transaction handling across repositories and outbox. - Expect: "How do you test this without a database?", "How do you handle transactions across two repositories?", "Isn't this over-engineering?" — answer the last one honestly with the overkill criteria.
- Bank-specific follow-up: "We are replacing the core banking vendor in two years. How does your design help?" — only the driven adapter (and its ACL translators) changes; use cases and domain stay.
- Red flags: claiming you need a DI framework; defining one interface per struct; not knowing where the transaction boundary lives.
Self-check
1. State the dependency rule and explain how a use case can call a database without depending on it.
Source code dependencies must point only inward: inner rings (domain, use cases) never reference outer rings (adapters, frameworks). The use case declares an interface (outbound port) in its own package; the Postgres adapter implements it and imports the app package. At runtime control flows outward, but at compile time the dependency points inward — dependency inversion.
2. What is the difference between a driving and a driven adapter? Give two examples of each for a payments service.
Driving adapters initiate calls into the application: an HTTP handler for transfer requests, a Kafka consumer for switch responses (also CLI commands and tests). Driven adapters are called by the application: a Postgres repository, a national switch client, the outbox publisher, a fraud-scoring client.
3. Why define port interfaces in the application package rather than the adapter package in Go?
Go interfaces are satisfied implicitly, so the consumer can define exactly the methods it needs (small interfaces). Defining them in the app keeps dependencies pointing inward: the app compiles without any adapter, and adapters import the app. Defining them in the adapter would force the app to import the adapter, reversing the arrow.
4. How do you make saving a transfer and writing an outbox event atomic in this structure?
Introduce a TxManager port with WithinTx(ctx, fn). The Postgres adapter begins a transaction, passes it via context (or as transaction-scoped repositories) to the repository and outbox adapters used inside fn, and commits only if fn succeeds. The use case defines the boundary; the adapter implements it.
5. Scenario: a teammate proposes full clean architecture for a reference-data service that serves bank branch codes. What do you say?
It is overkill: there are no meaningful business rules to protect, only reads and occasional admin updates. A handler → repository structure with good tests is enough. Reserve the full structure for services with complex, long-lived rules (ledger, payments, pricing) or with multiple delivery channels or swappable vendors.
6. Which tests become cheap thanks to hexagonal architecture, and which still need real infrastructure?
Cheap: domain invariants and calculations (pure unit tests) and use-case workflows (with in-memory fakes) — idempotency, error handling, event emission. Still need real infrastructure: adapter tests for SQL correctness, transaction behaviour, serialization and broker integration (e.g. Testcontainers), plus a few end-to-end tests for wiring and configuration.
Exercise
Implement the transfer service skeleton above:
- Create
domain(Money,TransferwithNewTransfer, domain errors),app(ports,InitiateTransfer), and adaptersrestandpostgres(repository, tx manager, outbox table). - Write use-case tests with fakes for: success, limit exceeded, idempotent replay, and outbox failure rolling back the transfer.
- Write one Testcontainers-based integration test for the Postgres repository and tx manager.
- Add an architecture test (or
depguardconfig) that fails ifinternal/domainorinternal/appimport anything underinternal/adapteror any driver package. - Measure:
go test ./internal/app/...should run in well under a second.
Done when: the use-case tests run without Docker, the integration test proves the outbox row and transfer row commit or roll back together, and the architecture test fails when you deliberately add a forbidden import.
Further reading
- Alistair Cockburn, "Hexagonal Architecture" (2005, alistair.cockburn.us).
- Clean Architecture: A Craftsman's Guide to Software Structure and Design — Robert C. Martin (2017).
- Jeffrey Palermo, "The Onion Architecture" (blog series, 2008).
- Get Your Hands Dirty on Clean Architecture — Tom Hombergs (Packt, 2nd ed. 2023). Java, but the clearest practical walkthrough.
- Three Dots Labs, Go With The Domain (free e-book) — DDD and clean architecture in Go.
- Growing Object-Oriented Software, Guided by Tests — Freeman & Pryce. Ports, adapters and test doubles.
Related
- Project Layout & Clean Architecture in Go — Go-specific layout conventions.
- Interfaces & Composition — implicit interfaces that make ports cheap in Go.
- SOLID in Go — dependency inversion in detail.
- Testing Strategy — the test pyramid this structure enables.
- Domain-Driven Design — what goes in the domain ring.
- Transactional Outbox & CDC — reliable events from the use case transaction.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).