Skip to content
Lesson 33

Hexagonal and clean architecture

Keep your business rules in the middle and plug the tools in from outside. Learn ports, adapters and the dependency rule, why they make a vendor switch cheap and tests fast, and where they're not worth it.

The lesson in text

Click a paragraph to hear it.

01Twenty-three files

Monday morning. Karim, the CTO, has news from finance. A second payment provider, Adyen, would save StayHub about €30,000 a month in card fees. His question is simple: how fast can we switch?

You ask Claude Code to look. Stripe, the current provider, is named in 23 files, three of them inside the booking rules. And the payment tests take 14 minutes, and fail about one run in ten.

That's not a payments problem. It's an architecture problem: which part of the code knows about which. Today you'll learn hexagonal architecture, its cousin clean architecture, and the one rule behind both.

And you'll see how one shortcut around that rule blocked thirty-one guests' cards in a single morning.

02The wall socket

Think of the sockets in your home. The house decides their shape. Any lamp, kettle or charger whose plug fits that shape just works. You never rewire the walls to change your kettle.

Now imagine a house where the builder wired one brand of kettle straight into the wall. No socket. To try another kettle, you open the wall.

That second house is StayHub today. The booking rules call Stripe directly, by name, in twenty-three places. Changing provider means opening the walls.

And abroad, when your plug doesn't fit, you don't rebuild the hotel. You use a small travel adapter: one side fits the wall, the other fits your plug. It translates between the two.

The wall socket, and your code
At homeIn your codeAt StayHub
The houseThe core: the business rulesDeposits, refunds, what to do when a card is declined
The socket, shaped by the houseA port, written in the core's wordsPaymentPort: charge, refund; paid, declined, provider unavailable
The travel adapterAn adapter: plugs a real tool in and translatesThe Stripe adapter, the Adyen adapter, a fake for tests
The kettleThe tool (a detail)Stripe, Adyen, PostgreSQL, the email service
A kettle wired into the wallRules that name the vendor directlyStripe named in 23 files, 3 inside the booking rules
The house decides the socket's shape; any plug that fits works. A travel adapter translates between two shapes, so nobody rewires the walls.

03The core and the details

Every app has two kinds of code. The core is the business rules, the reason the app exists. At StayHub: how much deposit a booking needs, when a refund is allowed, what to do when a card is declined.

The details are the tools the core uses: the database, the payment provider, the email service, the web framework. Details matter, but they can be replaced. Stripe today, Adyen tomorrow.

The core changes when the business changes. A detail changes when a vendor changes its price or its rules. Different reasons, different times. So they should live apart.

Code depends on other code when it names it and uses its words: if that code changes, it must change too. At StayHub, the deposit rule depends on Stripe. The most valuable code depends on the most changeable code.

The core and the details
The core
  • · How much deposit a booking needs
  • · When a refund is allowed
  • · What to do when a card is declined
Changes when the business changes.
The details
  • · The database
  • · The payment provider
  • · The email service, the web framework
Change when a vendor changes its price or its rules.
Code depends on other code when it names it and uses its words. Today StayHub's deposit rule depends on Stripe: the most valuable code depends on the most changeable code.

04Ports and adapters

Hexagonal architecture fixes this with two ideas, named after our sockets. The first is a port: a socket that the core defines, in its own words.

For payments, the port says: I need to charge an amount, and to refund one. And I understand three answers: paid, declined, or provider unavailable. Nothing about Stripe. Nothing about Adyen.

The payment port, in StayHub's own words
interface PaymentPort {lives in the core, next to the booking rules
charge(amount, card, idempotencyKey)take money once, even if asked twice
refund(paymentId, amount)give money back
}
answer: "paid" | "declined" | "provider_unavailable"the only answers the core understands
The vendor saysIts adapter answersThe core does
Stripe: success · Adyen: AuthorisedpaidConfirms the booking
Stripe: card_declined · Adyen: RefuseddeclinedAsks the guest for another card. Never retries.
Timeout, network error, anything unknownprovider_unavailableMay retry, with the same idempotency key
Nothing in the port names Stripe or Adyen. Each adapter translates its vendor's words into these three answers.

The second idea is an adapter: a small piece of code that plugs a real tool into a port. The Stripe adapter turns charge into Stripe's calls, and Stripe's answers back into paid, declined or unavailable. An Adyen adapter does the same for Adyen.

Adapters work on both sides. The web adapter turns a guest's request into a command for the core: book this room. On the other side, adapters for the database and payments do what the core asks.

The name comes from the drawing: the core as a hexagon, ports on its sides, adapters all around. The six sides mean nothing special. Only adapters know the vendors' words, so a new provider means one new adapter, not twenty-three files.

05The arrows point inward

Behind all of this is one rule, called the dependency rule: code only points inward. Adapters know about the core. The core knows nothing about the adapters.

It can feel backwards: when a guest pays, the core does reach Adyen. But it goes through the port, and only the adapter knows Adyen's name. Like a socket: power flows out to the kettle, but the house never needs to know which kettle it is.

Which way do the arrows point?
Before: the rules name the vendor
Booking rules
↓ imports Stripe
Stripe's library
After: arrows point inward
Booking rules + PaymentPort (the core)
↑ implements PaymentPort
Stripe adapter
Adyen adapter
Fake
An arrow here means "names and uses". At runtime the core still reaches Adyen, but only through the port, and only the adapter knows Adyen's name.

