Skip to content

Lesson 14 of 28Architecture

Hexagonal and Clean Architecture

Point every dependency at the business rules: rings, driving and driven ports, use cases, in-memory adapters, and a linter that keeps it honest.

14 min read0/3 questions

Your team runs a payouts service. It started as a few Express routes calling Prisma, and the rules for who can withdraw how much now live inside route handlers, scattered between SQL queries and Stripe calls. Product wants the same payout logic triggered from a queue consumer and an admin CLI, and finance wants to move some countries to a second payment provider. Every one of those changes means copying rules out of HTTP handlers. Hexagonal architecture (also called ports and adapters) and its cousin Clean Architecture are the standard answer: put the rules in the middle, make everything else plug into them, and make the compiler or a linter enforce the direction. Interviewers ask about it for senior backend roles, usually as "how would you structure this so it is testable and the database is swappable?" Python Backend Architecture gave you a short sketch of ports and adapters. This lesson is the full version.

The dependency rule, drawn as rings

Layered Architecture gave you a stack with one direction. Clean Architecture (Robert C. Martin, 2012) redraws the same idea as concentric rings, and states one rule: source code dependencies point only inward. Nothing in an inner ring may name anything in an outer ring: not a class, not a function, not a type.

Clean Architecture, from the inside out
  1. EntitiesWallet, Money, payout limits: rules true for the whole business
  2. Use casesRequestPayout, ApprovePayout: one application action each, plus the ports they need
  3. Interface adaptersHTTP handlers, queue consumers, repositories, gateway clients, mappers
  4. Frameworks and driversExpress, Next.js, Prisma, Drizzle, Postgres, the Stripe SDK

Entities hold invariants such as 'a wallet cannot go negative'. They import nothing from the other rings, so they are the most stable code you own.

1/4

What "inward" means in practice is a list of allowed imports:

  • domain/ imports only the standard library.
  • application/ (use cases and ports) imports domain/.
  • adapters/ imports application/ and domain/, plus the frameworks they wrap.
  • One composition root (main.ts, create_app()) imports everything and wires concrete adapters into use cases. It is the only file allowed to know every concrete class.

The trick that makes this possible is the one from Dependency Inversion in SOLID: the use case needs to save a wallet, so it owns the WalletRepository interface, and the Prisma class in the outer ring implements it. Control flows outward to the database. The source dependency points inward to the interface.

Hexagonal architecture (Alistair Cockburn, 2005) is the same rule with different pictures. The hexagon is "the application"; ports are its sockets; adapters plug in on every side. Onion architecture is a third name for it. In an interview, say they share one idea, the dependency rule, and differ mostly in vocabulary.

Driving and driven ports

Ports come in two kinds, and the difference is who starts the conversation.

  • A driving (primary) port is how the outside world asks the application to do something. Its adapters are HTTP handlers, queue consumers, CLI commands, cron jobs and tests. In code, the driving port is often just the use case's public method.
  • A driven (secondary) port is something the application needs from the outside world: storage, payments, email, the clock. The use case defines the interface; an adapter in the outer ring implements it.
One payout request through the hexagon
Route handlerRequestPayoutWalletRepositoryPayoutGatewayexecute({ walletId, cents })get(walletId)Walletsend(walletId, cents)transferId{ transferId, balanceCents }

The driving adapter validated the JSON shape and built a plain input DTO. No req or res object crosses this line.

1/6

Here is the whole thing in TypeScript in one runnable file. In a real repo each section is its own folder, and the in-memory classes live under test/ or adapters/memory/.

