clean-ddd-hexagonal

Proactively apply when designing APIs, microservices, or scalable backend structure. Triggers on DDD, Clean Architecture, Hexagonal, ports and adapters, entities, value objects, domain events, CQRS, event sourcing, repository pattern, use cases, onion architecture, outbox pattern, aggregate root, anti-corruption layer. Use when working with domain models, aggregates, repositories, or bounded contexts. Clean Architecture + DDD + Hexagonal patterns for backend services, language-agnostic (Go, Rust, Python, TypeScript, Java, C#).

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "clean-ddd-hexagonal" with this command: npx skills add ccheney/robust-skills/ccheney-robust-skills-clean-ddd-hexagonal

Clean Architecture + DDD + Hexagonal

Backend architecture combining DDD tactical patterns, Clean Architecture dependency rules, and Hexagonal ports/adapters for maintainable, testable systems.

When to Use (and When NOT to)

Use WhenSkip When
Complex business domain with many rulesSimple CRUD, few business rules
Long-lived system (years of maintenance)Prototype, MVP, throwaway code
Team of 5+ developersSolo developer or small team (1-2)
Multiple entry points (API, CLI, events)Single entry point, simple API
Need to swap infrastructure (DB, broker)Fixed infrastructure, unlikely to change
High test coverage requiredQuick scripts, internal tools

Start simple. Evolve complexity only when needed. Most systems don't need full CQRS or Event Sourcing.

CRITICAL: The Dependency Rule

Dependencies point inward only. Outer layers depend on inner layers, never the reverse.

Infrastructure → Application → Domain
   (adapters)     (use cases)    (core)

Violations to catch:

  • Domain importing database/HTTP libraries
  • Controllers calling repositories directly (bypassing use cases)
  • Entities depending on application services

Design validation: "Create your application to work without either a UI or a database" — Alistair Cockburn. If you can run your domain logic from tests with no infrastructure, your boundaries are correct.

Quick Decision Trees

"Where does this code go?"

Where does it go?
├─ Pure business logic, no I/O           → domain/
├─ Orchestrates domain + has side effects → application/
├─ Talks to external systems              → infrastructure/
├─ Defines HOW to interact (interface)    → port (domain or application)
└─ Implements a port                      → adapter (infrastructure)

"Is this an Entity or Value Object?"

Entity or Value Object?
├─ Has unique identity that persists → Entity
├─ Defined only by its attributes    → Value Object
├─ "Is this THE same thing?"         → Entity (identity comparison)
└─ "Does this have the same value?"  → Value Object (structural equality)

"Should this be its own Aggregate?"

Aggregate boundaries?
├─ Must be consistent together in a transaction → Same aggregate
├─ Can be eventually consistent                 → Separate aggregates
├─ Referenced by ID only                        → Separate aggregates
└─ >10 entities in aggregate                    → Split it

Rule: One aggregate per transaction. Cross-aggregate consistency via domain events (eventual consistency).

Directory Structure

src/
├── domain/                    # Core business logic (NO external dependencies)
│   ├── {aggregate}/
│   │   ├── entity              # Aggregate root + child entities
│   │   ├── value_objects       # Immutable value types
│   │   ├── events              # Domain events
│   │   ├── repository          # Repository interface (DRIVEN PORT)
│   │   └── services            # Domain services (stateless logic)
│   └── shared/
│       └── errors              # Domain errors
├── application/               # Use cases / Application services
│   ├── {use-case}/
│   │   ├── command             # Command/Query DTOs
│   │   ├── handler             # Use case implementation
│   │   └── port                # Driver port interface
│   └── shared/
│       └── unit_of_work        # Transaction abstraction
├── infrastructure/            # Adapters (external concerns)
│   ├── persistence/           # Database adapters
│   ├── messaging/             # Message broker adapters
│   ├── http/                  # REST/GraphQL adapters (DRIVER)
│   └── config/
│       └── di                  # Dependency injection / composition root
└── main                        # Bootstrap / entry point

DDD Building Blocks

PatternPurposeLayerKey Rule
EntityIdentity + behaviorDomainEquality by ID
Value ObjectImmutable dataDomainEquality by value, no setters
AggregateConsistency boundaryDomainOnly root is referenced externally
Domain EventRecord of changeDomainPast tense naming (OrderPlaced)
RepositoryPersistence abstractionDomain (port)Per aggregate, not per table
Domain ServiceStateless logicDomainWhen logic doesn't fit an entity
Application ServiceOrchestrationApplicationCoordinates domain + infra

Anti-Patterns (CRITICAL)

Anti-PatternProblemFix
Anemic Domain ModelEntities are data bags, logic in servicesMove behavior INTO entities
Repository per EntityBreaks aggregate boundariesOne repository per AGGREGATE
Leaking InfrastructureDomain imports DB/HTTP libsDomain has ZERO external deps
God AggregateToo many entities, slow transactionsSplit into smaller aggregates
Skipping PortsControllers → Repositories directlyAlways go through application layer
CRUD ThinkingModeling data, not behaviorModel business operations
Premature CQRSAdding complexity before neededStart with simple read/write, evolve
Cross-Aggregate TXMultiple aggregates in one transactionUse domain events for consistency

Implementation Order

  1. Discover the Domain — Event Storming, conversations with domain experts
  2. Model the Domain — Entities, value objects, aggregates (no infra)
  3. Define Ports — Repository interfaces, external service interfaces
  4. Implement Use Cases — Application services coordinating domain
  5. Add Adapters last — HTTP, database, messaging implementations

DDD is collaborative. Modeling sessions with domain experts are as important as the code patterns.

Reference Documentation

FilePurpose
references/LAYERS.mdComplete layer specifications
references/DDD-STRATEGIC.mdBounded contexts, context mapping
references/DDD-TACTICAL.mdEntities, value objects, aggregates (pseudocode)
references/HEXAGONAL.mdPorts, adapters, naming
references/CQRS-EVENTS.mdCommand/query separation, events
references/TESTING.mdUnit, integration, architecture tests
references/CHEATSHEET.mdQuick decision guide

Sources

Primary Sources

Pattern References

Implementation Guides

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

General

postgres-drizzle

No summary provided by upstream source.

Repository SourceNeeds Review
General

mermaid-diagrams

No summary provided by upstream source.

Repository SourceNeeds Review
General

feature-slicing

No summary provided by upstream source.

Repository SourceNeeds Review
General

modern-javascript

No summary provided by upstream source.

Repository SourceNeeds Review