Clean architecture draws the same idea as rings. Business rules in the centre. Around them, the use cases: book a room, cancel a booking. Then the adapters, then the frameworks and tools. Arrows only cross the rings inward.

Clean architecture: the same idea as rings
Frameworks and tools
Next.js, PostgreSQL, Stripe, Adyen
Adapters
web controller, database adapter, payment adapters
Use cases
book a room, cancel a booking
Business rules
deposit, refund policy
Dependencies only cross the rings inward. One file at the very edge (often main) picks which adapter plugs into which port: at StayHub, Adyen for 10% of EU bookings.

One file at the very edge, often called main, does the wiring. It picks which adapter plugs into which port. At StayHub, it's one line: Adyen for 10% of EU bookings, Stripe for the rest.

06A pretend kettle for tests

There's a bonus. If the core only talks to a port, you can plug in a pretend adapter for tests: a fake. It answers paid or declined on demand. No network, no keys, no waiting.

StayHub's payment tests took 14 minutes, needed Stripe test keys, and failed one run in ten. With a fake, the deposit and refund rules ran in about 6 seconds, every time.

But a fake can lie. So one shared set of contract tests runs against the fake, Stripe and Adyen alike. If all three pass, the port really fits them all.

07The port that spoke Stripe

Now the incident. Under deadline, the first port was written by copying Stripe's own functions. Inside, the core still checked Stripe's error code: "card_declined". Anything else meant the provider was down: try again, up to three times.

Thursday, 11:40. Adyen goes live for ten percent of EU bookings. A guest's card is declined. But Adyen doesn't say "card_declined". It says "Refused".

The core doesn't know that word. So it treats the decline as an outage and retries. Three retries make four charge attempts in a few seconds. To a bank, that looks like fraud.

By the time Omar, the on-call engineer, spotted it, thirty-one guests had their cards blocked by their banks. All of them had been told: payment provider unavailable.

The port that spoke Stripe
  1. 1
    Adyen goes live for 10% of EU bookings
    Thursday, 11:40
  2. 2
    A card is declined: Adyen says "Refused"
    The core only knows Stripe's "card_declined"
  3. 3
    Unknown answer = outage, so retry ×3
    4 charge attempts in a few seconds
  4. 4
    Banks see fraud and block the cards
    31 guests
  5. 5
    Every guest is told "provider unavailable"
    The wrong message too
The fix: each adapter turns its vendor's decline into the port's own answer, declined, and the core never retries a decline.

The fix: the core only sees the port's own answers. Each adapter translates: Stripe's "card_declined" and Adyen's "Refused" both become declined, and a decline is never retried. A port shaped like one vendor is that vendor in disguise.

08Where it's worth it

The next day, Omar wanted ports on everything: admin screens, reports, photo uploads. Lina, the senior engineer, disagreed: the bug came from a badly shaped port, not a missing one.

Ports cost more files and a translation step. They pay off where the rules are rich or the tools will change: payments, email and the database. The admin screen that edits a hotel's address has no rules to protect. Plain code is fine there.

Where ports are worth it
Part of StayHubPorts?Why
PaymentsYesTwo providers, money at stake, slow flaky tests
Booking rulesYesRich rules: deposits, refunds, cancellations
Email, the databaseUsuallyExternal tools that change and slow tests down
Admin screen: edit a hotel's addressNoNo rules to protect; plain code is clearer
Ports cost more files and a translation step. Put them where rules are rich or tools will change; write the choice down so the whole team follows it.

So the team wrote the choice down: ports for Payments and Booking, plain code for simple screens. Writing decisions down is the last lesson of this module.

09Your job as lead

Claude Code will happily build ports and adapters. But left alone, it tends to copy the vendor's shape, because that's what the vendor's documentation shows. The words of the port are your decision.

Ask it: list every place we use this vendor, grouped by what the core needs. Propose a port in our business words, with our own answers and no vendor types. Wait for my approval.

Then check three things. The port file never names the vendor. Each adapter turns a decline into declined, and nothing retries it. And the core's tests run in seconds, with no keys.

Let's recap. The core holds your business rules. A port is a socket the core defines in its own words. An adapter plugs a real tool in and translates. The arrows point inward. The text, the diagrams and the questions are below the video. Next: serverless, code that runs only when it's needed.

Check yourself

0/10 answered
  1. 1In hexagonal architecture, what is a port?

  2. 2What does an adapter do?

  3. 3What does the dependency rule say?

  4. 4Karim asks why switching from Stripe to Adyen is slow. Stripe is named in 23 files, 3 inside the booking rules. What's the real problem?

  5. 5Claude Code proposes a PaymentPort with the methods createPaymentIntent and confirmPaymentIntent, using Stripe's types, and says "Adyen can implement this too". What do you do?

  6. 6Adyen went live for 10% of EU bookings and 31 guests had their cards blocked. Why?

  7. 7Where should Adyen's "Refused" be turned into the core's answer "declined"?

  8. 8Payment tests took 14 minutes and failed one run in ten. With ports, what makes them run in about 6 seconds?

  9. 9After the incident, a teammate wants ports on every screen, including the admin page that edits a hotel's address. What's the better call?

  10. 10Claude Code finishes the PaymentPort. Which check tells you the most?

Free account

Save your progress — create a free account

Free. No card. Your finished lessons follow you to any device, and you can ask questions in the community.

Create my free account
Founding members

Every lesson is free while we build. Lock in €9/month for later.

The first 100 members keep the founding price for as long as they stay. Reserving is free: no card, nothing is charged.

See the founding offer

Questions from the community

All questions →