Refactoring to Hexagonal Architecture: A Clean Slate for Ryuu-no-Mi
Refactoring for Resilience
Technical debt is the gravity of software development: if you don't fight it, it eventually grounds your project. In the Ryuu-no-Mi marketplace project, we reached a point where the monolithic organization of our code was slowing down feature iteration. By shifting to a Hexagonal Architecture, we have decoupled our business logic from infrastructure concerns, making the system significantly more maintainable.
Moving to Hexagonal Architecture
Hexagonal Architecture, or the Ports and Adapters pattern, acts like a smart home hub. Just as a hub connects various devices (lights, cameras) without needing to know their internal wiring, our core domain logic now interacts with external services—like databases or message brokers—through defined interfaces rather than direct coupling.
The Core Domain
By separating our domain models from our infrastructure, we ensure that the business rules for the marketplace remain untouched even if we swap out our persistence layer or event bus.
# Example of a clean domain entity
from pydantic import BaseModel
class Product(BaseModel):
id: str
name: str
price: float
Defining Ports
Ports define the "what" without the "how." In our new structure, we define abstract base classes for our repositories to ensure that any data implementation adheres to the contract our business logic expects.
from abc import ABC, abstractmethod
class ProductRepository(ABC):
@abstractmethod
def save(self, product: Product) -> None:
pass
Standardizing Documentation
Architecture is only as good as its documentation. To ensure the team maintains these boundaries, we introduced a suite of docs, including ARCHITECTURE.md and EXTENSION_GUIDE.md, which provide a clear roadmap for adding new entities like reviews or payment processors without polluting the core logic.
Results
This refactoring resulted in a codebase where:
- Infrastructure changes (e.g., swapping SQLite for PostgreSQL) are contained in adapters.
- Testing is simplified because core logic can be tested in isolation using mocks for repositories.
- Onboarding is faster thanks to the standardized project structure and IDE rules.
Next Steps
With the architectural foundation solidified, we are now moving toward implementing full Event Sourcing and CQRS to handle complex marketplace transactions at scale. Use the EXTENSION_GUIDE.md in the repository to contribute your next feature securely.
Generated with Gitvlg.com