Nguyen Le Phong

Foundations of Software ArchitecturePart 1 of 15

Ports and Adapters, Explained With One Checkout

Hexagonal architecture in plain words: what Cockburn meant by ports and adapters, the one dependency rule behind it, and how much of it your codebase really needs.

A ticket comes in: "move order emails from SendGrid to Amazon SES." Sounds like an afternoon. Then you open the checkout code and find the email client created inline, right next to the payment call and the SQL insert, with the rule for when an order counts as confirmed squeezed in between. The afternoon turns into three days, and most of that time goes into making sure you didn't break checkout.

Ports and Adapters, also known as hexagonal architecture, is a way of arranging code so that ticket stays an afternoon. Alistair Cockburn wrote it up in 2005. It isn't a framework and there's nothing to install. It's one rule about which code is allowed to know about which, and it works in any language. Below: where the idea came from, one checkout before and after, and how much of it a real codebase actually needs.

Where the pain comes from

Most apps start out the same friendly way. A controller calls a service, the service talks to a database and a couple of vendors, and everyone's happy. Give it a few months and the checkout looks like this:

Phong and two teammates lean over a desk covered in cables, integration cards and hand-drawn arrows, tracing a tangled checkout flow.
When every vendor and data path meets in one function, you have to hold all of them in your head to change any one of them.
// checkout.ts: everything in one place
class OrderService {
  async checkout(cart: Cart) {
    const db = new Pool({ connectionString: process.env.DB_URL })  // a specific database
    const stripe = new Stripe(process.env.STRIPE_KEY!)             // a payment vendor
    sgMail.setApiKey(process.env.SENDGRID_KEY!)                       // an email vendor

    // the business rules are buried between vendor calls
    const total = cart.items.reduce((sum, item) => sum + item.price, 0)
    await stripe.paymentIntents.create({ amount: total, currency: 'usd', payment_method: cart.paymentMethodId, confirm: true })
    await db.query('INSERT INTO orders (email, total) VALUES ($1, $2)', [cart.email, total])
    await sgMail.send({ to: cart.email, from: 'shop@example.com', templateId: 'order-confirmed' })
  }
}

No single line here is wrong. The trouble is what each line sits next to. What an order is, when it's valid, what "confirmed" means: all of that lives between a database driver and two vendor SDKs. You can't test the total without a live database. You can't leave SendGrid without editing the same function that charges money. And a new teammate learns how Stripe works before they learn how your orders work.

Cockburn described the same mess in his original paper, from both ends. Business logic creeps into UI code, so you can't test it without clicking through screens. On the other side, when the database is down or being changed, "the programmers can't work because their work is tied to the presence of the database." His point was that both problems come from one design mistake: business logic tangled up with the things outside it (Cockburn, Hexagonal Architecture).

The core question

How do you keep the code that holds your business rules apart from the parts you'll swap out over the years: databases, vendors, frameworks and UIs?

The idea in one picture

Cockburn's intent statement is worth reading word for word: "Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases." The word doing the work is "equally." A test script is as legitimate a caller as a human, and an in-memory fake is as legitimate a database as Postgres.

In code, that comes down to three moves. Put the business rules in the middle. Don't let that code import a framework, a database driver or a vendor SDK. Let the outside world reach it only through ports, which are interfaces the core defines, with adapters doing the real-world work on the other side.

The domain sits in the middle. Adapters plug into it through ports on both sides. DRIVING · calls the app DRIVEN · the app calls it Domain business rules, no vendors Web / Mobile UI REST / GraphQL Tests / CLI / Cron Database Email / SMS Payment vendor ● = a port (an interface the domain owns)
The hexagon is only a drawing. The domain in the middle never imports a framework or a vendor, and everything outside reaches it through a port. Adapters on the left drive the app. Adapters on the right get driven by it.

So why a hexagon? Cockburn says it plainly: "The hexagon is not a hexagon because the number six is important." The shape leaves room to draw ports all around the edge, which breaks the habit of picturing an app as a stack with the UI on top and the database at the bottom. In the same paper he notes that the apps he'd seen had two, three or four ports ("four is most I have encountered to date"). So please don't count your sides.

Three words, in plain English

The whole pattern runs on three terms:

  • Domain (the core): your business concepts and rules. Order, Money, "an empty cart can't check out." Reading it should tell you about the business and nothing about the tech stack.
  • Port: an interface the core owns, describing a conversation it needs to have, like "save this order" or "charge this amount." Cockburn's advice is to design interfaces "by purpose rather than by technology," so a port's name and types never mention a vendor.
  • Adapter: the code that fulfils a port with real technology, such as PostgresOrderRepo or StripeGateway. This is the only place Stripe, Postgres or React get to appear.

The one subtle part is that ports face two directions.

A request goes from a driving adapter, through the use case, out to a driven adapter and the vendor behind it. PRIMARY · driving SECONDARY · driven User / Test actor Controller / CLI driving adapter Use case domain rules Repo / Gateway driven adapter DB / Vendor input port output port
Same core, two kinds of adapter. A driving (primary) adapter sends a request in through an input port. The core sends work out through an output port to a driven (secondary) adapter. These arrows show who calls whom at runtime. Source-code dependencies run differently, as the next sections show.
  • Driving (primary) adapters call into your app: a web controller, a CLI command, a test. They go through an input port, which is usually your use case.
  • Driven (secondary) adapters get called by your app: a database, an email service, a payment API. They implement an output port the core defined.
A quick way to tell them apart

Ask who starts the conversation. In Cockburn's words, a primary actor "drives the application," and a secondary actor is one the application drives. A customer clicking "Buy" is driving. The payment vendor is driven.

One checkout, before and after

Back to that checkout. Start by writing down what it needs from the outside world, using only words from your business:

Phong compares a messy spread of integration cards on one side of the table with a tidy core diagram on the other, while a teammate traces the boundary line between them.
The real work is moving vendor detail out to the edge, so the rules in the middle stay easy to read.
// ports.ts: the core's vocabulary, no vendor names allowed
interface PaymentGateway  { charge(amount: Money, paymentMethodId: string): Promise<Receipt> }
interface OrderRepository { save(order: Order): Promise<void> }
interface Notifier        { orderConfirmed(order: Order): Promise<void> }

The use case now depends on those three interfaces and nothing else. Read it out loud and it sounds like a description of checking out:

// checkout-service.ts: knows the ports, never the vendors
class CheckoutService {
  constructor(
    private payments: PaymentGateway,
    private orders: OrderRepository,
    private notify: Notifier,
  ) {}

  async checkout(cart: Cart): Promise<Order> {
    const order = Order.fromCart(cart)         // pure business rule
    await this.payments.charge(order.total, cart.paymentMethodId)
    await this.orders.save(order)
    await this.notify.orderConfirmed(order)
    return order
  }
}

The vendors move into adapters. Here's the real Postgres adapter next to the fake you'd use in tests:

// adapters/postgres-order-repo.ts: the only file that writes SQL for orders
class PostgresOrderRepo implements OrderRepository {
  constructor(private db: Pool) {}

  async save(order: Order): Promise<void> {
    await this.db.query(
      'INSERT INTO orders (id, email, total_cents) VALUES ($1, $2, $3)',
      [order.id, order.email, order.total.cents],
    )
  }
}

// test/fakes.ts: same port, no database
class InMemoryOrders implements OrderRepository {
  saved: Order[] = []
  async save(order: Order): Promise<void> {
    this.saved.push(order)
  }
}

// in a test (FakePayments and NullNotifier follow the same shape)
const orders = new InMemoryOrders()
const service = new CheckoutService(new FakePayments(), orders, new NullNotifier())

Look at what moved. Stripe, Postgres and SendGrid are details at the edge now. The rules sit in the middle, readable and testable, with no idea those vendors exist. You can run the whole checkout from a test with no network at all, which was exactly Cockburn's goal: his paper walks through a mock database adapter "that sits in memory and doesn't depend on the presence of the real database at all." In Gerard Meszaros's test double vocabulary, which Martin Fowler sums up in Test Double, this kind of stand-in is a fake: an object with a working implementation that takes a shortcut, like an in-memory database.

The one rule that holds it together

If you keep one thing from this post, keep this: source-code dependencies point inward. Adapters, frameworks and I/O code may import the core. The core imports nothing from outside itself. Robert C. Martin later wrote the same rule into Clean Architecture as "source code dependencies can only point inwards," and he lists hexagonal architecture among the ideas it grew from (The Clean Architecture).

Source-code dependencies point inward, toward the domain. ADAPTERS · frameworks · databases · HTTP · I/O APPLICATION · use cases + ports Domain pure rules Outer rings may know inner rings. Never the reverse.
Source-code dependencies only point inward. The domain doesn't know the database exists, while the database adapter knows the domain. Rewrite an outer ring and the domain files stay the same.

Compare this with the runtime arrows in the earlier diagram. At runtime, the checkout calls out to Stripe. In the source code, the Stripe adapter imports PaymentGateway from the core, so the arrow points in. That flip is the Dependency Inversion Principle (the D in SOLID), and Cockburn's paper cites it directly. Handing the real adapters to the use case at startup is dependency injection, which gets its own post.

The payoff is that you can swap the web framework or the database and the domain files won't show up in the diff, because nothing at the edge has an import path back into the core. One honest caveat: this only holds if the ports talk in business terms. A repository shaped around SQL joins will still hurt when you move to a document store.

Driving vs driven, in daily work

The split matters day to day because it tells you who owns each interface.

  • For a driven port (database, email), the core owns the interface and the adapter bends to fit it. That's what makes vendors swappable.
  • For a driving port (your use cases), the application owns the interface and HTTP, a CLI or a test harness calls it. The same checkout can serve a REST API today and a queue consumer or a nightly job later, with zero rule changes.

Here's a handy leak test. A new way in, say a Slack bot, should need only a new driving adapter. A new vendor, say Adyen next to Stripe, should need only a new driven adapter. If either one makes you open the domain, something has slipped through a port.

Phong and teammates compare two adapter cards around a shared core diagram, checking how different integrations plug into the same business flow.
Once the core owns the contract, the team can compare and replace adapters without reopening the business rules.

How much of it at each stage

A lot of architecture advice pretends one dose fits everyone. It doesn't. Here's a rough guide by stage. Treat it as a starting point and adjust it to where your code actually hurts:

StageThe pain it removesHow much to apply
Solo / early startup You picked a database and a payment provider in a hurry and worry about being stuck with them. One or two ports at most, usually the database and payments. Call everything else directly. Speed wins here.
Small, growing team Tests hit a real database and a vendor sandbox, so they're slow and flaky and people stop running them. Put ports around the I/O that slows your tests down. Fakes keep unit tests fast, and the domain gets easier for new hires to read.
Scale-up, several teams Teams step on each other, and a cost-cutting vendor switch turns into a month-long rewrite. Ports become contracts between teams. Switching a vendor means writing one adapter.
Enterprise Legacy systems, regional vendors, audits and procurement rules that ask for no single-vendor lock-in. Several adapters per port (old and new side by side), gradual migrations and vendor independence as a written requirement.

Three made-up scenes you'll probably recognize

Say a 10-person online shop wraps email behind a one-method Notifier port early on. Two years later the email bill jumps and they want to leave SendGrid for Amazon SES. With the port in place, that's one new adapter plus one changed line of wiring. The order logic doesn't move.

Now take a fintech scale-up that has to route payments through a local provider in one country and an international one elsewhere, chosen per transaction. If PaymentGateway is a port, "which provider" turns into a routing adapter behind the interface, and the core still just says "charge this amount."

Or a bank with an old mainframe ledger that nobody can replace in one go. It defines an AccountLedger port with two adapters, one for the mainframe and one for the new core system, then moves traffic over a little at a time. Martin Fowler calls this kind of gradual replacement a strangler fig. Teams keep building features against the port while the migration happens underneath.

Ports and Adapters vs the classic layered stack

Most of us come from layered code: UI on top, services in the middle, database at the bottom. Cockburn's complaint about layers is a practical one. In theory they work, but "people tend not to take the 'lines' in the layered drawing seriously," so application logic leaks across them. Here's how the two compare:

QuestionClassic layered (UI → service → DB)Ports and Adapters
Who depends on whom?Top-down. Each layer depends on the one below, ending at the database.Everything depends inward, ending at the domain. The database is one more plug-in.
Can you test rules without a DB?Usually no, because the service reaches the database directly.Yes. Pass in a fake repository and run with no database or network.
Swap a vendor?You edit the service layer and the change spreads.You write one new adapter and the domain stays the same.
Where do business rules live?Often spread across services and the database.In the domain, in business language.
CostLittle ceremony, but you get tied to your stack over time.A few extra interfaces up front. They pay off once things start changing.

The headline difference is the direction of the arrows. In the classic stack, everything ends up depending on the database. Here, the database adapter depends on your core.

When to reach for it, and when to skip it

Match the effort to the stakes. Ports and Adapters earns its keep when:

  • The app has real business rules worth protecting, more than CRUD over a table.
  • You expect to swap or add integrations over its life: vendors, databases, channels.
  • You want fast, deterministic unit tests and you're tired of waiting on sandboxes.
  • Several teams or a long lifespan make clear boundaries pay for themselves.

Go light, or skip it, when:

  • It's a thin CRUD app or a throwaway prototype, where the extra layer is pure overhead.
  • The "domain" is basically your database schema, so there's nothing to protect.
  • You're shipping solo and fast, and a future rewrite would cost less than the ceremony today.
Don't cargo-cult it

Three interfaces around a plain CRUD endpoint won't make it clean. They'll make it harder to read. Architecture is a price you pay for code that's easy to change, so if nothing around that code is going to change, skip the bill.

Common mistakes and how to fix them

  • Leaky ports. If PaymentGateway returns a Stripe.PaymentIntent, the vendor has walked straight through the port. Ports should speak your own types only, like Receipt and Money.
  • An empty core. If the real logic lives in adapters and the domain is a pile of data classes, the boundary is in the wrong place. Move the rules inward.
  • One giant port. A single IRepository with 40 methods is a junk drawer. Cockburn thought of a port as one purposeful conversation and admitted the right count is "largely a matter of taste." In code, splitting a conversation into a few small, well-named interfaces (OrderRepository, InventoryRepository) usually reads better.
  • Wire formats in the core. The JSON you send over HTTP is a different thing from your domain entity. Let adapters translate between the two.
  • Interfaces for everything. Only what crosses the boundary needs a port: I/O, vendors and ways into the app. Add one when you feel the pain.

How to start on Monday

No rewrite needed. Add one seam where it hurts most, then stop:

  1. Pick the dependency that hurts most. Usually that's the database or a flaky vendor.
  2. Write the interface you wish you had, in business words. save(order) beats execSql(...).
  3. Move the vendor code into an adapter that implements it. Leave everything else alone for now.
  4. Pass the adapter in through the constructor instead of creating it inline, and write one fake for tests.
  5. Enjoy the fast tests, then repeat only where churn or test pain justifies another port.

One seam gets you fast tests around your worst integration and a core that starts to read like your business. If you'd like the full walk-through on a single feature, folders and naming included, Hexagonal Architecture in Practice picks up from here.

Try this week

  • Find one function where a vendor SDK and a business rule share the same lines. That's your first seam.
  • Write the port for it in business words, with no vendor types in the signature.
  • Write an in-memory fake and one test that runs the use case with no network.
  • Grep your core for framework or SDK imports and move one of them out.
  • The next time someone proposes a new port, ask which change or which test pain it pays for.

Next in the series: Ports and Adapters next to Onion and Clean Architecture, three names for the same direction of arrows, and where they really differ. Read it in Clean, Onion and Hexagonal Architecture.

What did you think?

Frequently asked questions

What is the difference between a port and an adapter?
A port is an interface the core of your app owns, written in business terms, such as OrderRepository.save(order). An adapter is the code that fulfils that interface with real technology, such as a Postgres repository or a Stripe gateway. The core only knows the port, so you can swap the adapter without touching business rules.
Is hexagonal architecture the same as Ports and Adapters?
Yes. Alistair Cockburn wrote the pattern up in 2005 as Ports and Adapters and gave hexagonal architecture as its other name. The hexagon is only a drawing that leaves room for several ports around the edge. Cockburn says the number six has no special meaning.
What are driving and driven adapters?
Driving (primary) adapters call into your app, like a web controller, a CLI command or a test. Driven (secondary) adapters are called by your app, like a database, an email service or a payment API. The easy way to tell them apart is to ask who starts the conversation.
When should I not use Ports and Adapters?
Skip it or keep it very light for thin CRUD apps, throwaway prototypes, and code where the domain is basically the database schema. The extra interfaces only pay off when there are real business rules to protect or integrations you expect to change.