SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Client-Server
  • Monolithic Architecture
  • Microservices
  • Serverless
  • Event-Driven Architecture
  • Peer-to-Peer (P2P)
  • Hexagonal Architecture
  • CQRS
  • Event Sourcing
  • Domain-Driven Design (DDD)
  • Layered (N-Tier) Architecture
  • Containers and Docker
  • Kubernetes Basics
  • Clean Architecture and Modular Monolith
  • Multi-Tenancy
  • Cloud Basics: Regions, Zones and Edge
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Architectural Patterns

Hexagonal Architecture

Keep business rules in the middle and plug the outside world in through ports and adapters.

⏱ 13 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Hexagonal architecture (also called Ports and Adapters) puts your business rules in the middle and keeps every tool (database, web framework, message broker, other APIs) outside, behind small plugs.

  • The core holds the rules of your business. It does not know about HTTP, SQL or any library.
  • A port is an interface that the core owns, such as OrderRepository or PaymentGateway.
  • An adapter is the code that plugs into a port and talks to a real tool, such as PostgresOrderRepository.
  • You can swap or fake any tool without touching the core, so testing and change get much easier.

02Concept: What is it?

Alistair Cockburn introduced this idea in 2005. The aim is simple: keep the important code free from technical details. In many apps the rules ("a customer cannot order more than the stock") are mixed with SQL queries and HTTP code. Then a change in the database or the web framework forces changes in the rules.

In a hexagonal design the application has an inside and an outside. The inside is the core: the domain model (orders, prices, rules) and the use cases ("place an order"). The outside is everything else. They talk through ports.

  • Driving (primary) ports are how the outside calls the core: PlaceOrder. Adapters on this side are controllers, CLI commands, message consumers and tests.
  • Driven (secondary) ports are how the core calls the outside: OrderRepository, SendEmail. Adapters on this side are database code, email clients and HTTP clients.
The core in the middle, adapters around it
🌐REST controller
⌨️CLI command
📥Queue consumer
→↓driving ports
Core (the hexagon)
🧩Use casesPlaceOrder, CancelOrder
📐Domain rulesOrder, Price, Stock
→↓driven ports
🐘SQL repository
✉️Email sender
💳Payment API client
Driving adapters (call us) Core Driven adapters (we call them)
Dependencies point inwards. The core defines the ports. The adapters depend on the core, never the other way round.
🧠The hexagon is only a picture
The six sides mean nothing. The shape just shows that a core can have many ports, not one "top" and one "bottom" as in a layered diagram.

03Real-Life Example

🍵The Lamp and the Wall Sockets
A table lamp does not care where its power comes from. It has a standard plug. In one country the wall has round holes, in another flat ones. You do not rebuild the lamp, you buy a small travel adapter. The lamp is the core. The plug shape is the port. The travel adapter is the adapter. Even a battery pack works, because it also fits the same plug.
Lamp
Hexagonal architecture
The lamp itself
The core: business rules and use cases
The standard plug shape
A port (an interface the core owns)
A travel adapter for a country
An adapter (Postgres, MongoDB, REST...)
Wall socket or battery pack
Real database or in-memory fake for tests
Moving to another country
Changing the database or framework
The lamp does not change
The core does not change
Testing the lamp with a battery
Testing the core with fakes, no database
Placing an order, step by step
🌐REST adapterreads JSON
→↓PlaceOrder
🧩Corechecks rules
→↓OrderRepository
🐘Postgres adapterruns SQL

04Why Do We Need It?

🧪Easy testing
Test the rules with in-memory fakes. No database, no network, tests run in milliseconds.
🔄Swap tools
Move from MySQL to PostgreSQL, or from REST to a queue, by writing one new adapter.
🧠Rules stay clear
A new developer can read the business logic without reading SQL or HTTP code.
⏳Delay decisions
You can start with an in-memory store and pick the real database later.
🛡️Fewer ripple changes
A framework upgrade or a vendor API change stays in one adapter.
🧱Good fit for services
A clean core is easier to split into a microservice later.
Put the rules in the middle, and let the tools plug in from the outside. The tools depend on the rules, never the reverse.

05Where Do We Use It?

🏦Business-heavy services
Banking, insurance, orders and billing, where the rules are complex and last for years.
🧩Domain-Driven Design
Fits well with DDD: the domain model is the core, repositories are driven ports.
🔬Test-first teams
Teams that want fast unit tests of the main logic, without starting servers.
🔌Many ways in
One use case reached by REST, gRPC, a CLI and a queue. Each way is just an adapter.
🧳Migrations
Moving databases or cloud vendors. Only the adapters are rewritten.
🧱Microservices
Each service can use the same inner structure, which keeps services alike.
📝Names you will see
Hexagonal, Ports and Adapters, Onion Architecture and Clean Architecture are close cousins. All say: dependencies point inwards towards the domain.

06Types / Parts / How It Works

The parts

PartWhat it isExample
Domain modelObjects and rules of the business, with no outside importsOrder, Money, Stock, rule: stock cannot go below zero
Use case (application service)One thing a user wants to do. It orchestrates the domain and portsPlaceOrder, CancelOrder
Driving portInterface the outside uses to start a use caseinterface PlaceOrder { execute(cmd) }
Driven portInterface the core needs from the outside, owned by the coreinterface OrderRepository { save(order) }
Driving adapterTurns an outside request into a call on a driving portREST controller, CLI command, queue consumer, test
Driven adapterImplements a driven port with a real toolPostgresOrderRepository, SmtpEmailSender, StripePayments
Layered vs hexagonal: which way do dependencies point?
Classic layers
🖥️Controller
↓
🧩Business logic
↓depends on
🗄️Data access
Hexagonal
🖥️Controller
→↓
🧩Core + ports
←implements
🗄️DB adapter
In a classic layered app the business layer depends on the data layer. In a hexagon the data adapter depends on the core's port.
📝Dependency inversion
The core says "I need something that can save an order", as an interface. The database adapter implements that interface. The arrow of code dependency now points into the core. This is the Dependency Inversion Principle.
VisualizerSwap the database and the way users call the appSwitch between hexagonal and a direct database design, change the database, then see how many core files need edits. Click 'Place an order' to follow the call.
How is the code organised?
Who calls the app? (driving adapter)
Where is data saved? (driven adapter)
🌐REST controllerdriving adapter
→↓port: PlaceOrder
Core (business rules)
🧩PlaceOrderrules, prices, stock
→↓port: OrderRepository
🐘PostgreSQLadapter: PostgresOrderRepository
Core files edited
0
none
New adapter files
0
none
Test without a database?
Yes
use the in-memory adapter
In a hexagon the core only sees ports (interfaces). Try swapping the database or the way users call the app. The core stays the same.

A simplified picture. In a real project the numbers depend on how the code is split, but the direction is always the same: ports keep the rules free from tools.

07How to Use It / Steps / Implementation

Building a hexagonal service

  1. 1
    Start with the domain
    Write the entities and rules in plain code, with no framework imports. Make them pass unit tests first.
  2. 2
    Define use cases
    One class or function for each thing a user does (PlaceOrder). It receives a command and returns a result.
  3. 3
    Write driven ports as interfaces
    List what the core needs: OrderRepository, PaymentGateway, Clock. Name them by the business need, not by the tool (not 'SqlOrderTable').
  4. 4
    Write fakes
    Create in-memory versions of each driven port. Now every use case can be tested without infrastructure.
  5. 5
    Add driving adapters
    A REST controller turns JSON into a command, calls the use case, and turns the result into JSON. Keep it thin.
  6. 6
    Add driven adapters
    Implement the ports with real tools: SQL, HTTP clients, a message broker. Test them with a few integration tests.
  7. 7
    Wire it together at the edge
    Create the adapters and give them to the core in one place (the main function or a DI container). The core never creates its own adapters.
💡Keep it as simple as the problem
A small CRUD app with almost no rules does not need ports for everything. Use this pattern where the rules are the valuable part. Adding ports to code that only copies data between a form and a table is extra work with little gain.
⚠️Do not leak details through a port
A port like findByQuery(sqlString) pushes SQL into the core. A good port speaks the language of the business: findOpenOrdersFor(customer).

08Key Terms to Know

TermMeaning in easy words
Core / domainThe business rules and use cases, free from tools
PortAn interface that defines how the core talks to the outside
AdapterCode that connects a port to a real tool or caller
Driving (primary) sideCallers that start the core: UI, REST, CLI, tests
Driven (secondary) sideThings the core calls: database, email, other APIs
Use caseOne action a user wants to do, such as Place Order
Dependency inversionHigh-level code owns the interface, low-level code implements it
Dependency injectionPassing the adapter into the core from outside, instead of the core creating it
Fake / in-memory adapterA simple stand-in that makes tests fast
Anti-corruption layerAn adapter that translates a messy outside model into your clean one
Composition rootThe one place where adapters are created and connected

