<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tejas Rawat on Medium]]></title>
        <description><![CDATA[Stories by Tejas Rawat on Medium]]></description>
        <link>https://medium.com/@tejasrawat_82721?source=rss-d3dbd031019------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZOtqwaGnKnoeZtjgEgvIWw@2x.jpeg</url>
            <title>Stories by Tejas Rawat on Medium</title>
            <link>https://medium.com/@tejasrawat_82721?source=rss-d3dbd031019------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:09:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tejasrawat_82721/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hexagonal Architecture (Ports and Adapters) Explained: A Practical Guide from Concept to Code]]></title>
            <link>https://medium.com/@tejasrawat_82721/hexagonal-architecture-ports-and-adapters-explained-a-practical-guide-from-concept-to-code-7903053f38f4?source=rss-d3dbd031019------2</link>
            <guid isPermaLink="false">https://medium.com/p/7903053f38f4</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[ports-and-adapters]]></category>
            <dc:creator><![CDATA[Tejas Rawat]]></dc:creator>
            <pubDate>Sat, 03 May 2025 15:24:57 GMT</pubDate>
            <atom:updated>2025-05-03T15:24:57.892Z</atom:updated>
            <content:encoded><![CDATA[<h3>🏷 Introduction</h3><p>In this article, we’ll explore one of the most practical and powerful architectural styles for backend systems: <a href="https://alistair.cockburn.us/hexagonal-architecture"><strong>Hexagonal Architecture</strong>,</a> also known as <strong>Ports and Adapters</strong>.<br>It’s a modern evolution of traditional layered architecture that shifts the focus to what matters most the <strong>business domain</strong>, not the frameworks, databases, or external tools surrounding it.</p><h3>🏷️ What to expect in this article</h3><p>In this article we’ll stay <strong>language-agnostic</strong>. Whether you’re working in Java, Python, JavaScript, or any other technology stack, the principles remain the same. Here’s what we’ll cover:</p><ol><li>What is <strong>Hexagonal Architecture</strong>?</li><li><strong>Dependency inversion</strong> principle in Hexagonal Architecture</li><li><strong>Data flow</strong> and <strong>dependency flow</strong> in Hexagonal Architecture</li><li><strong>Traditional Layered Architecture</strong> vs Hexagonal Architecture</li><li><strong>When </strong>to Use Hexagonal Architecture</li><li>Conclusion</li></ol><p>We’ll also walk through a real-world example based on a <strong>Java + Spring Boot Task Management Service</strong> project, including its structure, flow, and key architectural decisions, all of which are open-sourced on <a href="https://github.com/TejasRawat/task-management-service">GitHub</a>.</p><p>Ready? Let’s start by breaking down what Hexagonal Architecture is and why it’s worth knowing this architecture style.</p><h3>🏷️ What is Hexagonal Architecture?</h3><p><strong>Hexagonal Architecture</strong> (also known as <strong>Ports and Adapters</strong>) is a software design pattern that structures applications to make the <strong>core domain logic</strong>:</p><ul><li><strong>Isolated</strong> from frameworks, databases, APIs, and UIs</li><li><strong>Testable</strong> and <strong>technology-agnostic</strong></li><li><strong>Adaptable</strong> to change</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UHVOri4QPMuMTwPgqF_AA.jpeg" /><figcaption>Hexagonal architecture | High level (data &amp; dependency flow)</figcaption></figure><h4>Core Concepts</h4><p>📌 <strong>Domain: <br></strong>Contains business rules and core models. Declares interfaces (called <strong>ports</strong>) for input and output</p><p>📌<strong> Ports: <br> • Input ports</strong> define how external actors interact with the domain.<br> • <strong>Output ports</strong> define how the domain communicates with external. systems.</p><p>📌 <strong>Adapters:<br>Input Adapters</strong> (e.g., GraphQL, REST)<br> • Receive queries/commands<br> • Implement the input port<br> • Translate external formats (e.g., DTOs) to domain models<br><strong>Output Adapters</strong> (e.g., MySQL, Elasticsearch)<br> • Connect to external systems<br> • Implement the output port<br> • Translate domain models to entities (e.g., DB rows)</p><h3>️🏷️ Dependency Inversion Principle</h3><p>In Hexagonal architecture:<br>🔖 The <strong>domain </strong>defines<strong> input/output</strong> ports (interfaces) that:<br> • <strong>Accept domain models</strong> as input<br> • <strong>Return domain models</strong> as output</p><p>🔖 <strong>Adapters </strong>interact with these ports:<br> • <strong>Input adapters</strong> (e.g., GraphQL, REST controllers) <strong>call</strong> input ports to invoke business logic<br> • <strong>Output adapters</strong> (e.g., MySQL, Elasticsearch repositories) <strong>implement</strong> output ports to handle external side effects</p><p>This inverts traditional dependencies:</p><blockquote>Instead of the domain depending on external frameworks, <strong>frameworks depend on the domain</strong>.</blockquote><p>💡 <strong>This ensures:<br></strong>• Core domain logic remains isolated and independent<br>• You can <strong>swap technologies</strong> (e.g., databases, UI) without touching business rules</p><h3>️🏷 Data flow and dependency flow in Hexagonal Architecture</h3><p>Let’s break down the data and dependency flow using the example of the <strong>createTask</strong> operation in a <a href="https://github.com/TejasRawat/task-management-service/tree/main/src/main/java/com/example/taskmanagement">task-management-service</a>. The same principles apply to other operations as well.</p><ul><li><strong>createTask</strong> mutation takes <strong>tittle</strong> &amp; <strong>description</strong> as mandatory input field while <strong>dueDate</strong> is optional<br>📣 <strong><em>NOTE:</em></strong><em> This is a basic sample schema for learning Hexagonal Architecture using a simple TODO app. In a real-world TODO application, there would likely be many more fields and operations.</em></li></ul><pre>input CreateTaskDto {<br> title: String!<br> description: String!<br> dueDate: Date<br>}</pre><pre>type Mutation {<br>    createTask(input: CreateTaskDto!): TaskDto!<br>}</pre><pre>type TaskDto {<br>    id: String!<br>    title: String!<br>    description: String!<br>    priority: TaskPriorityDto! (HIGH, MEDIUM, LOW, NONE (default))<br>    status: TaskStatusDto! (CREATED (default), TODO, IN_PROGRESS, DONE)<br>    dueDate: Date<br>    createDate: Instant!<br>}</pre><h4>Package structure:</h4><pre>├── adapters<br>│   ├── in<br>│   │   ├── graphql<br>│   │   │   ├── mapper<br>│   │   │   │   └── TaskGQLMapper.java      : Maps domain to GraphQL DTO<br>│   │   │   ├── mutation<br>│   │   │   │   └── TaskMutation.java       : Calls TaskService<br>│   │   └── rest                            : (Implement later...)<br>│   └── out<br>│       └── repository<br>│           ├── elasticsearch               : (Implement later...)<br>│           └── mysql<br>│               ├── entity<br>│               │   └── TaskMySQLEntity.java<br>│               ├── mapper<br>│               │   └── TaskMySQLMapper.java : Maps MySQL entity to domain<br>│               ├── repository<br>│               │   └── TaskMySQLRepository.java : Implements TaskDBPort.java<br>├── application<br>│   └── TaskServiceImpl.java                : Implements TaskService<br>├── domain<br>│   ├── model<br>│   │   ├── CreateTask.java<br>│   │   ├── Task.java<br>│   └── port<br>│       ├── in<br>│       │   └── TaskService.java            : Task createTask(CreateTask input);<br>│       └── out<br>│           └── TaskDBPort.java             : Task saveTask(Task task);</pre><h4>Package details:</h4><p>📌 <strong>domain:</strong> Owns the core business logic (domain models : CreateTask, Task) and is framework-agnostic, meaning its plain Java classes in this case without any Spring or other framework annotation.</p><p>📌 <strong>ports (Interfaces):</strong><br> • TaskService.java(input port) defines operations the domain exposes to the outside like TaskMutation in this case or TaskController if we implement REST.<br> • TaskDBPort.java(output port) defines how the domain interacts with external systems like databases.</p><p>📌 <strong>adapters:</strong><br> • <strong>input adapters</strong> (e.g., GraphQL) invoke the domain by calling input ports.<br> • <strong>output adapters</strong> (e.g., MySQL repositories) implement output ports to handle persistence or external interaction.</p><p>📌 <strong>application:</strong><br>Coordinates the flow between the input port and output port by implementing business logic TaskServiceImpl.. This layer may include minimal framework-specific code, for example, annotations for <strong>dependency injection</strong> such as @Service in Spring. However, it does <strong>not contain any infrastructure logic (like calling DB directly)</strong>, keeping it close to the domain while enabling practical runtime integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sIrMnoJFuRCZZw_WTUQ9A.jpeg" /><figcaption>Hexagonal architecture | Data flow steps</figcaption></figure><p>By now, we’ve seen how the <strong>Dependency Inversion Principle (DIP)</strong> plays a crucial role in shaping the structure of a Hexagonal Architecture. Let’s unpack this with more clarity.</p><p>In this design:</p><ul><li><strong>Input adapters</strong> (such as GraphQL or REST controllers) <strong>do not contain business logic</strong> themselves. Instead, they delegate work to the domain by calling <strong>input port interfaces</strong> like TaskService.java These ports define the operations the domain exposes (e.g., createTask) and operate entirely on <strong>domain model objects</strong>.</li><li>This separation of concerns means input adapters are <strong>plug-and-play</strong>. For example, if you want to add a REST API alongside GraphQL, you don’t need to duplicate business logic — you just reuse the existing TaskService interface. The only thing new is the adapter code that translates REST requests into domain calls.</li></ul><p>Just like input adapters rely on <strong>input ports</strong> to interact with the domain, <strong>output adapters</strong> work through <strong>output ports</strong> to handle responsibilities such as persistence, messaging, or integrations with external services.</p><p>In our case:</p><ul><li>The <strong>domain layer</strong> defines an output port interface , for example, TaskDBPort.java which abstracts the idea of saving or retrieving a Task without tying it to any specific storage mechanism.</li><li>The <strong>output adapter</strong>, such as a MySQL implementation, <strong>provides the actual behavior</strong> by implementing this interface e.g., TaskMySQLRepository.java. It takes care of ORM mapping, SQL queries, and data source management. This adapter translates domain models into persistence models (like JPA entities) and back.</li></ul><p>This design pattern ensures:</p><ul><li><strong>Isolation of business logic:</strong> The domain doesn’t know or care where the data goes or comes from. It simply calls an interface.</li><li><strong>Plugability:</strong> You can introduce a new data source, such as Elasticsearch or a remote service, by implementing the same output port without touching the domain or application logic.</li><li><strong>Resilience to tech shifts:</strong> If your storage changes (say, from MySQL to MongoDB), only the output adapter needs to change not the core logic.</li></ul><h3>️🏷 Traditional Layered architecture vs Hexagonal architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMb2ogllSdyEVHhVH9-hdg.jpeg" /><figcaption>Hexagonal architecture vs Traditional layered architecture</figcaption></figure><p>While the data flow (<strong>Controller &gt; Service &gt; Repository</strong>) remain the same in both the architecture, the major difference lies in the direction of dependency.</p><p>In a traditional layered architecture, the core business logic depends directly on outer layers like the controller and repository. Let’s break this down with an example:</p><ul><li>TaskController: createTask(CreateTaskRequestDto)</li><li>TaskService: createTask(CreateTaskRequestDto)</li><li>TaskRepository: saveTask(TaskEntity)</li></ul><p>Here’s where tight coupling comes into play:</p><ul><li>The <strong>service layer</strong> depends on specific <strong>DTOs</strong> defined in the <strong>controller</strong> layer (e.g., CreateTaskRequestDto), meaning <strong>changes</strong> in the controller can ripple into the business logic.</li><li>The service also directly <strong>uses repository </strong>implementations or specific ORM entities like <strong>TaskEntity</strong>, tying it to a particular <strong>database</strong> technology or persistence framework.</li><li>Apart from dependency there is framework (Like Spring in case of Java backend) code across the layer.</li></ul><p>This tight coupling makes the system harder to test, evolve, or switch components (e.g., swapping from MySQL to Elasticsearch, REST to GraphQL) without modifying core logic.</p><h3>️🏷 When to use Hexagonal Architecture</h3><p>Hexagonal Architecture introduces a clean separation between core business logic and infrastructure concerns, making systems more modular, testable, and adaptable to change. However, this comes with some added complexity, such as:</p><ul><li>A steeper learning curve due to more structured (and sometimes non-intuitive) package organization.</li><li>Additional transformation logic especially in controllers and repositories to conform to input/output port interfaces.</li></ul><h4>✅ Use Hexagonal Architecture when:</h4><p>📌 <strong>Your application relies on multiple and evolving integration points</strong><br> If your business logic interacts with various external systems (databases, messaging systems, third-party APIs), and you foresee potential changes to any of these, Hexagonal is a great fit. For example:</p><ul><li>Migrating from SQL to NoSQL due to scalability.</li><li>Switching from Kafka to Google Pub/Sub.</li><li>Replacing ServiceNow with Jira as the ticketing system.<br> The architecture allows you to isolate and swap out these integrations with minimal impact to the core business logic.</li></ul><p>📌 <strong>You’re building a large-scale monolith</strong><br> Monoliths often contain <strong>significant business logic</strong> and numerous<strong> integration</strong> points. Here, the clear separation Hexagonal Architecture offers helps manage complexity and improve maintainability.<br> However, in <strong>microservices</strong> , where the scope is narrow and focused on a single business capability the benefits may not outweigh the added complexity. <strong>Changing a database</strong> or <strong>integration</strong> in a small microservice may not justify introducing multiple architectural layers.</p><p>📌 <strong>The application is business-logic heavy, not infrastructure-heavy</strong><br> Hexagonal Architecture shines when your application is centered around complex business rules or workflows. It enables clear encapsulation of those rules, independent of technical choices.<br>On the other hand, if your app is mostly CRUD-heavy with high database read/writes and minimal business logic, layering ports/adapters might be unnecessary overhead. In such cases, keeping things simple may be more pragmatic.</p><h3>️🏷 Conclusion</h3><p>Hexagonal Architecture is a great choice when:</p><ul><li>You need flexibility around infrastructure decisions.</li><li>Your app’s complexity lies in the business domain.</li><li>You want a loosely coupled, testable system that’s resilient to change.</li></ul><p>But it might be <strong>overkill</strong> for:</p><ul><li>Small microservices with limited logic.</li><li>Simple CRUD-based apps that are more infrastructure-driven than domain-driven.</li></ul><h4>Source Code</h4><p><a href="https://github.com/TejasRawat/task-management-service">GitHub - TejasRawat/task-management-service: A Spring Boot application for managing tasks CRUD operations. Supports both GraphQL and REST APIs, with interchangeable database implementations (Elasticsearch and MySQL) to suit different needs. Built with Hexagonal Architecture for flexibility and scalability.</a></p><h4>Resources and related links:</h4><ul><li>Alistair Cockburn’s paper on <a href="https://alistair.cockburn.us/hexagonal-architecture">Hexagonal architecture</a></li><li>Robert C. Martin AKA Uncle Bob’s <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">clean architecture</a></li><li>Jeffery Palermo’s <a href="https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/">onion architecture</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7903053f38f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>