Hexagonal Architecture: Ports and Adapters

Hexagonal Architecture: Ports and Adapters
1. The Core: The Hexagon
Inside the hexagon is your "Domain."
- It contains zero references to SQL, zero references to AWS, and zero references to JSON.
- It only contains the pure rules of your business (e.g., "A user must be 18 to sign up").
- The Benefit: You can run your entire business logic in a 1-second test without even having an internet connection.
2. Ports (The Interfaces)
A Port is a hole in the hexagon.
- It's an Interface (Module 111).
UserRepositoryPort: Any tool that can "Save a User" can plug into this port.- The Hexagon doesn't care WHO is on the other side. It just says: "I have an object, please save it."
3. Adapters (The Plugins)
An Adapter is the "Plug" that fits into the Port.
- SQL Adapter: Plugs into the Port and sends data to PostgreSQL.
- In-Memory Adapter: Plugs into the Port and saves data to a simple List (for fast testing).
- The Magic: You can swap the SQL Adapter for a NoSQL Adapter in 5 minutes because the Hexagon at the center doesn't change a single line of code.
4. Driving vs. Driven Actors
- Driving Actors: These start the action (The User, a Cron Job). They plug into the "Input" side of the hexagon.
- Driven Actors: These are used by the hexagon (The Database, The Email Service). They plug into the "Output" side. By separating these, you gain a perfectly symmetrical architecture that is clean and professional.
Frequently Asked Questions
Why is it a Hexagon? It's just a shape to represent that there are many "Sides" to talk to. You could have 2 sides or 20. It's not a literal rule; it's a visual metaphor for "Many connections to one core."
Is this the same as Onion Architecture? Essentially, yes. Both are "Clean Architectures." They both focus on the same rule: Dependencies point inward. The outside tools depend on the code, but the code NEVER depends on the tools.
Key Takeaway
Hexagonal Architecture is the "Ultimate Flexibility." By mastering the isolation of your core logic from your external adapters, you gain the ability to survive any technical shift in the industry. You build a "Business Engine" that is eternal, while the tools you use around it can be swapped like lightbulbs.
Read next: Clean Architecture: The Uncle Bob Way →
Part of the Software Architecture Hub — engineering the core.