TypeScript
// ---- core/domain: entities and invariants. Imports nothing.class DomainError extends Error {} class Wallet { constructor(readonly id: string, private balanceCents: number) {} get balance() { return this.balanceCents; } withdraw(cents: number) { if (cents > this.balanceCents) throw new DomainError("insufficient funds"); this.balanceCents -= cents; }} // ---- core/ports: what the use case needs, in its own words.interface WalletRepository { get(id: string): Promise<Wallet | undefined>; save(wallet: Wallet): Promise<void>;}interface PayoutGateway { send(walletId: string, cents: number): Promise<string>; // returns a transfer id} // ---- core/use-cases: one use case, with its own input and output DTOs.type RequestPayoutInput = { walletId: string; cents: number };type RequestPayoutOutput = { transferId: string; balanceCents: number }; class RequestPayout { constructor(private wallets: WalletRepository, private payouts: PayoutGateway) {} async execute(input: RequestPayoutInput): Promise<RequestPayoutOutput> { const wallet = await this.wallets.get(input.walletId); if (!wallet) throw new DomainError(`wallet ${input.walletId} not found`); wallet.withdraw(input.cents); // the invariant lives in the entity const transferId = await this.payouts.send(wallet.id, input.cents); await this.wallets.save(wallet); return { transferId, balanceCents: wallet.balance }; }} // ---- adapters/driven: in-memory versions for tests and this demo.class InMemoryWallets implements WalletRepository { private rows = new Map<string, number>(); constructor(seed: Record<string, number>) { for (const [id, cents] of Object.entries(seed)) this.rows.set(id, cents); } async get(id: string) { const cents = this.rows.get(id); return cents === undefined ? undefined : new Wallet(id, cents); } async save(w: Wallet) { this.rows.set(w.id, w.balance); }} class FakePayouts implements PayoutGateway { sent: Array<[string, number]> = []; async send(walletId: string, cents: number) { this.sent.push([walletId, cents]); return `tr_${this.sent.length}`; }} // ---- adapters/driving: an HTTP handler. Shape validation, then translate.type HttpRequest = { params: { id: string }; body: unknown };type HttpResponse = { status: number; json: unknown }; function makePayoutHandler(useCase: RequestPayout) { return async (req: HttpRequest): Promise<HttpResponse> => { const body = req.body as { cents?: unknown }; if (typeof body?.cents !== "number" || !Number.isInteger(body.cents) || body.cents <= 0) { return { status: 400, json: { error: "cents must be a positive integer" } }; } try { const out = await useCase.execute({ walletId: req.params.id, cents: body.cents }); return { status: 201, json: out }; } catch (e) { if (e instanceof DomainError) return { status: 422, json: { error: e.message } }; throw e; } };} // ---- composition root: the only place that knows every concrete class.const payouts = new FakePayouts();const handler = makePayoutHandler(new RequestPayout(new InMemoryWallets({ w1: 5000 }), payouts)); async function main() { console.log(await handler({ params: { id: "w1" }, body: { cents: 1200 } })); console.log(await handler({ params: { id: "w1" }, body: { cents: "lots" } })); console.log(await handler({ params: { id: "w1" }, body: { cents: 9000 } })); console.log("gateway calls:", payouts.sent);} main();
Output
Press Run (⌘ Enter) to see what happens.

Notice the gateway was called once. The bad request never reached the use case, and the overdraft was stopped by the entity before any money moved. The production driven adapter is boring on purpose: it maps rows to entities and nothing else.

src/adapters/db/drizzle-wallet-repository.ts
import { eq } from "drizzle-orm";
import type { Db } from "./client";
import { wallets } from "./schema";
import { Wallet } from "../../core/domain/wallet";
import type { WalletRepository } from "../../core/ports/wallet-repository";
 
export class DrizzleWalletRepository implements WalletRepository {
  constructor(private db: Db) {}
 
  async get(id: string) {
    const [row] = await this.db.select().from(wallets).where(eq(wallets.id, id));
    return row ? new Wallet(row.id, row.balanceCents) : undefined;
  }
 
  async save(wallet: Wallet) {
    await this.db.update(wallets)
      .set({ balanceCents: wallet.balance })
      .where(eq(wallets.id, wallet.id));
  }
}

In a Next.js app, a route handler in app/api/wallets/[id]/payouts/route.ts plays exactly the role of makePayoutHandler: parse, call the use case, map the result to a Response. A Server Action is another driving adapter for the same use case.

Quick check
Which import breaks the dependency rule?
Need a nudge? A hint rules out a wrong answer.

Use cases as interactors

A use case (Clean Architecture calls it an interactor) is one class or function per application action: RequestPayout, ApprovePayout, FreezeWallet. Not a WalletService with 30 methods. Small use cases are easy to name, easy to find from a ticket, and each has an obvious test file.

Each use case gets its own input and output DTOs: plain data, no framework types. That keeps HTTP details out (no req), and keeps entities from leaking out to callers who might mutate them or serialise private fields.

