| name | architecture-patterns |
| description | Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use when architecting complex backend systems or refactoring existing applications for better maintainability. |
| license | MIT |
Architecture Patterns
Master proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design to build maintainable, testable, and scalable systems.
When to Use This Skill
- Designing new backend systems from scratch
- Refactoring monolithic applications for better maintainability
- Establishing architecture standards for your team
- Migrating from tightly coupled to loosely coupled architectures
- Implementing domain-driven design principles
- Creating testable and mockable codebases
- Planning microservices decomposition
Core Concepts
1. Clean Architecture (Uncle Bob)
Layers (dependency flows inward):
- Entities: Core business models
- Use Cases: Application business rules
- Interface Adapters: Controllers, presenters, gateways
- Frameworks & Drivers: UI, database, external services
Key Principles:
- Dependencies point inward
- Inner layers know nothing about outer layers
- Business logic independent of frameworks
- Testable without UI, database, or external services
2. Hexagonal Architecture (Ports and Adapters)
Components:
- Domain Core: Business logic
- Ports: Interfaces defining interactions
- Adapters: Implementations of ports (database, REST, message queue)
Benefits:
- Swap implementations easily (mock for testing)
- Technology-agnostic core
- Clear separation of concerns
3. Domain-Driven Design (DDD)
Strategic Patterns:
- Bounded Contexts: Separate models for different domains
- Context Mapping: How contexts relate
- Ubiquitous Language: Shared terminology
Tactical Patterns:
- Entities: Objects with identity
- Value Objects: Immutable objects defined by attributes
- Aggregates: Consistency boundaries
- Repositories: Data access abstraction
- Domain Events: Things that happened
Clean Architecture Pattern
Directory Structure
app/
├── domain/ # Entities & business rules
│ ├── entities/
│ ├── value_objects/
│ └── interfaces/ # Abstract interfaces
├── use_cases/ # Application business rules
├── adapters/ # Interface implementations
│ ├── repositories/
│ ├── controllers/
│ └── gateways/
└── infrastructure/ # Framework & external concerns
Implementation Example
from dataclasses import dataclass
from datetime import datetime
@dataclass
class User:
"""Core user entity - no framework dependencies."""
id: str
email: str
name: str
created_at: datetime
is_active: bool = True
def deactivate(self):
"""Business rule: deactivating user."""
self.is_active = False
def can_place_order(self) -> bool:
"""Business rule: active users can order."""
return self.is_active
from abc import ABC, abstractmethod
from typing import Optional
class IUserRepository(ABC):
"""Port: defines contract, no implementation."""
@abstractmethod
async def find_by_id(self, user_id: str) -> Optional[User]:
pass
@abstractmethod
async () -> User:
dataclasses dataclass
uuid
datetime datetime
:
email:
name:
:
():
.user_repository = user_repository
() -> CreateUserResponse:
existing = .user_repository.find_by_email(request.email)
existing:
CreateUserResponse(user=, success=, error=)
user = User(
=(uuid.uuid4()),
email=request.email,
name=request.name,
created_at=datetime.now(),
is_active=
)
saved_user = .user_repository.save(user)
CreateUserResponse(user=saved_user, success=)
():
():
.pool = pool
() -> [User]:
.pool.acquire() conn:
row = conn.fetchrow(, user_id)
._to_entity(row) row
() -> User:
.pool.acquire() conn:
conn.execute(
,
user., user.email, user.name, user.created_at, user.is_active
)
user
Hexagonal Architecture Pattern
class OrderService:
"""Domain service - no infrastructure dependencies."""
def __init__(
self,
order_repository: OrderRepositoryPort,
payment_gateway: PaymentGatewayPort,
notification_service: NotificationPort
):
self.orders = order_repository
self.payments = payment_gateway
self.notifications = notification_service
async def place_order(self, order: Order) -> OrderResult:
if not order.is_valid():
return OrderResult(success=False, error="Invalid order")
payment = await self.payments.charge(amount=order.total, customer=order.customer_id)
if not payment.success:
return OrderResult(success=False, error="Payment failed")
order.mark_as_paid()
saved_order = await self.orders.save(order)
await self.notifications.send(
to=order.customer_email,
subject="Order confirmed",
body=f"Order {order.id} confirmed"
)
return OrderResult(success=True, order=saved_order)
class ():
() -> PaymentResult:
():
() -> PaymentResult:
PaymentResult(success=, transaction_id=)
Domain-Driven Design Pattern
@dataclass(frozen=True)
class Email:
value: str
def __post_init__(self):
if "@" not in self.value:
raise ValueError("Invalid email")
@dataclass(frozen=True)
class Money:
amount: int
currency: str
def add(self, other: "Money") -> "Money":
if self.currency != other.currency:
raise ValueError("Currency mismatch")
return Money(self.amount + other.amount, self.currency)
class Order:
def __init__(self, id: str, customer: Customer):
self.id = id
self.customer = customer
self.items: List[OrderItem] = []
.status = OrderStatus.PENDING
._events: [DomainEvent] = []
():
item = OrderItem(product, quantity)
.items.append(item)
._events.append(ItemAddedEvent(., item))
():
.items:
ValueError()
.status = OrderStatus.SUBMITTED
._events.append(OrderSubmittedEvent(.))
:
():
. =
.email = email
._addresses: [Address] = []
():
(._addresses) >= :
ValueError()
._addresses.append(address)
Best Practices
- Dependency Rule: Dependencies always point inward
- Interface Segregation: Small, focused interfaces
- Business Logic in Domain: Keep frameworks out of core
- Test Independence: Core testable without infrastructure
- Bounded Contexts: Clear domain boundaries
- Ubiquitous Language: Consistent terminology
- Thin Controllers: Delegate to use cases
- Rich Domain Models: Behavior with data
Common Pitfalls
- Anemic Domain: Entities with only data, no behavior
- Framework Coupling: Business logic depends on frameworks
- Fat Controllers: Business logic in controllers
- Repository Leakage: Exposing ORM objects
- Missing Abstractions: Concrete dependencies in core
- Over-Engineering: Clean architecture for simple CRUD