Community코딩 & 개발github.com

아키텍처 패턴 (Architecture Patterns)

클린 아키텍처, 헥사고날 아키텍처, 도메인 주도 설계 등 검증된 백엔드 아키텍처 패턴을 구현합니다. 새로운 마이크로서비스 설계, 모놀리스 리팩토링, 경계 컨텍스트 분할, 의존성 순환 문제 해결 시 이 스킬을 사용하세요.

아키텍처 패턴 (Architecture Patterns)란 무엇인가요?

이 스킬은 소프트웨어 엔지니어가 유지보수 가능하고 테스트 가능하며 확장 가능한 시스템을 구축할 수 있도록 클린 아키텍처, 헥사고날 아키텍처 및 도메인 주도 설계(DDD)의 핵심 개념과 실제 구현 패턴을 제공합니다. 클린 아키텍처는 의존성 규칙을 통해 프레임워크와 데이터베이스로부터 비즈니스 로직을 분리하며, 헥사고날 아키텍처는 포트와 어댑터 패턴으로 기술 결정을 가장자리로 미룹니다. DDD는 전략적 패턴(경계 컨텍스트, 컨텍스트 매핑, 보편 언어)과 전술적 패턴(엔티티, 값 객체, 애그리게이트, 리포지토리, 도메인 이벤트)을 모두 다룹니다. 또한 인메모리 어댑터를 사용한 유닛 테스트 예제와 함께 일반적인 문제(데이터베이스 의존성, 순환 임포트, 프레임워크 침투 등)에 대한 해결 방법을 제공합니다. Python 기반 예제를 포함하지만 개념은 모든 언어와 프레임워크에 적용 가능합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mianhtsys/landingMod3/tree/HEAD/MODULO_3_DESARROLLO_AL_LADO_DEL_CLIENTE_Y_SERVIDOR_WEB/architecture-skills-framework/.agents/skills/architecture-patterns

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

아키텍처 패턴

클린 아키텍처, 헥사고날 아키텍처, 도메인 주도 설계를 포함한 검증된 백엔드 아키텍처 패턴을 마스터하여 유지보수 가능하고 테스트 가능하며 확장 가능한 시스템을 구축합니다.

주어진 것: 아키텍처를 설계할 서비스 경계 또는 모듈 생성물: 명확한 의존성 규칙, 인터페이스 정의, 테스트 경계를 갖춘 계층 구조

이 스킬을 사용해야 할 때

  • 새로운 백엔드 서비스 또는 마이크로서비스를 처음부터 설계할 때
  • 비즈니스 로직이 ORM 모델이나 HTTP 관련 코드에 얽혀 있는 모놀리식 애플리케이션을 리팩토링할 때
  • 시스템을 여러 서비스로 분할하기 전에 경계 컨텍스트를 설정할 때
  • 인프라 코드가 도메인 계층으로 스며드는 의존성 순환 문제를 디버깅할 때
  • 데이터베이스 없이 실행되는 유스케이스 테스트가 가능한 코드베이스를 만들 때
  • 도메인 주도 설계의 전술적 패턴(애그리게이트, 값 객체, 도메인 이벤트)을 구현할 때

핵심 개념

1. 클린 아키텍처 (Uncle Bob)

계층 (의존성은 안쪽으로 향함):

  • 엔티티: 핵심 비즈니스 모델, 프레임워크 임포트 없음
  • 유스케이스: 애플리케이션 비즈니스 규칙, 엔티티 조율
  • 인터페이스 어댑터: 컨트롤러, 프리젠터, 게이트웨이 — 유스케이스와 외부 형식 간 변환
  • 프레임워크 및 드라이버: UI, 데이터베이스, 외부 서비스 — 모두 가장 바깥쪽 원

핵심 원칙:

  • 의존성은 안쪽으로만 향함; 안쪽 계층은 바깥쪽 계층에 대해 아무것도 알지 못함
  • 비즈니스 로직은 프레임워크, 데이터베이스, 전달 메커니즘에 독립적임
  • 모든 계층 경계는 추상 인터페이스를 통해 교차됨
  • UI, 데이터베이스 또는 외부 서비스 없이 테스트 가능

2. 헥사고날 아키텍처 (포트와 어댑터)

구성 요소:

  • 도메인 코어: 비즈니스 로직이 위치, 프레임워크 없음
  • 포트: 코어가 외부 세계와 상호작용하는 방식을 정의하는 추상 인터페이스(구동 포트, 구동 포트)
  • 어댑터: 포트의 구체적인 구현체(PostgreSQL 어댑터, Stripe 어댑터, REST 어댑터)

장점:

  • 코어를 건드리지 않고 구현체 교체 가능 (예: PostgreSQL을 DynamoDB로 교체)
  • 테스트에서 인메모리 어댑터 사용 — Docker 불필요
  • 기술 결정을 가장자리로 지연

3. 도메인 주도 설계 (DDD)

전략적 패턴:

  • 경계 컨텍스트: 하나의 하위 도메인에 일관된 모델을 격리; 전체 시스템에서 단일 모델 공유 방지
  • 컨텍스트 매핑: 컨텍스트 간의 관계 정의 (안티코럽션 계층, 공유 커널, 공개 호스트 서비스)
  • 보편 언어: 코드의 모든 용어가 도메인 전문가가 사용하는 용어와 일치

전술적 패턴:

  • 엔티티: 시간이 지남에 따라 변경되는 안정적인 식별자를 가진 객체
  • 값 객체: 속성(이메일, 금액, 주소)으로 식별되는 불변 객체
  • 애그리게이트: 일관성 경계; 외부에서는 루트만 접근 가능
  • 리포지토리: 애그리게이트를 영속화하고 재구성; 저장소 메커니즘을 추상화
  • 도메인 이벤트: 도메인 내부에서 발생한 일을 캡처; 애그리게이트 간 조정에 사용

상세 패턴 및 실제 예제

상세 패턴 문서는 references/details.md에 있습니다. 위 탐색 계층으로 충분하지 않을 때 해당 파일을 읽으십시오.

테스팅 — 인메모리 어댑터

클린 아키텍처가 올바르게 적용되었는지 확인하는 지표는 모든 유스케이스가 실제 데이터베이스나 Docker 없이 일반 유닛 테스트로 실행 가능해야 한다는 점입니다:

# tests/unit/test_create_user.py
import asyncio
from typing import Dict, Optional
from domain.entities.user import User
from domain.interfaces.user_repository import IUserRepository
from use_cases.create_user import CreateUserUseCase, CreateUserRequest


class InMemoryUserRepository(IUserRepository):
    def __init__(self):
        self._store: Dict[str, User] = {}

    async def find_by_id(self, user_id: str) -> Optional[User]:
        return self._store.get(user_id)

    async def find_by_email(self, email: str) -> Optional[User]:
        return next((u for u in self._store.values() if u.email == email), None)

    async def save(self, user: User) -> User:
        self._store[user.id] = user
        return user

    async def delete(self, user_id: str) -> bool:
        return self._store.pop(user_id, None) is not None


async def test_create_user_succeeds():
    repo = InMemoryUserRepository()
    use_case = CreateUserUseCase(user_repository=repo)

    response = await use_case.execute(CreateUserRequest(email="[email protected]", name="Alice"))

    assert response.success
    assert response.user.email == "[email protected]"
    assert response.user.id is not None


async def test_duplicate_email_rejected():
    repo = InMemoryUserRepository()
    use_case = CreateUserUseCase(user_repository=repo)

    await use_case.execute(CreateUserRequest(email="[email protected]", name="Alice"))
    response = await use_case.execute(CreateUserRequest(email="[email protected]", name="Alice2"))

    assert not response.success
    assert "already exists" in response.error

문제 해결

유스케이스 테스트에 실행 중인 데이터베이스가 필요함

비즈니스 로직이 인프라 계층으로 유출된 경우입니다. 모든 데이터베이스 호출을 IRepository 인터페이스 뒤로 이동하고 테스트에서는 인메모리 구현체를 주입하십시오(위 테스팅 섹션 참조). 유스케이스 생성자는 구체적인 클래스가 아닌 추상 포트를 받아야 합니다.

계층 간 순환 임포트

use_cases와 adapters 사이에 ImportError: cannot import name X가 발생하는 일반적인 증상입니다. 이는 유스케이스가 추상 포트 대신 구체적인 어댑터 클래스를 임포트할 때 발생합니다. 규칙을 강제하십시오: use_cases/는 domain/(엔티티 및 인터페이스)에서만 임포트합니다. adapters/ 또는 infrastructure/에서 절대 임포트해서는 안 됩니다.

도메인 엔티티에 프레임워크 데코레이터가 나타남

SQLAlchemy Column() 또는 Pydantic Field() 애노테이션이 도메인 엔티티에 나타나면 엔티티가 더 이상 순수하지 않습니다. adapters/repositories/에 별도의 ORM 모델을 만들고 리포지토리의 _to_entity() 메서드에서 도메인 엔티티로 매핑하십시오.

모든 로직이 컨트롤러에 집중됨

컨트롤러가 HTTP 파싱과 응답 포맷팅 이상으로 성장하면 로직을 유스케이스 클래스로 추출하십시오. 컨트롤러 메서드는 세 가지만 수행해야 합니다: 요청 파싱, 유스케이스 호출, 응답 매핑.

값 객체가 너무 늦게 오류를 발생시킴

__post_init__(Python) 또는 생성자에서 불변 조건을 검증하여 잘못된 Email 또는 Money가 생성되지 않도록 하십시오. 이렇게 하면 잘못된 데이터가 비즈니스 로직 내부가 아닌 경계에서 발견됩니다.

경계 컨텍스트 간 컨텍스트 누출

Order 컨텍스트가 Identity 컨텍스트의 User 엔티티를 임포트하는 경우, 안티코럽션 계층을 도입하십시오. Order 컨텍스트는 자체적인 경량 CustomerId 값 객체를 보유하고 명시적인 인터페이스를 통해서만 Identity 컨텍스트를 호출해야 합니다.

고급 패턴

DDD 경계 컨텍스트 매핑, 전체 멀티 서비스 프로젝트 트리, 안티코럽션 계층 구현, 그리고 양파 아키텍처 비교에 대한 자세한 내용은 다음을 참조하십시오:

관련 스킬

  • microservices-patterns — 모놀리스를 여러 서비스로 분해할 때 이러한 아키텍처 패턴 적용
  • cqrs-implementation — CQRS 명령/쿼리 분리를 위한 구조적 기반으로 클린 아키텍처 사용
  • saga-orchestration — 사가는 잘 정의된 애그리게이트 경계가 필요하며, DDD 전술적 패턴이 이를 제공
  • event-store-design — 애그리게이트에서 생성된 도메인 이벤트가 이벤트 스토어에 직접 공급

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

mianhtsys/landingMod3

Implement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.

mianhtsys/landingMod3

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.

mianhtsys/landingMod3

Diseña y compara alternativas arquitectónicas trazables a RF/RNF sin implementar código.

mianhtsys/landingMod3

Revisión adversarial de la arquitectura contra RF/RNF, detectando contradicciones, cobertura faltante y complejidad innecesaria.

mianhtsys/landingMod3

Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems. Use when implementing auth systems, securing APIs, or debugging security issues.

mianhtsys/landingMod3

>- Generate grounded-and-verified, engine-agnostic database documentation that reaches 100% parity with the real schema. Introspects the LIVE database as ground truth and cross-validates it against ORM models, migrations, generated types, seeds, and application queries, then proves completeness by diffing the docs back against the database. Produces ER diagrams (mermaid), per-table data dictionaries, and a machine-readable schema.json. Works with PostgreSQL, MySQL, SQL Server, and SQLite across any ORM (Prisma, TypeORM, Drizzle, Sequelize, Knex, Django, Rails) or raw SQL. Use when asked to document a database, produce an ERD or data dictionary, write db/schema docs, audit schema drift, or refresh existing DB docs.

mianhtsys/landingMod3

Compara estrategias de persistencia y motores de datos según consistencia, concurrencia, volumen, recuperación y operación.

mianhtsys/landingMod3

Design robust, scalable database schemas for SQL and NoSQL databases. Provides normalization guidelines, indexing strategies, migration patterns, constraint design, and performance optimization. Ensures data integrity, query performance, and maintainable data models.

mianhtsys/landingMod3

Consolida análisis especializados en una recomendación arquitectónica, matriz de decisión, ADR y plan de validación.

mianhtsys/landingMod3

Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.

mianhtsys/landingMod3

Build and maintain web frontends — component architecture, state management, API integration, responsive layout, client-side performance, and frontend testing patterns. Framework agnostic, focused on web frontend implementation. Do not use for backend service implementation, data engineering, or platform infrastructure work.

mianhtsys/landingMod3

Evalúa despliegue, contenedores, escalado, alta disponibilidad, observabilidad, backup, recuperación y CI/CD de forma proporcional.

mianhtsys/landingMod3

Execute read-only SQL queries against multiple Microsoft SQL Server databases. Use when: (1) querying MSSQL/SQL Server databases, (2) exploring database schemas/tables, (3) running SELECT queries for data analysis, (4) checking database contents. Supports multiple database connections with descriptions for intelligent auto-selection. Blocks all write operations (INSERT, UPDATE, DELETE, DROP, etc.) for safety.

mianhtsys/landingMod3

Generate and maintain OpenAPI 3.1 specifications from code, design-first specs, and validation patterns. Use when creating API documentation, generating SDKs, or ensuring API contract compliance.

mianhtsys/landingMod3

PHP 8.0+ development — XAMPP, RESTful APIs, PDO/MySQL/MariaDB, and authentication. Use when building PHP backends, creating API endpoints, configuring XAMPP, or integrating PHP with databases.

mianhtsys/landingMod3

Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features

mianhtsys/landingMod3

Analiza requisitos funcionales y no funcionales, reglas, restricciones, capacidad y ambigüedades antes de seleccionar tecnologías.

mianhtsys/landingMod3

Implement modern responsive layouts using container queries, fluid typography, CSS Grid, and mobile-first breakpoint strategies. Use when building adaptive interfaces, implementing fluid layouts, or creating component-level responsive behavior.

mianhtsys/landingMod3

>- Use when designing or implementing software securely: define security requirements, threat-model a feature, choose secure defaults, design authentication and authorization, handle untrusted data and secrets, evaluate dependencies, design multi-tenant trust boundaries, or review security-sensitive changes. Use for prevention during requirements, design, implementation, and review; not for post-build security assessments or scanning an existing codebase.

mianhtsys/landingMod3

Revisa seguridad arquitectónica, identidad, autorización, secretos, APIs, auditoría, fraude y resiliencia antes de implementar.

관련 스킬