헥사고날 아키텍처(Hexagonal Architecture, Ports and Adapters)는 비즈니스 로직을 외부 시스템(DB, UI, API)로부터 완전히 격리하는 아키텍처 패턴이다. Alistair Cockburn이 2005년 제안했다.
구조
[UI] [REST API]
↓ ↓
┌──────────────────────────────┐
│ Inbound Adapters (입력) │
├──────────────────────────────┤
│ │
│ 도메인 (핵심 로직) │
│ Port (인터페이스만 알 뿐) │
│ │
├──────────────────────────────┤
│ Outbound Adapters (출력) │
└──────────────────────────────┘
↓ ↓
[DB] [이메일]
포트와 어댑터
- •Port (포트): 도메인이 선언하는 인터페이스
- •Adapter (어댑터): 포트를 구현하는 외부 통합 코드
python
# Port (도메인이 선언)
class UserRepository(ABC):
@abstractmethod
def save(self, user: User): ...
@abstractmethod
def find_by_id(self, id: int) -> User: ...
# Outbound Adapter (DB 구현)
class PostgresUserRepository(UserRepository):
def save(self, user):
# SQL INSERT ...
# Outbound Adapter (테스트용 In-Memory)
class InMemoryUserRepository(UserRepository):
def __init__(self):
self._store: dict[int, User] = {}
def save(self, user):
self._store[user.id] = user
# 도메인 서비스 (포트만 알 뿐, DB를 모름)
class UserService:
def __init__(self, repo: UserRepository):
self.repo = repo
헥사고날 아키텍처, 클린 아키텍처, 어니언 아키텍처는 모두 같은 목표를 가진 변형들이다:
- •도메인을 중심에 배치
- •의존성은 항상 안쪽(도메인)을 향함
- •외부 시스템은 교체 가능
관련 개념