09Pros, Cons and Trade-offs

✅ Pros
  • Business rules are easy to test
  • Tools can be replaced with little change
  • Rules stay readable and focused
  • Many entry points reuse the same use cases
  • Pushes teams to name things by business meaning
⚠️ Cons
  • More files, interfaces and mapping code
  • Overkill for simple CRUD apps
  • Beginners may find the indirection hard to follow
  • Mapping between domain objects and database rows costs effort
  • Bad ports can leak details and give a false sense of safety

Trade-offs

ChoiceWe gainWe lose
A port for every toolFull freedom to swap and fakeMore boilerplate and more things to name
Few ports, only where neededLess codeSome tools stay tied to the core
Separate domain and database modelsA clean domain, free from table shapesMapping code in both directions
Shared model for bothLess codeThe core is shaped by the database again
Thin adaptersRules stay in one placeNeed discipline in code reviews
Strict dependency rules (tool-checked)The structure cannot driftSetup time and some rigidity

10Common Problems and Mistakes

Common mistakes

  1. Framework types in the core. If an ORM annotation or an HTTP request object appears in a use case, the core is no longer free.
  2. Ports shaped like the tool. A port that copies the database API is just the database with a different name.
  3. Fat adapters. Business checks hidden in the controller are lost when a second entry point is added.
  4. Interfaces for everything. One-to-one wrappers around every class add noise without any benefit.
  5. The core creating its adapters. Using "new PostgresRepo()" inside a use case brings the dependency back.
  6. Skipping integration tests. Fakes prove the rules. You still need a few tests that run the real adapters.

Things to watch

🕸️Anemic domain
Objects with only data and all logic in services. The hexagon then protects nothing of value.
🗺️Mapping cost
Many copies of the same data (DTO, domain, row). Use mapping only where it pays off.
🧭Where does validation go?
Format checks at the edge, business rules in the core. Decide and write it down.
🔁Transactions
A use case that spans several ports needs a clear place for the transaction boundary.

11Real-World Examples

🏦Banking cores
Teams isolate account rules from the many channels that call them (mobile, branch, partner API).
🛒E-commerce checkout
The checkout rules stay stable while payment providers and shipping partners change often.
🧩Spring and .NET apps
Common in Java and C# teams that follow DDD, with 'port' packages and 'adapter' packages.
🚚Logistics
The same routing rules are used by a web app, a driver app and a batch job.
🔌Cloud migration
Move from an on-premise database to a cloud one by replacing the adapter.
🧪Fast CI
Thousands of rule tests run in seconds because they need no database.
📝Note
The pattern is a way to organise code inside one application. It does not decide if you have one service or many.
Mini case: the same core, three callers and two stores
🌐REST
📥Queue
🧪Tests
→↓
🧩Order corerules + ports
→↓
🐘Postgresproduction
🧠In-memorytests
Everything that changes is on the edges.

12Related Topics to Read Next

Monolithic Architecture→

A hexagonal core can keep a monolith tidy and ready to split.

Microservices→

Each service often uses this layout inside.

CQRS→

Commands and queries can be two driving ports on the same core.

Event-Driven Architecture→

A message consumer is just another driving adapter.

Strangler Fig→

An anti-corruption adapter helps when moving off an old system.

Relational Databases→

The most common thing hidden behind a repository port.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: business core in the middle, tools outside, joined by ports and adapters.
  • ✔Port: an interface the core owns. Adapter: code that plugs into it.
  • ✔Driving: callers (REST, CLI, queue, tests). Driven: things we call (DB, email, APIs).
  • ✔Rule: dependencies point inwards. The core imports no framework or driver.
  • ✔Test: use cases with in-memory fakes, plus a few integration tests for adapters.
  • ✔Wire up: create adapters in one place and inject them (composition root).
  • ✔Skip it: for simple CRUD with few rules. Do not wrap everything.
  • ✔One line: “The rules own the interfaces, the tools plug in.”
← Previous
Peer-to-Peer (P2P)
Next →
CQRS