Implement proven backend architecture patterns including

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

Architecture patterns cover

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use…

---
name: architecture-patterns
description: Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.
---

# Architecture Patterns

Master proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design to build maintainable, testable, and scalable systems.

**Given:** a service boundary or module to architect.
**Produces:** layered structure with clear dependency rules, interface definitions, and test boundaries.

## When to Use This Skill

- Designing new backend services or microservices from scratch
- Refactoring monolithic applications where business logic is entangled with ORM models or HTTP concerns
- Establishing bounded contexts before splitting a system into services
- Debugging dependency cycles where infrastructure code bleeds into the domain layer

Overview

Master proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design to build maintainable, testable, and scalable systems.

Manual install (npx, ZIP)
Claude Codenpx skills add wshobson/agents --skill architecture-patterns -g -a claude-code
Claude Code (manual)mkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \ | tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/backend-development/skills/architecture-patterns
Windows (PowerShell)New-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/140ef303021e623147c3/architecture-patterns.zip" -OutFile "$env:TEMP\architecture-patterns.zip"; Expand-Archive "$env:TEMP\architecture-patterns.zip" -DestinationPath "$HOME\.claude\skills" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md7.8 KB
  • references/2 files · 25.7 KB
Read the files here
wshobson/4236bb93 files
SKILL.md
Show the full text165 lines

Architecture Patterns

Master proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design to build maintainable, testable, and scalable systems.

Given: a service boundary or module to architect. Produces: layered structure with clear dependency rules, interface definitions, and test boundaries.

When to Use This Skill

  • Designing new backend services or microservices from scratch
  • Refactoring monolithic applications where business logic is entangled with ORM models or HTTP concerns
  • Establishing bounded contexts before splitting a system into services
  • Debugging dependency cycles where infrastructure code bleeds into the domain layer
  • Creating testable codebases where use-case tests do not require a running database
  • Implementing domain-driven design tactical patterns (aggregates, value objects, domain events)

Core Concepts

1. Clean Architecture (Uncle Bob)

Layers (dependency flows inward):

  • Entities: Core business models, no framework imports
  • Use Cases: Application business rules, orchestrate entities
  • Interface Adapters: Controllers, presenters, gateways — translate between use cases and external formats
  • Frameworks & Drivers: UI, database, external services — all at the outermost ring

Key Principles:

  • Dependencies point inward only; inner layers know nothing about outer layers
  • Business logic is independent of frameworks, databases, and delivery mechanisms
  • Every layer boundary is crossed via an abstract interface
  • Testable without UI, database, or external services
2. Hexagonal Architecture (Ports and Adapters)

Components:

  • Domain Core: Business logic lives here, framework-free
  • Ports: Abstract interfaces that define how the core interacts with the outside world (driving and driven)
  • Adapters: Concrete implementations of ports (PostgreSQL adapter, Stripe adapter, REST adapter)

Benefits:

  • Swap implementations without touching the core (e.g., replace PostgreSQL with DynamoDB)
  • Use in-memory adapters in tests — no Docker required
  • Technology decisions deferred to the edges
3. Domain-Driven Design (DDD)

Strategic Patterns:

  • Bounded Contexts: Isolate a coherent model for one subdomain; avoid sharing a single model across the whole system
  • Context Mapping: Define how contexts relate (Anti-Corruption Layer, Shared Kernel, Open Host Service)
  • Ubiquitous Language: Every term in code matches the term used by domain experts

Tactical Patterns:

  • Entities: Objects with stable identity that change over time
  • Value Objects: Immutable objects identified by their attributes (Email, Money, Address)
  • Aggregates: Consistency boundaries; only the root is accessible from outside
  • Repositories: Persist and reconstitute aggregates; abstract over the storage mechanism
  • Domain Events: Capture things that happened inside the domain; used for cross-aggregate coordination

Detailed patterns and worked examples

Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.

Testing — In-Memory Adapters

The hallmark of correctly applied Clean Architecture is that every use case can be exercised in a plain unit test with no real database, no Docker, and no network:

# 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

Troubleshooting

Use case tests require a running database

Business logic has leaked into the infrastructure layer. Move all database calls behind an IRepository interface and inject an in-memory implementation in tests (see Testing section above). The use case constructor must accept the abstract port, not the concrete class.

Circular imports between layers

A common symptom is ImportError: cannot import name X between use_cases and adapters. This happens when a use case imports a concrete adapter class instead of the abstract port. Enforce the rule: use_cases/ imports only from domain/ (entities and interfaces). It must never import from adapters/ or infrastructure/.

Framework decorators appearing in domain entities

If SQLAlchemy Column() or Pydantic Field() annotations appear on domain entities, the entity is no longer pure. Create a separate ORM model in adapters/repositories/ and map to/from the domain entity in the repository's _to_entity() method.

All logic ending up in controllers

When the controller grows beyond HTTP parsing and response formatting, extract the logic into a use case class. A controller method should do three things only: parse the request, call a use case, map the response.

Value objects raising errors too late

Validate invariants in __post_init__ (Python) or the constructor so an invalid Email or Money cannot be constructed at all. This surfaces bad data at the boundary, not deep inside business logic.

Context bleed across bounded contexts

If the Order context is importing User entities from the Identity context, introduce an Anti-Corruption Layer. The Order context should hold its own lightweight CustomerId value object and only call the Identity context through an explicit interface.

Advanced Patterns

For detailed DDD bounded context mapping, full multi-service project trees, Anti-Corruption Layer implementations, and Onion Architecture comparisons, see:

  • microservices-patterns — Apply these architecture patterns when decomposing a monolith into services
  • cqrs-implementation — Use Clean Architecture as the structural foundation for CQRS command/query separation
  • saga-orchestration — Sagas require well-defined aggregate boundaries, which DDD tactical patterns provide
  • event-store-design — Domain events produced by aggregates feed directly into an event store
