Hexagonal Architecture

Ports and Adapters: the application in the middle, every outside thing behind a port. Know the two kinds of port, why the dependency arrows point inward, and how that makes the core testable without a database or a screen.

Overview

Hexagonal Architecture puts the application's logic in the middle and treats everything outside it the same way: the user interface, the database, the message broker, another service, a test. Each of those talks to the core through a port, and a port is served by an adapter that knows one technology. The core knows the ports and nothing else.

Alistair Cockburn described the pattern in 2005 and also calls it Ports and Adapters. His intent sentence is worth learning: the application should be equally drivable by users, programs, automated tests or batch scripts, and be developed and tested in isolation from its eventual run-time devices and databases. The problem it fixes is entanglement, business logic that has HTTP or SQL details mixed into it, so it cannot be tested or reused without those details.

Interviewers use the pattern to check whether you can name the two kinds of port, whether you know which way the dependencies point, and whether you can show the core running in a test with fake adapters. They also like to hear when the pattern is too much for the job.

The shape

Picture the core in the middle, the things that use it on the left, and the things it uses on the right.

Cockburn says the hexagon is not about the number six. It gives room to draw several ports on the edge, and it stops people thinking in one-dimensional layers with the user at the top and the database at the bottom. The only line that matters is inside versus outside.

Five terms carry the whole pattern.

  • Core (the application): the rules and use cases, with no technology in them, such as OrderService.place(order).
  • Port: a purposeful conversation between the core and the outside, expressed as an interface, such as Inventory with reserve(sku, qty).
  • Adapter: a converter between one technology and one port, such as SqlInventory, FakeInventory or a Flask route.
  • Driving (primary) side: the things that start a conversation with the core: the UI, tests, schedulers and other services.
  • Driven (secondary) side: the things the core starts a conversation with: databases, mail and payment providers.

Interview questions

  • What is the difference between a driving port and a driven port?
  • How does Hexagonal Architecture improve testability?
  • How do you enforce the dependency rule in a codebase?
  • How does Hexagonal Architecture relate to Clean Architecture and Onion Architecture?
  • When is Hexagonal Architecture the wrong choice?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio