skillZs
LIVE SKILL TAGS
>>> LIVE SKILLS INDEX <<<
* OPEN SOURCE *
NO LOGIN, NO TRACKING
REAL INSTALL DATA
← back to all skills
ccheney/robust-skills3.7k installs

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#).

How do I install this agent skill?

npx skills add https://github.com/ccheney/robust-skills --skill clean-ddd-hexagonal
view source ↗

Is this agent skill safe to install?

  • Gen Agent Trust Hubpass

    This skill is a comprehensive architectural guide for Domain-Driven Design (DDD), Clean Architecture, and Hexagonal Architecture. It provides conceptual frameworks, directory structures, and code templates for building maintainable backend services. No security risks or malicious patterns were identified.

  • Socketpass

    No alerts

  • Snykpass

    Risk: LOW · No issues

  • Runlayerpass

    2/8 files flagged

  • ZeroLeakspass

    Score: 93/100 · 2 sections analyzed

What does this agent skill do?

Clean Architecture + DDD + Hexagonal

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

This skill is an opinionated synthesis of several related architecture traditions. It is not a single canonical architecture model. Use the original source that matches the design question you are answering: DDD for domain modeling, Hexagonal Architecture for ports/adapters, Clean Architecture for dependency direction, Onion Architecture for domain-centered layering, and CQRS/Event Sourcing only for specific read/write or temporal requirements.

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.

Pattern Boundaries

PatternPrimary QuestionUse It ForDo Not Treat As
DDDHow do we model a complex business domain?Ubiquitous language, bounded contexts, aggregates, value objectsA folder structure by itself
Hexagonal ArchitectureHow does the application interact with the outside world?Ports, driver adapters, driven adapters, testable application coreA mandate for six sides or one exact package layout
Clean ArchitectureWhich direction should dependencies point?Inward dependency rule, use case boundaries, framework independenceA universal four-folder template
Onion ArchitectureHow do we keep the domain model central?Domain-centered layers and dependency inversionA separate requirement when Clean/Hexagonal already solve the local problem
CQRSDo reads and writes need different models?Bounded contexts with divergent read/write workloadsA default application architecture
Event SourcingDo we need state from a complete event history?Audit, temporal queries, replayable workflowsA persistence default for CRUD systems

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
  • In this architecture style, controllers calling repositories directly instead of application 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)

Sharp edges — the placements LLMs most often get wrong:

CodeLayerWhy
Business invariant ("order needs items to confirm")Domain (entity method)It's a rule, not orchestration
Input format validation (JSON shape, required fields)Adapter (controller/DTO)Protocol concern, not business rule
Transaction begin/commitApplicationUse case = transaction boundary
ORM entity / table modelInfrastructureMap to domain objects; never let ORM entities BE domain entities
Domain ↔ DB mappingInfrastructure (mapper)Persistence detail
Authorization ("is user allowed?")Application (policy) or adapter middlewareDomain stays auth-agnostic; encode role RULES in domain only if they're business rules
Clock, UUID generationPort in domain/application; adapter in infrastructureKeeps domain deterministic and testable
Reacting to a domain eventApplication (event handler)Side effects = orchestration
Query joining many tables for a screenRead model (application interface, infrastructure impl)Don't force it through aggregates

Litmus test for anemic domain models: if an application service reads state out of an entity, decides, then writes state back (if (order.status === 'draft') order.status = 'confirmed'), move that logic into the entity as order.confirm(). Handlers should read like a script: load aggregate → call one behavior method → save → publish.

"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          # DDD 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

Port placement: This skill defaults to a DDD-centered layout where aggregate repository interfaces live beside the aggregate in domain/. A stricter Hexagonal layout may instead put driven ports under application/ports/driven/. Pick one convention per codebase and keep the dependency rule intact.

Presentation layer: Driver adapters (REST/gRPC/CLI) live under infrastructure/ in this default layout. Some codebases lift them into a fourth top-level presentation/ layer instead (references/LAYERS.md shows that variant). Use one home for controllers, not both.

Event publishing: Saving an aggregate and then publishing its events to a broker are two writes; a crash between them silently drops events. When events must reach other services reliably, write them to an outbox table in the same transaction as the aggregate — see the outbox pattern in references/CQRS-EVENTS.md.

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 Use CasesControllers call repositories directly in a use-case architectureRoute through application use cases
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

Read the matching file before doing the task in the left column:

Before you...Read
Write code in any layer, wire dependency injection, or decide 3-layer vs 4-layerreferences/LAYERS.md
Split a system into services/contexts, integrate with a legacy or third-party system (ACL), run Event Stormingreferences/DDD-STRATEGIC.md
Model an entity, value object, aggregate, repository, domain service, or factoryreferences/DDD-TACTICAL.md
Define ports/adapters, name interfaces, or lay out a ports-first structurereferences/HEXAGONAL.md
Add commands/queries, domain vs integration events, outbox, sagas, or evaluate CQRS/Event Sourcingreferences/CQRS-EVENTS.md
Write unit/integration/architecture tests for any layerreferences/TESTING.md
Answer a quick "which pattern/which layer" question without deep-divingreferences/CHEATSHEET.md

Sources

Primary Sources

Primary Pattern References

Implementation Guides

Supplemental Syntheses

Add the canonical catalog link to the repository README so users can inspect current installs and available audits. The publishing guide covers the complete discovery path.

<a href="https://skillzs.dev/skills/ccheney/robust-skills/clean-ddd-hexagonal">View clean-ddd-hexagonal on skillZs</a>