Skip to main content
skill CX Codex

architecture-patterns · secondsky — Claude Code skill: Clean Architecture and DDD

A skill that gives your agent backend architecture templates: Clean Architecture layers, ports and adapters, and Domain-Driven Design building blocks.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add secondsky/claude-skills --skill architecture-patterns -a claude-code
Open on GitHub

What architecture-patterns does

The skill hands your agent a set of backend patterns: Clean Architecture, Hexagonal Architecture and Domain-Driven Design. It walks through the layers (entities, use cases, adapters, infrastructure), the app/domain, app/use_cases, app/adapters, app/infrastructure layout, and Python examples — a User entity with no framework imports, an IUserRepository port built on ABC, and a PostgresUserRepository adapter.

The hexagonal section shows an OrderService domain service that takes payment and notification ports, plus two adapters for them: a real one and a mock for tests. That split pays off when a monolith has become hard to change, because dependencies point inward and business logic stays unaware of the database and HTTP.

Nothing here runs on its own or edits your repo — it is reference material the agent reads while writing code. The examples are Python, so other stacks mean translating the ideas by hand. Worth adding when a team is settling on architecture standards or planning a microservices split.

What it helps with

  • lay out a monolith into layers with inward dependencies
  • hide database access behind a port interface
  • swap a payment gateway for a mock in tests
  • sketch bounded contexts before splitting into services
  • agree on one vocabulary for the domain

Example prompts for the agent

  • design the directory layout for a new backend using Clean Architecture
  • refactor this module: move Postgres access behind a port and add an adapter
  • break this monolith into bounded contexts and show me the context map

How to install architecture-patterns

1Skills CLI (Vercel)

npx skills add secondsky/claude-skills --skill architecture-patterns -a claude-code

2Manually: put the files in place

~/.claude/skills/architecture-patterns/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/architecture-patterns/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about architecture-patterns

How do I install architecture-patterns in Claude?

Run npx skills add secondsky/claude-skills --skill architecture-patterns -a claude-code. The file lands at ~/.claude/skills/architecture-patterns/SKILL.md.

What does architecture-patterns do?

It gives the agent templates for Clean Architecture, Hexagonal Architecture and DDD: layers, ports, adapters, entities and repositories. The agent uses them to write or restructure backend code.

Does the skill need extra libraries?

The skill itself is text with Python examples. Those examples use dataclasses, abc and asyncpg, but the skill installs and runs nothing.

Source text

SKILL.md · MIT
---
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

```python
# domain/entities/user.py
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

# domain/interfaces/user_repository.py
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 def save(self, user: User) -> User:
        pass

# use_cases/create_user.py
from dataclasses import dataclass
import uuid
from datetime import datetime

@dataclass
class CreateUserRequest:
    email: str
    name: str

class CreateUserUseCase:
    """Use case: orchestrates business logic."""

    def __init__(self, user_repository: IUserRepository):
        self.user_repository = user_repository

    async def execute(self, request: CreateUserRequest) -> CreateUserResponse:
        # Business validation
        existing = await self.user_repository.find_by_email(request.email)
        if existing:
            return CreateUserResponse(user=None, success=False, error="Email already exists")

        # Create entity
        user = User(
            id=str(uuid.uuid4()),
            email=request.email,
            name=request.name,
            created_at=datetime.now(),
            is_active=True
        )

        # Persist
        saved_user = await self.user_repository.save(user)
        return CreateUserResponse(user=saved_user, success=True)

# adapters/repositories/postgres_user_repository.py
class PostgresUserRepository(IUserRepository):
    """Adapter: PostgreSQL implementation."""

    def __init__(self, pool):
        self.pool = pool

    async def find_by_id(self, user_id: str) -> Optional[User]:
        async with self.pool.acquire() as conn:
            row = await conn.fetchrow("SELECT * FROM users WHERE id = $1", user_id)
            return self._to_entity(row) if row else None

    async def save(self, user: User) -> User:
        async with self.pool.acquire() as conn:
            await conn.execute(
                """INSERT INTO users (id, email, name, created_at, is_active)
                VALUES ($1, $2, $3, $4, $5)
                ON CONFLICT (id) DO UPDATE SET email = $2, name = $3, is_active = $5""",
                user.id, user.email, user.name, user.created_at, user.is_active
            )
            return user
```

## Hexagonal Architecture Pattern

```python
# Core domain (hexagon center)
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:
        # Business logic
        if not order.is_valid():
            return OrderResult(success=False, error="Invalid order")

        # Use ports (interfaces)
        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)

# Adapters
class StripePaymentAdapter(PaymentGatewayPort):
    """Primary adapter: connects to Stripe API."""
    async def charge(self, amount: Money, customer: str) -> PaymentResult:
        # Implementation

class MockPaymentAdapter(PaymentGatewayPort):
    """Test adapter: no external dependencies."""
    async def charge(self, amount: Money, customer: str) -> PaymentResult:
        return PaymentResult(success=True, transaction_id="mock-123")
```

