Nguyen Le Phong

Foundations of Software ArchitecturePart 2 of 15

Clean, Onion and Hexagonal Architecture Are One Rule Drawn Three Ways

Hexagonal, Onion and Clean Architecture share one rule: dependencies point inward.

Open three architecture books and you get three drawings: a hexagon with plugs on its sides, an onion with rings, and a set of colored circles with very firm labels. Each comes with its own vocabulary and its own fans. Read them back to back and it feels like three people arguing about the best way to say the same sentence.

That's because they mostly are saying the same sentence. Robert C. Martin says so himself. In the 2012 post that introduced Clean Architecture, he lists Hexagonal and Onion among its sources and writes that they "all have the same objective, which is the separation of concerns" (The Clean Architecture). So this post won't crown a winner. It covers the rule all three share, what each author added on top, how their words map to each other, and how much of it your team needs right now.

Three engineers stand at a workshop table; on the whiteboard behind them a hexagon, onion rings and concentric circles all point to one shared core.
Three names and three drawings around one core. The part that survives every sketch is the direction of the arrows.

The rule all three share

Martin calls it the Dependency Rule: "source code dependencies can only point inwards." Put another way, "no name in an outer circle can be mentioned by an inner circle." Business rules sit in the middle. Databases, web frameworks, payment SDKs and email vendors sit outside. Outer code may import inner code. Inner code never imports outer code.

Why bother? Because the outside is where change happens. You swap a payment provider, move to a new database, add a mobile client. Palermo, writing in 2008, noted that the industry had changed its data access techniques at least every three years, so any long-lived system should expect to do it again (The Onion Architecture, part 1). If your business rules import those details, every vendor change ripples into the code you care about most. If they don't, the change stays at the edge.

The nice part is that you can check the rule by hand. Open any file in your core and read only the imports. If you see an ORM, an HTTP client or a framework annotation, an arrow points the wrong way, whichever diagram your team prefers.

The one rule

Inner code defines the interfaces it needs. Outer code implements them. A core file that imports a framework breaks the architecture, whatever name you've given it.

Hexagonal Architecture (Ports and Adapters)

Alistair Cockburn published Hexagonal Architecture in 2005, also under the name Ports and Adapters (Hexagonal Architecture). His stated intent is to let an application "equally be driven by users, programs, automated test or batch scripts," and to build and test it without its real devices and databases.

A port, in his words, "identifies a purposeful conversation": taking orders, storing orders, sending notifications. An adapter is the technology-specific piece that plugs into a port, such as a REST controller, a Postgres repository or an in-memory fake for tests. Cockburn borrows "primary" and "secondary" from use cases. Primary actors drive the application (a user, a test, a cron job). Secondary actors are driven by it (a database, an email service). Plenty of people say "driving" and "driven" instead.

The shape itself means nothing. Cockburn writes that it's "not a hexagon because the number six is important." The hexagon leaves room to draw ports, and he notes there are usually only two to four. The difference that matters is inside versus outside. Left versus right is a drawing detail.

What Hexagonal adds is symmetry and concrete slots. Incoming and outgoing calls get the same treatment, and every seam has a name you can point at in code. What it leaves open is how to organize the inside of the hexagon. For a full walk-through with code, see Ports and Adapters, explained simply and Hexagonal Architecture in practice.

Onion Architecture

Jeffrey Palermo described Onion Architecture in a 2008 blog series and credits Cockburn for the shared premise: push infrastructure out and write adapters so it can't couple itself to the core. His picture is rings. The Domain Model sits at the very center. His diagram draws domain services and application services around it, and he says plainly that "the number of layers in the application core will vary." The outer ring holds UI, infrastructure and tests, the parts he reserves "for things that change often."

Onion spells out one idea the other two leave implicit: "The database is not the center. It is external." Palermo was pushing back on the classic UI, business logic, data access stack, where everything ends up depending on the database. His standard example is the repository. The interface lives in the core, and the class that talks to a real database lives at the edge:

// core/orders/OrderRepository.ts: the core owns the interface
import type { Order } from "./Order";

export interface OrderRepository {
  findById(id: string): Promise<Order | undefined>;
  save(order: Order): Promise<void>;
}

// infrastructure/SqlOrderRepository.ts: the edge implements it
import type { Order } from "../core/orders/Order";
import type { OrderRepository } from "../core/orders/OrderRepository";
import { db } from "./db";

export class SqlOrderRepository implements OrderRepository {
  async findById(id: string) {
    return db.orders.findOne({ id });
  }
  async save(order: Order) {
    await db.orders.upsert(order);
  }
}

Part 3 of the series sums Onion up in four tenets, and the last one makes a sharp test: "All application core code can be compiled and run separate from infrastructure" (The Onion Architecture, part 3). If your core module won't build without the ORM package, you have folders named after rings and an arrow still pointing outward.

Palermo also gave a warning that people tend to skip. He wrote that this architecture "is not appropriate for small websites" and fits "long-lived business applications as well as applications with complex behavior."

Clean Architecture

Martin's 2012 post, later expanded into a book, draws four circles with firm names. Entities hold enterprise-wide business rules. Use Cases hold application-specific rules: what this particular app does for its users. Interface Adapters convert data between the use cases and outside formats, so controllers, presenters and gateways live there. Frameworks and Drivers is the outer ring with the database, the web framework and the UI toolkit.

He's also clear that four is a sketch. The circles are "schematic," and you may need more. "However, The Dependency Rule always applies."

Clean leans harder than the other two on two things. First, use cases get their own names. Instead of an OrderService with twelve methods, you get PlaceOrder, CancelOrder and RefundOrder, each small enough to find and test by name. Second, it has a rule for what crosses a boundary: "simple data structures," in whatever shape suits the inner circle. Martin's line is "We don't want to cheat and pass Entities or Database rows." That costs you some mapping code. In return, a renamed column in the database doesn't leak into your use cases.

Screaming architecture

In an earlier post, Screaming Architecture, Martin asks for a project layout that tells you what the system does, the way a floor plan tells you you're looking at a house or a library. A use-cases/ folder holding PlaceOrder.ts and RegisterUser.ts tells a new hire what the app is for. Top-level controllers/, models/ and views/ folders only tell them which framework you picked. He adds that you should be able to unit-test those use cases "without any of the frameworks in place."

Mapping the vocabulary

Most of the confusion comes from words. Here are the same concepts in each dialect:

Concept Hexagonal (Cockburn) Onion (Palermo) Clean (Martin)
The core The application inside the hexagon (no named rings) Domain Model at the center Entities
What the app does for users Application logic behind the ports Application services ring Use Cases (each one named)
Translation code Adapters, driving and driven Implementations in the outer ring Interface Adapters
Outermost technology Outside the hexagon: HTTP, DB, queues Outer ring: UI, infrastructure, tests Frameworks and Drivers
The seam Port, owned by the application Interface defined by an inner ring Boundary, crossed by simple data
What it stresses Symmetric ports, testing without real devices, swappable adapters Database at the edge, core that compiles alone, rings inside the core Named use cases, a "screaming" layout, plain data at every boundary
Fits best when You have many integrations and want each adapter replaceable The domain is rich and the system will live for years Several teams need one shared vocabulary and folder layout
On a workshop table, cards for a hexagon, onion rings and clean-architecture circles are laid out as matching labels around the same group of concepts.
Line up the matching parts and the three diagrams start to read like translations of each other.

Where they really differ

The shared rule hides some honest differences that show up once you sit down to write code.

Hexagonal is the most mechanical. It gives you named slots: a driving adapter calls a port, the application handles it, then calls another port that a driven adapter implements. Follow the slots and the structure mostly writes itself. Because both sides are symmetric, the habit that keeps SQL out of the core is the same habit that keeps HTTP details out of it. The trade-off is that Hexagonal says nothing about the inside. One big blob behind well-named ports still counts.

Onion is the most layered. Hexagonal draws one line, inside versus outside. Onion draws several rings inside the core, which helps when the domain is big enough to need its own structure: entities here, domain services that coordinate them there, application services on top. The cost is discipline. Rings are easy to cross when you're in a hurry, so teams that adopt Onion usually enforce it with separate modules or an architecture test such as ArchUnit on the JVM.

Clean is the most prescriptive. The diagram in Martin's post names every piece of a request's trip: controller, input port, interactor, output port, presenter. On a big team that shared vocabulary is gold, because "this crosses the use case boundary" means the same thing to everyone. On a prototype, creating all five pieces for every feature feels like paperwork. The plain-data rule at each boundary also adds mapping code that pays off only once leaking rich objects has become a real problem.

Most real codebases mix all three without saying so: ports and adapters at the edge, Onion-style rings inside the core, Clean-style names for use cases.

Concentric rings: the domain at the center, use cases and services around it, adapters next, frameworks and databases outside. Every dependency arrow points inward. Domain Entities / Model Use Cases / Services Adapters / Interface Adapters Frameworks · Databases · UI · External APIs Every arrow points inward, whichever drawing you use.
All three draw this picture: a domain that knows nothing about technology, rings that add detail on the way out, and every dependency arrow pointing inward. Hexagonal draws it as a hexagon with ports on its sides. Onion and Clean draw circles with named rings. The shape changes and the arrows stay put.

How much of it your team needs

Since the core rule is the same, the real choice is how much structure to add on top of it, and that depends mostly on team size and how long the system will live.

Team and stage Suggested dose Why
Solo or early startup Hexagonal, lightly: one or two ports around the database and the vendor most likely to change. Speed matters more than completeness. Two interfaces buy you fast tests and an exit route. The rest can wait.
Small team, growing Hexagonal or Onion, with a port for every kind of I/O. Slow tests start to hurt and new hires need to find the domain fast. Port names or ring names make the layout readable at a glance.
Several squads Clean vocabulary as the shared contract between teams. Squads trip over each other when boundaries are fuzzy. Named use cases and boundaries give each team a seam it can own.
Large, long-lived system All three together: explicit boundaries, versioned contracts, sometimes two adapters behind one port. Legacy systems and audits reward structure that's written down in code, where people can read it.

Three scenes to make the table concrete:

Say you're four engineers on a payments product. You put two ports in place, PaymentGateway and LedgerRepository, and let everything else call libraries directly. A year later the business switches payment provider. The work is one new adapter class plus one line of wiring, and the core tests don't change.

Say you're forty engineers across five squads. You agree that nothing in the domain folder imports from outside it, and you back that with an architecture test in CI. Now "you're reaching across rings here" is a complete review comment that everyone understands, and the build catches the cases reviewers miss.

Say you're replacing a 15-year-old core system piece by piece, the way Martin Fowler describes in Strangler Fig Application. One port with two adapters, old backend and new backend, lets you move traffic over a slice at a time. This is where Clean's heavier ceremony earns its keep: the boundaries are real interfaces in code, so the cutover is a wiring change.

A team reviews three architecture options laid out on a long table, comparing how much structure suits each team size.
The real choice is how much ceremony your team can carry today. All three agree on the direction of the arrows.
Pick one vocabulary and write it down

The one bad outcome is a team using all three sets of words with no glossary. If half the team says "port" and the other half says "boundary," every review turns into translation. Pick one set, put it in the README and stick to it. The arrows matter more than the names.

Try this week

  • Open three files in your core and read only the imports. Each framework or vendor name you find is an arrow pointing the wrong way.
  • Try Palermo's test: build or run the core module with the infrastructure packages removed. Whatever breaks is your to-do list.
  • Pick one fat service and pull a single method out into a named use case like CancelOrder. See if the folder reads better.
  • Write a five-line glossary for your team: which word you use for port, boundary, adapter and use case.
  • Before adding a new ring or interface, name the change it protects you from. If you can't name one, skip it for now.

All three architectures rely on one mechanism to plug adapters into ports at runtime. The next post in the series covers it: Dependency Injection and Inversion of Control. If you want the rule itself explained without the jargon first, start with Dependency direction in plain language.

What did you think?

Frequently asked questions

Are Clean, Onion and Hexagonal Architecture the same thing?
They share one rule: source code dependencies point inward, toward the business rules, and never out toward frameworks or databases. Robert C. Martin lists Hexagonal and Onion as sources for Clean Architecture and says they all have the same objective. They differ in emphasis and vocabulary.
Which came first: Hexagonal, Onion or Clean Architecture?
Alistair Cockburn published Hexagonal Architecture (Ports and Adapters) in 2005. Jeffrey Palermo described Onion Architecture in a 2008 blog series. Robert C. Martin introduced Clean Architecture in a 2012 blog post and later expanded it into a book.
Is Clean Architecture overkill for a small app?
Often, yes. Palermo himself wrote that Onion Architecture is not appropriate for small websites. For a small app, start with one or two ports around the database and the vendor most likely to change, and add structure when a real change makes you want it.
What is the difference between a port and a boundary?
Mostly vocabulary. A port in Hexagonal Architecture is an interface the application owns for one purposeful conversation, such as storing orders. A boundary in Clean Architecture is the interface at a ring crossing, and Martin adds a rule that only simple data structures cross it.
How can I check that my code follows the dependency rule?
Read the imports of files in your core and look for framework, ORM or vendor names. Try building the core module without infrastructure packages, which is Palermo's own test. On bigger teams, add an architecture test in CI, for example with ArchUnit on the JVM.