The ticket looks like a before-lunch job. Support wants a button that refunds an order, emails the buyer and leaves an audit line for finance. The rules from the meeting fit on a sticky note: paid orders only, nothing older than 30 days, and the email never goes out before the refund is recorded. Then you open the codebase. That one button touches a controller, the payment SDK, a database transaction, an email template and three tests that crawl because they need real infrastructure.
This post walks that single feature through Hexagonal Architecture, from the first sentence to the last test. If you want the vocabulary first, Ports and Adapters, Explained With One Checkout covers it. Here we stay hands-on: where the boundary goes, what the code looks like, how testing changes and where the pattern stops paying for itself.
Write the rule as one sentence first
Alistair Cockburn wrote the pattern up in 2005 with a very practical goal: an application that can be driven just as well by "users, programs, automated test or batch scripts", and that you can build and test without its real databases and devices (Hexagonal Architecture). The hexagon itself means nothing special. Cockburn picked the shape so there's room to draw several ports, and to get away from the one-dimensional layer cake.
The fastest way to find the inside of your hexagon is to skip interfaces for now and write the feature as plain English:
A support agent asks to refund an order. If the order is paid and less than 30 days old, we record the refund, send the money back, log it for finance and tell the buyer.
Now circle the nouns. Order, paid, 30 days, refund, finance log, buyer: that's the product talking, and it's the inside. HTTP, SQL, Stripe and SMTP never show up in the sentence. Everything that brings the request in or carries out a side effect sits outside:
| Piece | Side | What it does for the core |
|---|---|---|
| HTTP controller, admin CLI | Driving (calls in) | Turns a request into a call to the use case |
| Postgres | Driven (called out) | Loads orders, stores refunds |
| Payment provider SDK | Driven | Sends the money back |
| Email service | Driven | Tells the buyer |
| Audit log | Driven | Keeps the record finance asks for |
Name ports after the feature, adapters after the tool
Cockburn describes a port as something that "identifies a purposeful conversation". So a port should read like the conversation the refund needs: find an order, save a refund, return a payment, tell the buyer. If a vendor name sneaks into a port, the boundary is already leaking. StripePaymentGateway is a fine adapter name and a poor port name.
Here's the whole core in TypeScript. It's short on purpose:
export type Order = {
id: string
status: 'paid' | 'pending' | 'refunded'
paidAt: Date
totalCents: number
paymentId: string
}
export type Refund = { orderId: string; amountCents: number; requestedAt: Date }
export type RefundResult =
| { ok: true; refund: Refund }
| { ok: false; reason: 'not_found' | 'not_paid' | 'window_closed' }
// Ports: what the refund needs, named in product words
export interface OrderStore {
findById(orderId: string): Promise<Order | null>
saveRefund(refund: Refund): Promise<void>
}
export interface PaymentGateway {
refund(paymentId: string, amountCents: number, idempotencyKey: string): Promise<void>
}
export interface BuyerNotifier {
refundIssued(order: Order): Promise<void>
}
const REFUND_WINDOW_MS = 30 * 24 * 60 * 60 * 1000
// The use case: the rule lives here and nowhere else
export class RequestRefund {
constructor(
private readonly orders: OrderStore,
private readonly payments: PaymentGateway,
private readonly notifier: BuyerNotifier,
) {}
async run(orderId: string, now: Date): Promise<RefundResult> {
const order = await this.orders.findById(orderId)
if (!order) return { ok: false, reason: 'not_found' }
if (order.status !== 'paid') return { ok: false, reason: 'not_paid' }
if (now.getTime() - order.paidAt.getTime() > REFUND_WINDOW_MS) {
return { ok: false, reason: 'window_closed' }
}
const refund = { orderId, amountCents: order.totalCents, requestedAt: now }
await this.orders.saveRefund(refund)
await this.payments.refund(order.paymentId, order.totalCents, `refund-${orderId}`)
await this.notifier.refundIssued(order)
return { ok: true, refund }
}
}
A few things to notice. The use case imports nothing from Express, Postgres or Stripe. It takes now as an argument, so tests never have to fake the clock. It returns its own result type instead of throwing HTTP errors. The audit log would be one more port with the same shape as BuyerNotifier; it's left out to keep the sample readable.
One honest caveat about the order of steps. If the process dies between saveRefund and the payment call, you have a refund on record and no money moved. Real code would save the refund as pending, mark it done after the gateway answers and let a retry finish the job. The idempotency key is what makes that retry safe: Stripe stores the result of the first request with a given key and returns the same result for repeats, so a retried refund won't send money twice (Stripe idempotent requests). For more on that second-click problem, see Designing APIs That Survive the Second Click.
Keep the controller thin
The driving side gets the same treatment. The controller parses the request, checks who's asking and maps the result back to HTTP. No refund rule lives here:
app.post('/orders/:id/refund', async (req, res) => {
const result = await requestRefund.run(req.params.id, new Date())
if (result.ok) return res.status(201).json(result.refund)
const status = result.reason === 'not_found' ? 404 : 409
return res.status(status).json({ error: result.reason })
})
Next quarter, finance asks for a script that refunds a batch of orders from a CSV. The script becomes a second driving adapter that calls the same run. Nobody copies the 30-day rule into a second place, which is exactly what Cockburn meant by an app that a user and a batch script can drive equally well.
Test the rule without the outside world
This is where the pattern earns its keep. Gerard Meszaros's name for the stand-ins is test doubles, and the useful kind here is the fake. Fakes "actually have working implementations, but usually take some shortcut", like keeping data in memory instead of a database (Martin Fowler, TestDouble). With three tiny fakes, the riskiest rule in the feature gets a test with no database, no payment sandbox and no inbox:
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { RequestRefund, type Order } from './request-refund'
test('refuses orders older than 30 days and never touches the gateway', async () => {
const order: Order = {
id: 'o1', status: 'paid', paidAt: new Date('2026-01-01'),
totalCents: 4900, paymentId: 'p1',
}
const orders = {
async findById(id: string) { return id === order.id ? order : null },
async saveRefund() {},
}
const payments = { calls: 0, async refund() { this.calls++ } }
const notifier = { async refundIssued() {} }
const result = await new RequestRefund(orders, payments, notifier)
.run('o1', new Date('2026-02-15'))
assert.deepEqual(result, { ok: false, reason: 'window_closed' })
assert.equal(payments.calls, 0)
})
Two more tests cover the rest of the promise. A paid order inside the window comes back ok and calls the gateway exactly once. A third test pushes each call into an array and checks that saveRefund comes before refundIssued, because "never email before the refund is recorded" was the one rule support cared about most.
Adapters get their own, slower tests
The real adapters still need tests, just different ones and fewer of them. The Postgres adapter gets a test against a real database: mapping, the transaction, the query. The Stripe adapter runs against test mode to check the request shape, how vendor errors map to your own and that the idempotency key actually goes out. The email adapter checks that the template renders. These tests are slow, and that's fine, because they live at the edge and don't have to tell you whether the 30-day rule works.
Two mistakes that turn it into ceremony
- A port for everything. Date math, formatters and pure helpers don't need an interface. Ports go where the core meets I/O, a vendor or a delivery mechanism. Anywhere else, an interface is extra reading with nothing behind it.
- Outside types sneaking in. If the use case takes a raw request, returns an ORM row or throws a Stripe exception, the boundary exists only in the folder names. The adapter translates the messy outside shape into the core's own types and back. That feels like extra typing on day one. On day thirty, when a second payment provider shows up, it's the reason the change touches one file.
When it pays, and when to skip it
The payoff is in changes that would otherwise ripple. AWS's guidance on the pattern makes the same point: the domain doesn't know about adapter implementations, so moving from a SQL to a NoSQL database means writing a new adapter while the domain model stays as it is (AWS Prescriptive Guidance). The same page recommends modeling each operation as a command plus a handler, which is what RequestRefund is.
The cost is real too: more names to pick, more files to open and wiring to set up somewhere (plain constructor injection is enough, see Dependency Injection and Inversion of Control). For a thin CRUD screen that edits one table with no real policy, a route handler talking to the ORM is the kinder design.
Three signals make it worth trying on a feature:
- The feature has rules people argue about in product words, not just fields in a table.
- At least one outside dependency is likely to change, fail or be painful to test.
- The team has already felt slow tests or one change spreading across many files.
You don't need to convert the whole app. One hexagonal slice around the feature that hurts is a perfectly good place to stop. If you're wondering how this relates to Onion and Clean Architecture, they share one rule drawn three ways.
Try this week
- Pick one feature that already hurts a little and write its rule as one plain sentence.
- Circle the product words. Everything else is an adapter.
- Add ports only where the core touches I/O or a vendor, and name them after the conversation.
- Write one fast core test for the rule that would cost money if it broke.
- Then stop, and leave the rest of the codebase alone until it asks for the same.