The use case is also the natural transaction boundary. One use case, one unit of work: everything it changes commits together or not at all. You expose that as a port too (UnitOfWork with commit() and rollback()), so the use case controls the transaction without importing a database driver. Python Backend Architecture showed the FastAPI version of that unit of work.

Look again at RequestPayout: it sends money, then saves the wallet. If the save fails, the money is gone and the balance is wrong. Ordering side effects is a use-case decision, and here the senior answer is to save the debit and a "payout requested" record in one transaction, then send the payment from that record (the outbox pattern, from Event-Driven Architecture). The architecture does not solve this for you, but it puts the decision in one obvious place.

Where validation lives

There are two different kinds of "validation", and they belong in different rings.

  • Shape validation happens at the driving adapter: is cents present, an integer, positive? Is the email a string that looks like an email? Use Zod in TypeScript or Pydantic in Python, and reject with a 400 before the use case runs.
  • Invariants live in the domain: a wallet cannot go below zero, a payout above 10,000 needs approval, a frozen wallet cannot pay out. These hold no matter which adapter called, so they must be in the entity or use case, never only in the route.

A useful test: if a queue consumer called the use case directly, would the rule still need to hold? If yes, it is an invariant and belongs inside.

Match the pairs0/5 matched

Where should each check live?

Choose an item, then its match on the other side.

The testing payoff

The reason teams accept the extra files is the test suite it buys.

  • Use-case tests run against in-memory adapters. No database, no network, milliseconds each. You can have hundreds and run them on every save.
  • Adapter integration tests check that each real adapter honours the port. Run one contract test suite against both the in-memory and the real adapter. If both pass, your fast tests are trustworthy, because the fake behaves like the real thing.
  • A handful of end-to-end tests prove the wiring in the composition root.
Python
import sqlite3from dataclasses import dataclassfrom typing import Protocol # ---- core: entity, port, use case@dataclassclass Wallet: id: str balance_cents: int class WalletRepository(Protocol): def get(self, wallet_id: str) -> Wallet | None: ... def save(self, wallet: Wallet) -> None: ... def top_up(wallets: WalletRepository, wallet_id: str, cents: int) -> int: wallet = wallets.get(wallet_id) or Wallet(wallet_id, 0) wallet.balance_cents += cents wallets.save(wallet) return wallet.balance_cents # ---- driven adapter 1: in memory, for fast use-case testsclass InMemoryWallets: def __init__(self): self.rows: dict[str, int] = {} def get(self, wallet_id): cents = self.rows.get(wallet_id) return None if cents is None else Wallet(wallet_id, cents) def save(self, wallet): self.rows[wallet.id] = wallet.balance_cents # ---- driven adapter 2: real SQLclass SqlWallets: def __init__(self, conn: sqlite3.Connection): self.conn = conn conn.execute("CREATE TABLE IF NOT EXISTS wallets (id TEXT PRIMARY KEY, cents INTEGER)") def get(self, wallet_id): row = self.conn.execute("SELECT cents FROM wallets WHERE id = ?", (wallet_id,)).fetchone() return None if row is None else Wallet(wallet_id, row[0]) def save(self, wallet): self.conn.execute( "INSERT INTO wallets VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET cents = excluded.cents", (wallet.id, wallet.balance_cents), ) # ---- one contract, run against every adapterdef check_wallet_repository_contract(make_repo): repo = make_repo() assert repo.get("missing") is None repo.save(Wallet("w1", 500)) repo.save(Wallet("w1", 700)) # save twice must update, not duplicate assert repo.get("w1") == Wallet("w1", 700) return "ok" for name, factory in [("in-memory", InMemoryWallets), ("sqlite", lambda: SqlWallets(sqlite3.connect(":memory:")))]: print(f"{name:>9} contract:", check_wallet_repository_contract(factory)) # ---- the fast use-case test only needs the in-memory adapterrepo = InMemoryWallets()print("use case:", top_up(repo, "w9", 250), top_up(repo, "w9", 250))
Output
Press Run (⌘ Enter) to see what happens.

In a real suite the contract is a parametrised pytest fixture, and the SQL leg runs against real Postgres in a container, because SQLite and Postgres differ on types, locking and ON CONFLICT details.

Predict the outputPython

What does this print?

class FakeMailer:
  def __init__(self):
      self.sent = []
  def send(self, to, subject):
      self.sent.append(to)

def invite(members, mailer, emails):
  for e in emails:
      if e not in members:
          members.add(e)
          mailer.send(e, "Welcome")
  return len(mailer.sent)

mailer = FakeMailer()
print(invite({"a@x.io"}, mailer, ["a@x.io", "b@x.io", "b@x.io"]))
Need a nudge? Hints walk you through it.

The cost, and when it is overkill

Hexagonal architecture is not free.

  • Mapping boilerplate. Row to entity, entity to DTO, DTO to JSON. For a screen that edits five fields, that is three copies of the same five fields.
  • Indirection. "Go to definition" lands on an interface, and new joiners have to learn where the real code is.
  • "Interface for everything." A port with exactly one implementation and no test fake is ceremony. Add a port where you have a real second implementation (a fake, a second provider) or a real reason to isolate (a slow or paid external service).
Your service is mostlyChooseWhy
CRUD over tables, thin rulesPlain layered, or framework defaultsMapping layers cost more than they save
Complex rules, money, state machinesHexagonal / cleanRules need isolated, fast, thorough tests
Many entry points (HTTP, queue, CLI) for one logicHexagonalEvery driving adapter reuses one use case
External providers you may swap or must fakePorts for those onlyIsolate the expensive or volatile edge
A prototype that may be thrown awayWhatever ships fastestYou do not know the rules yet

Mixing is normal and healthy. A service can keep its admin CRUD screens thin and put its payout engine behind ports.

Vertical slices, and how they combine

Vertical slice architecture (popularised by Jimmy Bogard) organises code by feature or use case instead of by layer. Each slice, such as request-payout/, holds its handler, its input schema, its use case and even its own query, side by side. Changing a feature means touching one folder, not five.

It is not really a rival. The common combination is: slices on the outside, the dependency rule on the inside. Each slice has its own use case and adapters, and they all share one domain/ folder of entities and a small set of shared ports. You get feature locality and still keep the rules free of frameworks.

Slices outside, rings inside
  • src/
  • domain/Wallet, Money, invariants: shared and pure
  • features/
  • request-payout/
  • route.tsdriving adapter
  • schema.tsZod input shape
  • request-payout.tsuse case and its ports
  • freeze-wallet/
  • route.ts
  • freeze-wallet.ts
  • adapters/
  • drizzle-wallet-repository.tsdriven adapter
  • stripe-payout-gateway.tsdriven adapter
  • main.tscomposition root

Enforce it in CI

Architecture that lives only in a diagram decays within months. Turn the rule into a failing check.

In Python, import-linter reads contracts from pyproject.toml and the lint-imports command fails the build on a violation. A layers contract says higher layers may import lower ones, never the reverse. A forbidden contract bans specific imports, and with include_external_packages it can ban frameworks from the core.

pyproject.toml
[tool.importlinter]
root_package = "payouts"
include_external_packages = true
 
[[tool.importlinter.contracts]]
name = "Rings point inward"
type = "layers"
layers = [
    "payouts.adapters",
    "payouts.application",
    "payouts.domain",
]
 
[[tool.importlinter.contracts]]
name = "Core is framework-free"
type = "forbidden"
source_modules = ["payouts.domain", "payouts.application"]
forbidden_modules = ["fastapi", "sqlalchemy", "stripe"]

In TypeScript, dependency-cruiser does the same with regex rules.

.dependency-cruiser.cjs
module.exports = {
  forbidden: [
    {
      name: "core-stays-pure",
      severity: "error",
      from: { path: "^src/core" },
      to: { path: "^(src/adapters|node_modules/(express|next|@prisma|drizzle-orm))" },
    },
  ],
};

Run npx depcruise src --config .dependency-cruiser.cjs in CI. Check each tool's docs for the current option names, since both evolve.

Key terms
dependency rule
Source code dependencies point only inward, toward the business rules. Inner code never names outer code.
driving port
The way the outside world asks the application to act, used by adapters such as HTTP handlers, consumers and CLIs.
driven port
An interface the application defines for something it needs, such as storage or payments, implemented by an outer adapter.
use case
One application action as its own class or function, with input and output DTOs. Also called an interactor.
composition root
The single place, such as main.ts, that creates concrete adapters and wires them into use cases.
contract test
One test suite run against every implementation of a port, so fakes and real adapters behave the same.
vertical slice
Organising code by feature, with each feature's handler, schema and use case in one folder.