Ports & Adapters (Hexagonal Architecture)

Techpapers

In its evolution throughout its history, software development and the different schools of architecture with traction in the community have been solidifying a series of essential pillars when planning applications: maintainability, scalability and flexibility. Without them in mind, the universal tendency for systems to increase in complexity as they grow establishes a more or less defined ceiling beyond which a program could not grow, at the risk of becoming completely ungraspable by a person trying to enter the project, or tremendously fragile to change and therefore impossible to update and scale. 

Figure 1: Alistar Cockburn

One of these architectures that have earned a place as widely known and used patterns beyond the theoretical circuits is that of Ports and Adapters, proposed in 2005 by Alistair Cockburn1, also known for being one of the driving forces behind the Agile2 methodology. The basic idea of this architecture is the decoupling of the application’s core from its input and output mechanisms, allowing for greater modularity and testability. 

InprOTech Guardian, our advanced cybersecurity solution for OT networks, is proprietary software written with these architectural principles at its core. In this article we will explore the fundamentals of this architecture, its structure, advantages, disadvantages and how it is implemented in practice.

 

Origin and Motivation

Alistair Cockburn introduced the Ports and Adapters architecture as an answer to certain typical problems derived from object-oriented development: excessive and/or superfluous dependencies between layers, impossibility of replacing elements adjacent to the application by test or test systems, and filtering of business logic outside its application range. Its main objective was to solve the problems of excessive dependency on external interfaces, which hinders the evolution and maintenance of systems.

Problems in traditional architectures

Traditional architectures often present problems such as: 

  • Strong coupling between business logic and infrastructure layers (databases, graphical interfaces, external APIs). 
  • Difficulty to perform unit tests, since the business logic is intertwined with the infrastructure. 
  • Less flexibility, as any changes to external components directly impact the core of the application. 

 The Ports and Adapters architecture seeks to solve these problems by promoting a clear separation between the core business and the outside world. 

 In their own words3 , the following points are the key to this architecture, its “why”:

Create your application to work without a user interface or database so you can run automated tests against it: 

    – run automated tests against it
    – work when the database is not available
    – be open to implementing new technology
    – connect different applications 
    – protect your code from leaks between business logic and I/O

Figure 2: Alistar’s own architecture diagram

The Hexagon and the understandable confusion with the name

In the 1990s, when Cockburn began flirting with the idea that would eventually become this pattern, he used a hexagon to represent his system. The reason was that a square introduced a very strong idea of up-down-left-right, which he considered a focus problem, but he needed a figure with radial symmetry and facets to represent the application’s points of contact with the outside (although he would not identify these points as the ports until 2004). Although the hexagon had no significance whatsoever, nor was six a special or magic number in this context, the name Cockburn christened the pattern had already curdled by the time he decided that the correct name for the architecture, the one that best captures its essence, is Ports and Adapters. Although the author usually emphasizes which is the best name to clarify this possible confusion, the truth is that he does not deny the name Hexagonal Architecture: his book published in 2024 with the Sevillian Juan Manuel Garrido de Paz on this design is entitled Hexagonal Architecture Explained – How the Ports & Adapters architecture simplifies your life, and how to implement it; and he even sells mugs and T-shirts on his website where the hexagon is the protagonist4.

Illustration 3: Merchandising mug showing the hexagonal logo

Principles of Port and Adapter Architecture

The Ports and Adapters architecture is based on the following fundamental principles: 

  1.     The core of the application is independent of external details: Business logic must be autonomous and not directly dependent on frameworks, databases, APIs or user interfaces. 
  2.     Interaction through “ports”: Ports are interfaces that define how other components can interact with the business logic. 
  3.     Use of “adapters” to connect external interfaces with ports: Adapters translate calls between external components and internal ports.

Port and Adapter Architecture Structure

The architecture is composed of three main elements: 

 Application Core

 The core of the application contains all the business logic and domain rules. It is composed of: 

  • Use cases: represent the actions that the application can perform (e.g., “Register a user”). 
  • Domain entities: Model the core business concepts and contain the validation logic. 
  • Domain services: Contain complex business logic that does not belong to a single entity. 

 This core has no knowledge of the infrastructure, allowing it to be tested in isolation. 

 Ports (Interfaces) 

 Ports act as contracts that define how external components interact with the application core. There are two types of ports: 

  •  Input Ports: interfaces that expose the application’s use cases. They are implemented by drivers or application services. 
  • Output Ports: Interfaces that represent external dependencies such as databases, third-party APIs or messaging systems.

Adapters

Adapters implement ports and handle communication between the kernel and the outside world. They can implement inbound ports (handling external requests such as a REST API or a graphical interface) or outbound ports (communicating with databases, external systems, etc.). 

 It is worth mentioning that a system may not have adapters (or rather, following Cockburn’s usual emphasis on application users over the applications themselves, we might not need adapters).

Relationship to Separation into Layers (Domain, Application and Infrastructure)

Alistair Cockburn es muy explícito en que su diseño solo define la existencia de un “interior” y un “exterior” en la arquitectura de Puertos y Adaptadores y que solo tiene una capa, la propia aplicación. Sin embargo, la simplicidad de este patrón permite acoplarlo a otros diseños, y muchos desarrolladores han adoptado una separación en tres capas, de más a menos externas:

  • Infrastructure: Implements connectivity with databases, messaging systems, external APIs, etc.
  • Application: Orchestrate use cases, defining how they should be executed.
  • Domain: Contains pure business rules and core entities.
Figure 4: Typical separation into the three strata, infrastructure, application, and domain.

The relationship between these three layers is unidirectional, so that the inner layers can only communicate with the layers that contain them.

This separation draws directly from other paradigms such as Eric Evans’ Domain-Driven Design (DDD)5, Robert C. Martin’s Clean Architecuture6, and Onion Architecture7.

In many cases, and apparently contrary to the author’s consideration, this separation into three layers of infrastructure, application and domain is a de facto part of Architecture.

My_project/
│── src/
│   ├── application/
│   │   ├── ports.py
│   ├── domain/
│   │   ├── model.py
│   │   ├── services.py
│   ├── infrastructure/
│   │   ├── persistence.py
│   │   ├── api.py
│   ├── configuration/

Benefits of Ports and Adapters Architecture

  • Decoupling: Business logic is not dependent on external infrastructure, allowing changes to the database or interface without affecting the core.
  • Stability: Because the kernel is independent, unit tests can be performed without the need to configure databases or other external dependencies.
  • Flexibility and maintainability: Adapters can be easily replaced to support new technologies or integrate new external services.
  • Scalability: It allows the system to be divided into more manageable and reusable modules.

Challenges

  • Increased initial complexity: Separation into ports and adapters requires more design and structure compared to simple monolithic architectures.
  • Over-engineering in small applications: This level of abstraction is not always necessary if the application is very simple.
  • More code and classes: More code needs to be written due to the implementation of interfaces and adapters.

 

The Ports and Adapters architecture is a powerful alternative for designing decoupled, flexible and highly testable systems. Its focus on separating the core business and infrastructure allows applications to be more maintainable in the long term, facilitating the evolution of the system without relying on specific technologies.

Although its implementation requires greater planning and initial structure, the benefits it offers in terms of modularity, scalability and ease of testing justify its adoption in projects seeking robustness and flexibility. In addition, its compatibility with other approaches such as Domain-Driven Design (DDD) and Clean Architecture makes it a versatile choice for complex systems.

However, it is important to assess the context and needs of the project before applying it, as for small or short-term applications, the additional effort may not be justified. Ultimately, understanding the principles behind this architecture and knowing when to apply them is key to building high-quality, sustainable software.

References

1: https://alistair.cockburn.us/hexagonal-architecture

2: https://agilemanifesto.org/

3: https://www.youtube.com/watch?v=k0ykTxw7s0Y [Hexagonal Architecture @Tech Excellence]
4: https://alistaircockburn.com/Everything-else

5: https://itequia.com/en/domain-driven-design-what-is-it-and-how-to-apply-it-in-my-organization/

6: https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html

7: https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

keyboard_arrow_up