1---
2name: architecture-patterns
3description: Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.
4---
5 
6# Architecture Patterns
7 
8Master proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design to build maintainable, testable, and scalable systems.
9 
10**Given:** a service boundary or module to architect.
11**Produces:** layered structure with clear dependency rules, interface definitions, and test boundaries.
12 
13## When to Use This Skill
14 
15- Designing new backend services or microservices from scratch
16- Refactoring monolithic applications where business logic is entangled with ORM models or HTTP concerns
17- Establishing bounded contexts before splitting a system into services
18- Debugging dependency cycles where infrastructure code bleeds into the domain layer
19- Creating testable codebases where use-case tests do not require a running database
20- Implementing domain-driven design tactical patterns (aggregates, value objects, domain events)
21 
22## Core Concepts
23 
24### 1. Clean Architecture (Uncle Bob)
25 
26**Layers (dependency flows inward):**
27 
28- **Entities**: Core business models, no framework imports
29- **Use Cases**: Application business rules, orchestrate entities
30- **Interface Adapters**: Controllers, presenters, gateways — translate between use cases and external formats
31- **Frameworks & Drivers**: UI, database, external services — all at the outermost ring
32 
33**Key Principles:**
34 
35- Dependencies point inward only; inner layers know nothing about outer layers
36- Business logic is independent of frameworks, databases, and delivery mechanisms
37- Every layer boundary is crossed via an abstract interface
38- Testable without UI, database, or external services
39 
40### 2. Hexagonal Architecture (Ports and Adapters)
41 
42**Components:**
43 
44- **Domain Core**: Business logic lives here, framework-free
45- **Ports**: Abstract interfaces that define how the core interacts with the outside world (driving and driven)
46- **Adapters**: Concrete implementations of ports (PostgreSQL adapter, Stripe adapter, REST adapter)
47 
48**Benefits:**
49 
50- Swap implementations without touching the core (e.g., replace PostgreSQL with DynamoDB)
51- Use in-memory adapters in tests — no Docker required
52- Technology decisions deferred to the edges
53 
54### 3. Domain-Driven Design (DDD)
55 
56**Strategic Patterns:**
57 
58- **Bounded Contexts**: Isolate a coherent model for one subdomain; avoid sharing a single model across the whole system
59- **Context Mapping**: Define how contexts relate (Anti-Corruption Layer, Shared Kernel, Open Host Service)
60- **Ubiquitous Language**: Every term in code matches the term used by domain experts
61 
62**Tactical Patterns:**
63 
64- **Entities**: Objects with stable identity that change over time
65- **Value Objects**: Immutable objects identified by their attributes (Email, Money, Address)
66- **Aggregates**: Consistency boundaries; only the root is accessible from outside
67- **Repositories**: Persist and reconstitute aggregates; abstract over the storage mechanism
68- **Domain Events**: Capture things that happened inside the domain; used for cross-aggregate coordination
69 
70## Detailed patterns and worked examples
71 
72Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.
73 
74## Testing — In-Memory Adapters
75 
76The hallmark of correctly applied Clean Architecture is that every use case can be exercised in a plain unit test with no real database, no Docker, and no network:
77 
78```python
79# tests/unit/test_create_user.py
80import asyncio
81from typing import Dict, Optional
82from domain.entities.user import User
83from domain.interfaces.user_repository import IUserRepository
84from use_cases.create_user import CreateUserUseCase, CreateUserRequest
85 
86 
87class InMemoryUserRepository(IUserRepository):
88 def __init__(self):
89 self._store: Dict[str, User] = {}
90 
91 async def find_by_id(self, user_id: str) -> Optional[User]:
92 return self._store.get(user_id)
93 
94 async def find_by_email(self, email: str) -> Optional[User]:
95 return next((u for u in self._store.values() if u.email == email), None)
96 
97 async def save(self, user: User) -> User:
98 self._store[user.id] = user
99 return user
100 
101 async def delete(self, user_id: str) -> bool:
102 return self._store.pop(user_id, None) is not None
103 
104 
105async def test_create_user_succeeds():
106 repo = InMemoryUserRepository()
107 use_case = CreateUserUseCase(user_repository=repo)
108 
109 response = await use_case.execute(CreateUserRequest(email="[email protected]", name="Alice"))
110 
111 assert response.success
112 assert response.user.email == "[email protected]"
113 assert response.user.id is not None
114 
115 
116async def test_duplicate_email_rejected():
117 repo = InMemoryUserRepository()
118 use_case = CreateUserUseCase(user_repository=repo)
119 
120 await use_case.execute(CreateUserRequest(email="[email protected]", name="Alice"))
121 response = await use_case.execute(CreateUserRequest(email="[email protected]", name="Alice2"))
122 
123 assert not response.success
124 assert "already exists" in response.error
125```
126 
127## Troubleshooting
128 
129### Use case tests require a running database
130 
131Business logic has leaked into the infrastructure layer. Move all database calls behind an `IRepository` interface and inject an in-memory implementation in tests (see Testing section above). The use case constructor must accept the abstract port, not the concrete class.
132 
133### Circular imports between layers
134 
135A common symptom is `ImportError: cannot import name X` between `use_cases` and `adapters`. This happens when a use case imports a concrete adapter class instead of the abstract port. Enforce the rule: `use_cases/` imports only from `domain/` (entities and interfaces). It must never import from `adapters/` or `infrastructure/`.
136 
137### Framework decorators appearing in domain entities
138 
139If SQLAlchemy `Column()` or Pydantic `Field()` annotations appear on domain entities, the entity is no longer pure. Create a separate ORM model in `adapters/repositories/` and map to/from the domain entity in the repository's `_to_entity()` method.
140 
141### All logic ending up in controllers
142 
143When the controller grows beyond HTTP parsing and response formatting, extract the logic into a use case class. A controller method should do three things only: parse the request, call a use case, map the response.
144 
145### Value objects raising errors too late
146 
147Validate invariants in `__post_init__` (Python) or the constructor so an invalid `Email` or `Money` cannot be constructed at all. This surfaces bad data at the boundary, not deep inside business logic.
148 
149### Context bleed across bounded contexts
150 
151If the `Order` context is importing `User` entities from the `Identity` context, introduce an Anti-Corruption Layer. The `Order` context should hold its own lightweight `CustomerId` value object and only call the `Identity` context through an explicit interface.
152 
153## Advanced Patterns
154 
155For detailed DDD bounded context mapping, full multi-service project trees, Anti-Corruption Layer implementations, and Onion Architecture comparisons, see:
156 
157- [`references/advanced-patterns.md`](references/advanced-patterns.md)
158 
159## Related Skills
160 
161- `microservices-patterns` — Apply these architecture patterns when decomposing a monolith into services
162- `cqrs-implementation` — Use Clean Architecture as the structural foundation for CQRS command/query separation
163- `saga-orchestration` — Sagas require well-defined aggregate boundaries, which DDD tactical patterns provide
164- `event-store-design` — Domain events produced by aggregates feed directly into an event store
165 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
SkillCreate branded architecture, architecture deltaDiagram designcathrynlavery/diagram-design · by cathrynlaveryCreate branded architecture, architecture delta, IT current-state, flowchart, sequence, state machine, ER/data model, timeline, swimlane, quadrant, radar/spider, polar chart (polar/radial lollipop), loop/flywheel, nested, tree, org chart, layer stack, Venn, pyramid/funnel, treemap and marimekko, heatmap, bar and dumbbell, waterfall, line (slopegraph, ridgeline, streamgraph, bump), Gantt and scatter charts (bubble, beeswarm), high-level, process, medallion, data flow, DP integration, DP security matrix, Sankey, fishbone, Wardley map, kanban, user journey, deployment, dependency graph, UML class, story map, or database schema diagrams as HTML/SVG/PNG, with .drawio, Mermaid, and .excalidraw import, plus lifecycle phase maps, block decomposition trees, and onboarding guidance.★ 43.2k GitHub starsSkillReview a PR against the Pascal architectural rulesReview architecturepascalorg/editor · by pascalorgReview a PR against the Pascal architectural rules — package boundaries (core/viewer/editor/nodes), the registry-driven composition model (def.geometry / def.renderer / def.system), legacy-dispatch regressions, the slots + world-scale-UV convention for new nodes/geometry, hook hygiene (useEditor/useScene/useViewer), and selector performance. Use when the user asks to review a PR, audit a branch, or check that changes respect the codebase's architecture.★ 24.6k GitHub starsSkillCreate and edit draw.io/diagrams.net diagramsDraw.io Architecture StudioAgents365-ai/drawio-skill · by Agents365-aiCreate and edit draw.io/diagrams.net diagrams as editable `.drawio` files. Covers architecture, UML/ERD/sequence, BPMN, network, and swimlane views authored from a description or converted from code, IaC, SQL, and API schemas, plus sync, query, test, review, export, and publish of existing diagrams. Use when the user asks for draw.io/diagrams.net or an editable diagram; prefer Mermaid/PlantUML when diagrams-as-code is enough.★ 9.8k GitHub starsSkillCreate polished dark-themed architecture diagramsArchitecture Diagram SkillCocoon-AI/architecture-diagram-generator · by Cocoon-AICreate polished dark-themed architecture diagrams as self-contained HTML+SVG files. Use when the user asks for system, infrastructure, cloud, security, or network topology diagrams.★ 7.4k GitHub starsSkillThe foundational knowledge distillation pattern for buildingLLM Wiki — Knowledge Distillation PatternAr9av/obsidian-wiki · by Ar9avThe foundational knowledge distillation pattern for building and maintaining an AI-powered Obsidian wiki. Based on Andrej Karpathy's LLM Wiki architecture. Use this skill whenever the user wants to understand the wiki pattern, set up a new knowledge base, or needs guidance on the three-layer architecture (raw sources → wiki → schema). Also use when discussing knowledge management strategy, wiki structure decisions, or how to organize distilled knowledge. This is the "theory" skill — other skills handle specific operations (ingesting, querying, linting).★ 3.5k GitHub starsSkillManage software complexity through deep modulesA Philosophy of Software Design Frameworkwondelai/skills · by wondelaiManage software complexity through deep modules, information hiding, and strategic programming. Use when the user mentions "module design", "API too complex", "shallow class", "complexity budget", "strategic vs tactical", "deep module", "information leakage", "pass-through method", "this code is over-engineered", or "simplify this design". Also trigger when reviewing an interface for simplicity, evaluating whether an abstraction is pulling its weight, deciding whether a comment is worth writing, or choosing between general-purpose and special-purpose approaches. Covers deep vs shallow modules, red flags for complexity, and comments as design documentation. For code quality, see clean-code. For architecture boundaries, see clean-architecture.★ 2.2k GitHub stars

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement 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.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars