Get the FREE Ultimate OpenClaw Setup Guide →

clean-ddd-hexagonal

npx machina-cli add skill ccheney/robust-skills/clean-ddd-hexagonal --openclaw
Files (1)
SKILL.md
8.6 KB

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

git clone https://github.com/ccheney/robust-skills/blob/main/skills/clean-ddd-hexagonal/SKILL.mdView on GitHub

Overview

Backend architecture that blends domain-driven design (DDD) with Clean Architecture rules and Hexagonal ports/adapters. It focuses on maintainable, testable systems by isolating domain logic from infrastructure and external details. This approach emphasizes inward dependencies and clear boundaries across domain, application, and infrastructure layers.

How This Skill Works

Core business logic lives in the domain layer with aggregates, entities, value objects, and domain events. The application layer coordinates use cases and enforces ports/adapters, while infrastructure implements adapters and repositories. Dependencies flow inward: Infrastructure → Application → Domain, with anti-corruption layers and optional CQRS/event-sourcing where appropriate.

When to Use It

  • Complex business domain with many rules
  • Long-lived system that requires maintainability over years
  • Team of 5+ developers needing clear boundaries and collaboration
  • Multiple entry points (API, CLI, events) or need for interoperability
  • Need to swap infrastructure (DB, message broker) without touching domain logic

Quick Start

  1. Step 1: Map domain aggregates, value objects, and domain events; define core use cases in the application layer
  2. Step 2: Define repository interfaces and driver ports in domain/application layers; implement adapters in infrastructure
  3. Step 3: Wire up use cases, tests, and deploy progressively; validate boundaries with tests that run domain logic without infrastructure

Best Practices

  • Enforce the inward Dependency Rule: Infrastructure depends on Application, which depends on Domain
  • Keep Domain pure: no external I/O or infrastructure dependencies in domain models
  • One aggregate per transaction and use domain events for cross-aggregate consistency
  • Define repository interfaces and ports in domain/application layers; implement adapters in infrastructure
  • Start simple and evolve: avoid full CQRS/ES unless proven necessary; iterate when complexity demands it

Example Use Cases

  • An e-commerce order service with an Order aggregate, domain events, and event-driven workflows
  • A payment processing service using a Transaction aggregate and domain events for reconciliations
  • An inventory service leveraging domain events and a repository abstraction for stock, pricing, and events
  • A logistics service with hexagonal adapters to message brokers and databases, using an outbox pattern
  • A multi-tenant SaaS bounded context with an Anti-Corruption Layer to isolate external systems

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers