CQRS(Command Query Responsibility Segregation)는 읽기(Query)와 쓰기(Command) 모델을 분리하는 아키텍처 패턴이다. 읽기와 쓰기의 요구사항이 다를 때 각각 최적화할 수 있다.
기본 원리
일반 CRUD:
클라이언트 → [단일 모델] → DB
읽기/쓰기가 동일 모델 사용
CQRS:
클라이언트 → Command → [쓰기 모델] → Write DB (정규화)
→ Query → [읽기 모델] → Read DB (비정규화, 캐시)
구현 예시
python
# Command (쓰기)
class CreateOrderCommand:
user_id: int
products: list
total: float
class OrderCommandHandler:
def handle(self, cmd: CreateOrderCommand):
order = Order(user_id=cmd.user_id, ...)
db.save(order)
event_bus.publish(OrderCreatedEvent(order.id))
# Query (읽기)
class GetUserOrdersQuery:
user_id: int
class OrderQueryHandler:
def handle(self, query: GetUserOrdersQuery):
return read_db.get_orders_by_user(query.user_id)
# 읽기 전용 DB (Redis, Elasticsearch 등)
관련 개념
참고문헌
- •Young, G. CQRS Documents
- •Fowler, M. CQRS (martinfowler.com)