# Architecture Patterns

 

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.

 

**Licence** MIT

 

**Source** wshobson/agents

 [Download zip](<https://delaparra-services.nl/skills/architecture-patterns/download>)   

# 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="alice@example.com", name="Alice"))

    assert response.success
    assert response.user.email == "alice@example.com"
    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="alice@example.com", name="Alice"))
    response = await use_case.execute(CreateUserRequest(email="alice@example.com", 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:

 

- ` references/advanced-patterns.md `

 

## Related Skills

 

- ` 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

 

## Files

 

- ` LICENSE ` 
- ` SKILL.md ` 
- ` SOURCE.md ` 
- ` references/advanced-patterns.md ` 
- ` references/details.md `

 

## Related terms

 

- [Abstract Factory](<https://delaparra-services.nl/knowledge-hub/abstract-factory>) 
- [Abstraction](<https://delaparra-services.nl/knowledge-hub/abstraction>) 
- [Abstraction Level](<https://delaparra-services.nl/knowledge-hub/abstraction-level>) 
- [Adapter](<https://delaparra-services.nl/knowledge-hub/adapter>) 
- [Advice](<https://delaparra-services.nl/knowledge-hub/advice>) 
- [Amdahl's Law](<https://delaparra-services.nl/knowledge-hub/amdahls-law>) 
- [Aspect](<https://delaparra-services.nl/knowledge-hub/aspect>) 
- [Aspect-Oriented Programming (AOP)](<https://delaparra-services.nl/knowledge-hub/aspect-oriented-programming-aop>) 
- [Backtracking](<https://delaparra-services.nl/knowledge-hub/backtracking>) 
- [Builder](<https://delaparra-services.nl/knowledge-hub/builder>) 
- [Call Stack](<https://delaparra-services.nl/knowledge-hub/call-stack>) 
- [Callback](<https://delaparra-services.nl/knowledge-hub/callback>) 
- [Chain of Responsibility](<https://delaparra-services.nl/knowledge-hub/chain-of-responsibility>) 
- [Chunk](<https://delaparra-services.nl/knowledge-hub/chunk>) 
- [Class](<https://delaparra-services.nl/knowledge-hub/class>) 
- [Clone](<https://delaparra-services.nl/knowledge-hub/clone>) 
- [Code Generation](<https://delaparra-services.nl/knowledge-hub/code-generation>) 
- [Command](<https://delaparra-services.nl/knowledge-hub/command>) 
- [Composite](<https://delaparra-services.nl/knowledge-hub/composite>) 
- [Constraint](<https://delaparra-services.nl/knowledge-hub/constraint>) 
- [Constraint Programming](<https://delaparra-services.nl/knowledge-hub/constraint-programming>) 
- [Data as Data](<https://delaparra-services.nl/knowledge-hub/data-as-data>) 
- [Data-Oriented Programming](<https://delaparra-services.nl/knowledge-hub/data-oriented-programming>) 
- [Dataflow Programming](<https://delaparra-services.nl/knowledge-hub/dataflow-programming>) 
- [Declarative](<https://delaparra-services.nl/knowledge-hub/declarative>) 
- [Declarative vs. Imperative](<https://delaparra-services.nl/knowledge-hub/declarative-vs-imperative>) 
- [Decorator](<https://delaparra-services.nl/knowledge-hub/decorator>) 
- [Decorator / Annotation](<https://delaparra-services.nl/knowledge-hub/decorator-annotation>) 
- [Decoupled Functions](<https://delaparra-services.nl/knowledge-hub/decoupled-functions>) 
- [Delegation](<https://delaparra-services.nl/knowledge-hub/delegation>) 
- [Dependency injection](<https://delaparra-services.nl/knowledge-hub/dependency-injection>) 
- [Domain](<https://delaparra-services.nl/knowledge-hub/domain>) 
- [Edge / Channel](<https://delaparra-services.nl/knowledge-hub/edge-channel>) 
- [Encapsulation](<https://delaparra-services.nl/knowledge-hub/encapsulation>) 
- [Event](<https://delaparra-services.nl/knowledge-hub/event>) 
- [Event Listener / Handler](<https://delaparra-services.nl/knowledge-hub/event-listener-handler>) 
- [Event-Driven Programming](<https://delaparra-services.nl/knowledge-hub/event-driven-programming>) 
- [Facade](<https://delaparra-services.nl/knowledge-hub/facade>) 
- [Fact](<https://delaparra-services.nl/knowledge-hub/fact>) 
- [Factory Method](<https://delaparra-services.nl/knowledge-hub/factory-method>) 
- [Firing Rule](<https://delaparra-services.nl/knowledge-hub/firing-rule>) 
- [Framework](<https://delaparra-services.nl/knowledge-hub/framework>) 
- [Function](<https://delaparra-services.nl/knowledge-hub/function>) 
- [Functional Programming (FP)](<https://delaparra-services.nl/knowledge-hub/functional-programming-fp>) 
- [Garbage collection](<https://delaparra-services.nl/knowledge-hub/garbage-collection>) 
- [Generic Constraint](<https://delaparra-services.nl/knowledge-hub/generic-constraint>) 
- [Generic Programming](<https://delaparra-services.nl/knowledge-hub/generic-programming>) 
- [Global State](<https://delaparra-services.nl/knowledge-hub/global-state>) 
- [GOTO](<https://delaparra-services.nl/knowledge-hub/goto>) 
- [Heap](<https://delaparra-services.nl/knowledge-hub/heap>) 
- [Higher-Order Function](<https://delaparra-services.nl/knowledge-hub/higher-order-function>) 
- [Homoiconicity](<https://delaparra-services.nl/knowledge-hub/homoiconicity>) 
- [Idempotent](<https://delaparra-services.nl/knowledge-hub/idempotent>) 
- [Immutability](<https://delaparra-services.nl/knowledge-hub/immutability>) 
- [Imperative](<https://delaparra-services.nl/knowledge-hub/imperative>) 
- [Inheritance](<https://delaparra-services.nl/knowledge-hub/inheritance>) 
- [Iteration](<https://delaparra-services.nl/knowledge-hub/iteration>) 
- [Iterator](<https://delaparra-services.nl/knowledge-hub/iterator>) 
- [Join Point](<https://delaparra-services.nl/knowledge-hub/join-point>) 
- [Literate Programming](<https://delaparra-services.nl/knowledge-hub/literate-programming>) 
- [Location Transparency](<https://delaparra-services.nl/knowledge-hub/location-transparency>) 
- [Logic Programming](<https://delaparra-services.nl/knowledge-hub/logic-programming>) 
- [Macro](<https://delaparra-services.nl/knowledge-hub/macro>) 
- [map / filter / reduce](<https://delaparra-services.nl/knowledge-hub/map-filter-reduce>) 
- [Metaprogramming](<https://delaparra-services.nl/knowledge-hub/metaprogramming>) 
- [Middleware](<https://delaparra-services.nl/knowledge-hub/middleware>) 
- [Modular Programming](<https://delaparra-services.nl/knowledge-hub/modular-programming>) 
- [Monomorphization](<https://delaparra-services.nl/knowledge-hub/monomorphization>) 
- [Node / Operator](<https://delaparra-services.nl/knowledge-hub/node-operator>) 
- [Noweb](<https://delaparra-services.nl/knowledge-hub/noweb>) 
- [Null](<https://delaparra-services.nl/knowledge-hub/null>) 
- [Object (Instance)](<https://delaparra-services.nl/knowledge-hub/object-instance>) 
- [Object-Oriented Programming (OOP)](<https://delaparra-services.nl/knowledge-hub/object-oriented-programming-oop>) 
- [Observable](<https://delaparra-services.nl/knowledge-hub/observable>) 
- [Observer](<https://delaparra-services.nl/knowledge-hub/observer>) 
- [Operator](<https://delaparra-services.nl/knowledge-hub/operator>) 
- [Overhead](<https://delaparra-services.nl/knowledge-hub/overhead>) 
- [Pipeline](<https://delaparra-services.nl/knowledge-hub/pipeline-paradigms>) 
- [Pointcut](<https://delaparra-services.nl/knowledge-hub/pointcut>) 
- [Polymorphism](<https://delaparra-services.nl/knowledge-hub/polymorphism>) 
- [Procedural Programming](<https://delaparra-services.nl/knowledge-hub/procedural-programming>) 
- [Procedure / Routine](<https://delaparra-services.nl/knowledge-hub/procedure-routine>) 
- [Propagation](<https://delaparra-services.nl/knowledge-hub/propagation>) 
- [Prototype](<https://delaparra-services.nl/knowledge-hub/prototype-paradigms>) 
- [Prototype](<https://delaparra-services.nl/knowledge-hub/prototype>) 
- [Prototype Chain](<https://delaparra-services.nl/knowledge-hub/prototype-chain>) 
- [Prototype-Based Programming](<https://delaparra-services.nl/knowledge-hub/prototype-based-programming>) 
- [Proxy](<https://delaparra-services.nl/knowledge-hub/proxy>) 
- [Publish / Subscribe (Pub/Sub)](<https://delaparra-services.nl/knowledge-hub/publish-subscribe-pubsub>) 
- [Pure Function](<https://delaparra-services.nl/knowledge-hub/pure-function>) 
- [Query / Goal](<https://delaparra-services.nl/knowledge-hub/query-goal>) 
- [Quote / Eval](<https://delaparra-services.nl/knowledge-hub/quote-eval>) 
- [Reactive Programming](<https://delaparra-services.nl/knowledge-hub/reactive-programming>) 
- [Referential Transparency](<https://delaparra-services.nl/knowledge-hub/referential-transparency>) 
- [Reflection](<https://delaparra-services.nl/knowledge-hub/reflection>) 
- [Rule](<https://delaparra-services.nl/knowledge-hub/rule>) 
- [S-Expression](<https://delaparra-services.nl/knowledge-hub/s-expression>) 
- [Satisfiability](<https://delaparra-services.nl/knowledge-hub/satisfiability>) 
- [Selection](<https://delaparra-services.nl/knowledge-hub/selection>) 
- [Sequence](<https://delaparra-services.nl/knowledge-hub/sequence>) 
- [Side Effects](<https://delaparra-services.nl/knowledge-hub/side-effects>) 
- [SIMD](<https://delaparra-services.nl/knowledge-hub/simd>) 
- [Single Entry / Single Exit](<https://delaparra-services.nl/knowledge-hub/single-entry-single-exit>) 
- [Singleton](<https://delaparra-services.nl/knowledge-hub/singleton>) 
- [Solver](<https://delaparra-services.nl/knowledge-hub/solver>) 
- [Speedup](<https://delaparra-services.nl/knowledge-hub/speedup>) 
- [Stack](<https://delaparra-services.nl/knowledge-hub/stack>) 
- [Stateless](<https://delaparra-services.nl/knowledge-hub/stateless>) 
- [Static](<https://delaparra-services.nl/knowledge-hub/static>) 
- [Strategy](<https://delaparra-services.nl/knowledge-hub/strategy>) 
- [Stream](<https://delaparra-services.nl/knowledge-hub/stream>) 
- [Structure of Arrays](<https://delaparra-services.nl/knowledge-hub/structure-of-arrays>) 
- [Structured Programming](<https://delaparra-services.nl/knowledge-hub/structured-programming>) 
- [Subject](<https://delaparra-services.nl/knowledge-hub/subject>) 
- [Subscription](<https://delaparra-services.nl/knowledge-hub/subscription>) 
- [Symbol](<https://delaparra-services.nl/knowledge-hub/symbol>) 
- [Symbolic Programming](<https://delaparra-services.nl/knowledge-hub/symbolic-programming>) 
- [Tangle](<https://delaparra-services.nl/knowledge-hub/tangle>) 
- [Template Method](<https://delaparra-services.nl/knowledge-hub/template-method>) 
- [Type checking](<https://delaparra-services.nl/knowledge-hub/type-checking>) 
- [Type Erasure](<https://delaparra-services.nl/knowledge-hub/type-erasure>) 
- [Type Parameter](<https://delaparra-services.nl/knowledge-hub/type-parameter>) 
- [Unification](<https://delaparra-services.nl/knowledge-hub/unification>) 
- [Weave](<https://delaparra-services.nl/knowledge-hub/weave>) 
- [Weaving](<https://delaparra-services.nl/knowledge-hub/weaving>)

 

[Installing an agent skill in Claude Code, Codex, Cursor and Copilot](<https://delaparra-services.nl/manuals/een-skill-installeren-in-je-ai-assistent>)

[HTML version](https://delaparra-services.nl/skills/architecture-patterns)
