Layered, Hexagonal and Clean Architecture: Where the Business Rule Lives and Which Way the Arrows Point
One rule, a refund ticket always goes to a human, traced through three pictures of an app. Layered puts the rule on top of the database; hexagonal and clean flip the arrow so the core owns its ports and the web, database and AI model plug in at the edge.
What you will learn
- Explain why a business rule copied into three places goes wrong
- Draw layered, hexagonal (ports and adapters) and clean architecture and compare their arrows
- Show how the core owning its ports flips the dependency arrow
- Decide when the extra ports are worth their cost
Before you start
- What a web API and a database are
- The Pattern Atlas
Our example is a support-ticket app with an AI assistant that drafts replies. It has one business rule: a refund ticket always goes to a human, even when the AI is sure.
In a lot of apps this rule gets copied around: a check in the web handler, a filter in the SQL query, a sentence in the AI prompt. Then the business changes the rule. You have to find and edit it in three places, and if you miss one, the copies disagree and nobody knows which one is the truth.
So the question for this lesson is simple. Where should the rule sit so there's only one copy, and what is allowed to depend on it? Three famous pictures answer it: layered, hexagonal and clean. No framework needed, just boxes and arrows.
Layered
Most of us learn this one first. Three bands:
- Presentation at the top: your web pages or API.
- Business in the middle: this is where the refund rule goes.
- Data at the bottom, talking to the database.
A request comes in at the top and travels down one layer at a time. Each layer calls only the one below it. It's a good start. It's simple, everyone recognises it, and the rule now has one home.
The catch
Look at the arrows. The business layer depends on the data layer, so the rule sits on top of the database code. If you move to a different database, or the data layer changes its methods, the business layer has to change too. And to test the refund rule you need a database running, because the rule can't run without the layer below it.
To be fair, if you put an interface inside the business layer, you're already halfway to the next picture.
Hexagonal: ports and adapters
Think of flying abroad with your laptop. The wall socket has a different shape, so you buy a travel adapter. Next trip, another socket, another adapter. The laptop never changes. The laptop is the core of your app, the socket shape is a port, and the travel adapter is an adapter.
That's hexagonal architecture, also called ports and adapters, from Alistair Cockburn.
- In the middle, the core: the business logic with the refund rule. No web code, no database code.
- On its edge, the core declares ports. A port is a promise in the core's own words: I need a ticket store, a reply drafter, a notifier.
- On the left, the driving side: things that call the app, like the web API or a test.
- On the right, the driven side: things the app calls, like the database, the AI model and the email service. Each is an adapter that fits a port.
A request comes in through the web API, reaches the core, and the core asks the reply-drafter port for a draft. The AI model adapter answers. The core never knows which model it is.
The arrow flips
This is the one move that makes it work. In layered, the business layer points down at the data layer. In hexagonal, the core draws the port itself, on its own edge. The ticket-store port belongs to the core, so the database adapter now points at the core, not the other way round.
The core owns the port and the adapter plugs into it. If you know the D in SOLID, dependency inversion, this is it at the size of a whole app (the code version is in SOLID in Python).
Swap three adapters
- The team moves to a different AI provider: unplug one AI adapter, plug in another.
- For a quick local run, replace the database with an in-memory store.
- Support staff want a command-line tool next to the web API: one more driving adapter.
Three adapters swapped, and the core with the refund rule didn't change once.
Clean: the rings
Clean architecture, from Robert C. Martin, is the same idea drawn as rings.
- Entities in the centre: the ticket, and rules like the refund rule that would be true in any app the business runs.
- Use cases: open a ticket, triage a ticket, close a ticket. Each is one thing the app does for someone.
- Interface adapters: controllers, gateways and presenters that translate between the use cases and the outside world.
- Frameworks and drivers outside: the web framework, the database, the AI SDK.
One rule governs it all, the dependency rule: dependencies point only inward.
Same idea, three drawings
| Hexagonal | Clean | Layered |
|---|---|---|
| Core | Entities + use cases | Business layer |
| Adapters | Interface adapters + frameworks | Presentation and data layers |
| Arrows point at the core | Arrows point inward | Business points down at data |
Hexagonal and clean are one idea drawn two ways. Layered is the different one, because its arrow still points at the database.
Trace one refund ticket
A customer writes: "I want a refund for order 4471."
- The web controller, out in the adapter ring, receives it and hands it to the triage ticket use case.
- The use case asks the reply-drafter port for a draft. The AI model answers with a nice reply and says it's 97% sure.
- The entity rule runs. It's a refund, so it goes to a human. The AI's confidence doesn't matter here: the AI gives advice, the rule makes the decision.
- The use case saves the ticket through the ticket-store port, routed to the human queue.
One rule, in one place, and it won.
Test the rule without the world
Plug a fake ticket store and a fake AI into the ports. The fake AI always says "approve it, 99% sure". The test runs with no database, no web server and no model call, so it's fast, free and gives the same answer every time. The result is route == "human". The rule holds even against a very confident AI.
The honest cost
None of this is free. More ports means more interfaces, more mapping between layers, and more files to jump between. Think of a slider:
- On the left, an app that's mostly simple forms over one table. Layered is perfectly fine.
- On the right, rich rules and edges that keep changing, like AI providers and models. That's where hexagonal and clean pay for themselves.
A good default: start layered, keep the rules in the business layer, and add a port wherever something on the edge changes. The AI provider is usually the first one. In code, that port often ends up as a set of adapters, as in Adapter and Facade over three LLM providers.
Recap
- Put the business rule in one place, in the middle of the app.
- Layered: the rule still leans on the database. Hexagonal and clean: it doesn't.
- The core owns the ports; the web, the database and the AI model plug in at the edge.
- Pay for ports only where the edge really changes.
- Interview line: business rules in the centre, frameworks are details.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.