## Domain-Driven Design Pattern

```python
# Value Objects (immutable)
@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  # cents
    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)

# Entities (with identity)
class Order:
    def __init__(self, id: str, customer: Customer):
        self.id = id
        self.customer = customer
        self.items: List[OrderItem] = []
        self.status = OrderStatus.PENDING
        self._events: List[DomainEvent] = []

    def add_item(self, product: Product, quantity: int):
        item = OrderItem(product, quantity)
        self.items.append(item)
        self._events.append(ItemAddedEvent(self.id, item))

    def submit(self):
        if not self.items:
            raise ValueError("Cannot submit empty order")
        self.status = OrderStatus.SUBMITTED
        self._events.append(OrderSubmittedEvent(self.id))

# Aggregates (consistency boundary)
class Customer:
    def __init__(self, id: str, email: Email):
        self.id = id
        self.email = email
        self._addresses: List[Address] = []

    def add_address(self, address: Address):
        if len(self._addresses) >= 5:
            raise ValueError("Maximum 5 addresses allowed")
        self._addresses.append(address)
```

## Best Practices

1. **Dependency Rule**: Dependencies always point inward
2. **Interface Segregation**: Small, focused interfaces
3. **Business Logic in Domain**: Keep frameworks out of core
4. **Test Independence**: Core testable without infrastructure
5. **Bounded Contexts**: Clear domain boundaries
6. **Ubiquitous Language**: Consistent terminology
7. **Thin Controllers**: Delegate to use cases
8. **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

© secondsky · MIT · secondsky/claude-skills

Similar skills

Everything for Backend and APIs →

architecture-patterns by other authors comes first.

architecture-patterns Seth Hobson Guides backend architecture with Clean Architecture, Hexagonal Architecture, and DDD. Use it when designing a service, untangling a monolith, or tracing dependency cycles. CX Codex 24,144installs architecture-patterns sickn33 Guides backend system design using Clean Architecture, Hexagonal Architecture, and DDD, and assists with monolith decomposition. CX Codex +1 906installs architecture-advisor codewithmukesh Runs a questionnaire on domain, team and system lifetime, then recommends an architecture for your .NET project. Useful before you lay out folders. CX Codex +1 2,800installs clean-architecture giuseppe-trisciuoglio Guides Clean Architecture, hexagonal architecture and DDD patterns in Java 21+ Spring Boot 3.5+ projects. Use it when separating domain code from frameworks or refactoring coupled code. CX Codex +1 4,000installs plan codewithmukesh Builds an architecture-aware implementation plan for .NET work before code changes begin. Use it for changes spanning layers, modules, or architectural decisions. CX Codex +1 2,800installs Python Backend Architecture Review rknall A skill that reviews Python backend architecture: patterns, database, API, security, scalability. Useful when the design doc exists and you want the weak spots found before release. CX Codex +1 503installs architecture-review decebals A skill that reviews a Java project at the macro level: package layout, module boundaries, dependency direction and layering. Useful once a codebase grows past the point where you can hold its structure in your head. CX Codex +1 338installs V3 DDD Architecture ruvnet Splits the claude-flow v3 orchestrator into five bounded contexts and wires them back together through a microkernel and a domain event bus. CX Codex +1 1,100installs

From the same set89

kpi-dashboard-design A skill that guides the agent through KPI dashboard design: metric choice, layout, chart types and status colors. Useful when you build analytics views for leadership. CX Codex +1 507installs bun-sveltekit Tells the agent how to build and run SvelteKit apps on Bun: SSR, adapters, bun:sqlite and file handling. CX Codex +1 499installs progressive-web-app A skill for building installable web apps: manifest, service worker, offline support and an install prompt. CX Codex +1 500installs bun-sqlite A skill that tells your agent how to write bun:sqlite code: queries, prepared statements, transactions and parameters. CX Codex +1 495installs api-rate-limiting A skill that walks you through rate limiting an API with token bucket, sliding window and Redis-backed counters. Useful when you open an endpoint to the public or split access by plan. CX Codex +1 491installs design-system-creation A skill that walks the agent through building a design system: tokens, typography, components and their docs. Useful when UI standards need to be settled before code. CX Codex +1 481installs technical-specification This skill walks the agent through a technical spec template: requirements, architecture, API design, rollout plan, tests and risks. Useful before a feature turns into code. CX Codex +1 470installs mobile-app-testing A skill for testing mobile apps: unit tests, UI automation, E2E and performance. Useful when you need to set up test infrastructure. CX Codex +1 467installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor